Version 1.20.0-dev.6.0
Merge commit '3bdc62bfe3e419d6636e59ff873373fe4d6f05df' into dev
diff --git a/.gitignore b/.gitignore
index f839f5f..d399850 100644
--- a/.gitignore
+++ b/.gitignore
@@ -50,7 +50,6 @@
# Pub generated "packages" directories and files
packages
pubspec.lock
-.packages
# Local pub storage
.pub
diff --git a/.packages b/.packages
new file mode 100644
index 0000000..4dbf1a4
--- /dev/null
+++ b/.packages
@@ -0,0 +1,103 @@
+# Copyright (c) 2016, 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.
+#
+# .package file containing links to all packages in /pkg, and checked out
+# by DEPS into /third_party/pkg and /third_party/pkg_tested.
+# Please update this file if you add a package to DEPS or /pkg
+#
+analysis_server:pkg/analysis_server/lib
+analyzer:pkg/analyzer/lib
+analyzer_cli:pkg/analyzer_cli/lib
+args:third_party/pkg/args/lib
+async:third_party/pkg/async/lib
+async_helper:pkg/async_helper/lib
+barback:third_party/pkg/barback/lib
+bazel_worker:third_party/pkg/bazel_worker/lib
+boolean_selector:third_party/pkg/boolean_selector/lib
+browser:pkg/browser/lib
+charcode:third_party/pkg/charcode/lib
+charted:third_party/observatory_pub_packages/packages/charted/lib
+cli_util:third_party/pkg/cli_util/lib
+code_transformers:third_party/pkg/code_transformers/lib
+collection:third_party/pkg/collection/lib
+compiler:pkg/compiler/lib
+# Compiler is imported as compiler_unsupported so it can work outside the SDK.
+compiler_unsupported:pkg/compiler/lib
+convert:third_party/pkg/convert/lib
+crypto:third_party/pkg/crypto/lib
+csslib:third_party/pkg/csslib/lib
+dart2js_incremental:pkg/dart2js_incremental/lib
+dart2js_info:third_party/pkg/dart2js_info/lib
+dart_messages:pkg/dart_messages/lib
+dart_style:third_party/pkg_tested/dart_style/lib
+dartdoc:third_party/pkg/dartdoc/lib
+dev_compiler:pkg/dev_compiler/lib
+expect:pkg/expect/lib
+fixnum:third_party/pkg/fixnum/lib
+func:third_party/pkg/func/lib
+glob:third_party/pkg/glob/lib
+html:third_party/pkg/html/lib
+http:third_party/pkg/http/lib
+http_multi_server:third_party/pkg/http_multi_server/lib
+http_parser:third_party/pkg/http_parser/lib
+http_throttle:third_party/pkg/http_throttle/lib
+initialize:third_party/pkg/initialize/lib
+intl:third_party/pkg/intl/lib
+isolate:third_party/pkg/isolate/lib
+js:pkg/js/lib
+js_ast:pkg/js_ast/lib
+js_runtime:sdk/lib/_internal/js_runtime/lib
+json_rpc_2:third_party/pkg/json_rpc_2/lib
+kernel:third_party/pkg/kernel/lib
+linter:third_party/pkg/linter/lib
+logging:third_party/pkg/logging/lib
+lookup_map:pkg/lookup_map/lib
+markdown:third_party/pkg/markdown/lib
+matcher:third_party/pkg/matcher/lib
+meta:pkg/meta/lib
+metatest:third_party/pkg/metatest/lib
+microlytics:pkg/microlytics/lib
+mime:third_party/pkg/mime/lib
+mustache4dart:third_party/pkg/mustache4dart/lib
+oauth2:third_party/pkg/oauth2/lib
+observatory:runtime/observatory/lib
+observe:third_party/pkg/observe/lib
+package_config:third_party/pkg_tested/package_config/lib
+package_resolver:third_party/pkg_tested/package_resolver/lib
+path:third_party/pkg/path/lib
+petitparser:third_party/pkg/petitparser/lib
+plugin:third_party/pkg/plugin/lib
+pool:third_party/pkg/pool/lib
+protobuf:third_party/pkg/protobuf/lib
+pub:third_party/pkg/pub/lib
+pub_cache:third_party/pkg/pub_cache/lib
+pub_semver:third_party/pkg/pub_semver/lib
+quiver:third_party/pkg/quiver/lib
+resource:third_party/pkg/resource/lib
+scheduled_test:third_party/pkg/scheduled_test/lib
+sdk_library_metadata:sdk/lib/_internal/sdk_library_metadata/lib
+shelf:third_party/pkg/shelf/lib
+shelf_packages_handler:third_party/pkg/shelf_packages_handler/lib
+shelf_static:third_party/pkg/shelf_static/lib
+shelf_web_socket:third_party/pkg/shelf_web_socket/lib
+smoke:third_party/pkg/smoke/lib
+source_map_stack_trace:third_party/pkg/source_map_stack_trace/lib
+source_maps:third_party/pkg/source_maps/lib
+source_span:third_party/pkg/source_span/lib
+stack_trace:third_party/pkg/stack_trace/lib
+stream_channel:third_party/pkg/stream_channel/lib
+string_scanner:third_party/pkg/string_scanner/lib
+test:third_party/pkg/test/lib
+test_reflective_loader:third_party/pkg/test_reflective_loader/lib
+typed_data:third_party/pkg/typed_data/lib
+typed_mock:pkg/typed_mock/lib
+unittest:third_party/pkg/unittest/lib
+usage:third_party/pkg/usage/lib
+utf:third_party/pkg/utf/lib
+watcher:third_party/pkg/watcher/lib
+web_components:third_party/pkg/web_components/lib
+web_socket_channel:third_party/pkg/web_socket_channel/lib
+when:third_party/pkg/when/lib
+which:third_party/pkg/which/lib
+yaml:third_party/pkg/yaml/lib
diff --git a/.travis.yml b/.travis.yml
index 369488c..1424eaf 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -9,6 +9,8 @@
- $HOME/.nvm
- $HOME/.pub-cache/hosted
- pkg/dev_compiler/node_modules
+addons:
+ firefox: latest
before_install:
# g++4.8.1 setup
- if [ "$CXX" == "g++" ]; then sudo add-apt-repository -y ppa:ubuntu-toolchain-r/test; fi
@@ -58,6 +60,7 @@
- if [[ "$TEST" == node ]]; then ./tool/node_test.sh ; fi
env:
- ANALYZER=master
+ - ANALYZER=master DDC_BROWSERS=Firefox
- ANALYZER=master CXX=g++
- ANALYZER=master CXX=clang++
- TEST=coverage
@@ -65,6 +68,7 @@
matrix:
allow_failures:
- env: TEST=node
+ - env: ANALYZER=master DDC_BROWSERS=Firefox
- env: ANALYZER=master CXX=clang++
notifications:
email:
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 64e4b19..bf984ab 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,21 @@
[article on native extensions](https://www.dartlang.org/articles/dart-vm/native-extensions)
to reflect the VM's improved behavior.
+* Linux builds of the VM will now use the tcmalloc library for memory
+ allocation. This has the advantages of better debugging and profiling support
+ and faster small allocations, with the cost of slightly larger initial memory
+ footprint, and slightly slower large allocations.
+
+* We have improved the way the VM searches for trusted root certificates for
+ secure socket connections on Linux. First, the VM will look for trusted root
+ certificates in standard locations on the file system
+ (/etc/pki/tls/certs/ca-bundle.crt followed by /etc/ssl/certs), and only if
+ these do not exist will it fall back on the builtin trusted root certificates.
+ This behavior can be overridden on Linux with the new flags
+ --root-certs-file and --root-certs-cache. The former is the path to a file
+ containing the trusted root certificates, and the latter is the path to a
+ directory containing root certificate files hashed using `c_rehash`.
+
### Core library changes
* `dart:core`: Remove deprecated `Resource` class.
Use the class in `package:resource` instead.
@@ -21,7 +36,7 @@
* Added `WebSocket.addUtf8Text` to allow sending a pre-encoded text message
without a round-trip UTF-8 conversion.
-## Strong Mode
+### Strong Mode
* Breaking change - it is an error if a generic type parameter cannot be
inferred (SDK issue [26992](https://github.com/dart-lang/sdk/issues/26992)).
@@ -39,6 +54,59 @@
}
```
+* New feature - use `@checked` to override a method and tighten a parameter
+ type (SDK issue [25578](https://github.com/dart-lang/sdk/issues/25578)).
+
+ ```dart
+ import 'package:meta/meta.dart' show checked;
+ class View {
+ addChild(View v) {}
+ }
+ class MyView extends View {
+ // this override is legal, it will check at runtime if we actually
+ // got a MyView.
+ addChild(@checked MyView v) {}
+ }
+ main() {
+ dynamic mv = new MyView();
+ mv.addChild(new View()); // runtime error
+ }
+ ```
+
+* New feature - use `@virtual` to allow field overrides in strong mode
+ (SDK issue [27384](https://github.com/dart-lang/sdk/issues/27384)).
+
+ ```dart
+ import 'package:meta/meta.dart' show virtual;
+ class Base {
+ @virtual int x;
+ }
+ class Derived extends Base {
+ int x;
+
+ // Expose the hidden storage slot:
+ int get superX => super.x;
+ set superX(int v) { super.x = v; }
+ }
+ ```
+
+* Breaking change - infer list and map literals from the context type as well as
+ their values, consistent with generic methods and instance creation
+ (SDK issue [27151](https://github.com/dart-lang/sdk/issues/27151)).
+
+ ```dart
+ import 'dart:async';
+ main() async {
+ var b = new Future<B>.value(new B());
+ var c = new Future<C>.value(new C());
+ var/*infer List<Future<A>>*/ list = [b, c];
+ var/*infer List<A>*/ result = await Future.wait(list);
+ }
+ class A {}
+ class B extends A {}
+ class C extends A {}
+ ```
+
## 1.19.0
### Language changes
diff --git a/DEPS b/DEPS
index e7993ab..16d478c 100644
--- a/DEPS
+++ b/DEPS
@@ -34,6 +34,8 @@
"base_revision": "@672b04e54b937ec899429a6bd5409c5a6300d151",
"buildtools_revision": "@565d04e8741429fb1b4f26d102f2c6c3b849edeb",
+ "gperftools_revision": "@7822b5b0b9fa7e016e1f6b46ea86f26f4691a457",
+
# Revisions of /third_party/* dependencies.
"args_tag": "@0.13.5",
"async_tag": "@1.11.1",
@@ -149,7 +151,7 @@
Var("boringssl_rev"),
Var("dart_root") + "/third_party/root_certificates":
- "https://github.com/dart-lang/root_certificates.git" +
+ (Var("github_mirror") % "root_certificates") +
Var("root_certificates_rev"),
Var("dart_root") + "/third_party/jinja2":
@@ -167,6 +169,10 @@
Var("dart_root") + "/third_party/WebCore":
"https://github.com/dart-lang/webcore.git" + Var("WebCore_rev"),
+ Var("dart_root") + "/third_party/tcmalloc/gperftools":
+ Var('chromium_git') + '/external/github.com/gperftools/gperftools.git' +
+ Var("gperftools_revision"),
+
Var("dart_root") + "/third_party/pkg/args":
(Var("github_mirror") % "args") + Var("args_tag"),
Var("dart_root") + "/third_party/pkg/async":
@@ -185,7 +191,7 @@
Var("dart_root") + "/third_party/pkg/collection":
(Var("github_mirror") % "collection") + Var("collection_tag"),
Var("dart_root") + "/third_party/pkg/convert":
- "https://github.com/dart-lang/convert.git" + Var("convert_tag"),
+ (Var("github_mirror") % "convert") + Var("convert_tag"),
Var("dart_root") + "/third_party/pkg/crypto":
(Var("github_mirror") % "crypto") + Var("crypto_tag"),
Var("dart_root") + "/third_party/pkg/csslib":
@@ -284,7 +290,7 @@
Var("dart_root") + "/third_party/pkg/shelf":
(Var("github_mirror") % "shelf") + Var("shelf_tag"),
Var("dart_root") + "/third_party/pkg/shelf_packages_handler":
- "https://github.com/dart-lang/shelf_packages_handler.git"
+ (Var("github_mirror") % "shelf_packages_handler")
+ Var("shelf_packages_handler_tag"),
Var("dart_root") + "/third_party/pkg/shelf_static":
(Var("github_mirror") % "shelf_static") + Var("shelf_static_tag"),
diff --git a/pkg/BUILD.gn b/pkg/BUILD.gn
index 91a2266..7df856e 100644
--- a/pkg/BUILD.gn
+++ b/pkg/BUILD.gn
@@ -18,15 +18,17 @@
timestamp_file = "$target_gen_dir/packages.stamp"
outputs = [
timestamp_file,
+ "$root_out_dir/.packages",
]
script = "../tools/make_links.py"
args = [
+ "--create-links",
+ "--create-package-file",
"--quiet",
"--timestamp_file",
rebase_path(timestamp_file),
- rebase_path("$root_out_dir/packages"),] +
- inputs +
+ ] + inputs +
# Pub imports dart2js as compiler_unsupported so it can work outside
# the SDK. Map that to the compiler package.
[rebase_path("compiler/lib") + ":compiler_unsupported",]
diff --git a/pkg/analysis_server/benchmark/perf/analysis_timing_tests.dart b/pkg/analysis_server/benchmark/perf/analysis_timing_tests.dart
index 3e3af14..731bec5 100644
--- a/pkg/analysis_server/benchmark/perf/analysis_timing_tests.dart
+++ b/pkg/analysis_server/benchmark/perf/analysis_timing_tests.dart
@@ -44,7 +44,7 @@
test = new SubscriptionTimingTest();
}
- Future.wait([test.test_timing()]);
+ Future.wait(<Future>[test.test_timing()]);
}
const DEFAULT_METRIC = 'analysis';
@@ -94,7 +94,7 @@
/**
* SubscriptionTimingTest measures the time taken by the analysis server to return
- * information for navigation, semantic highlighting, outline, get occurances,
+ * information for navigation, semantic highlighting, outline, get occurrences,
* overrides, folding and implemented. These timings are wrt to the specified priority file
* - the file that is currently opened and has focus in the editor. Measure the time from
* when the client subscribes for the notifications till there is a response from the server.
@@ -103,8 +103,7 @@
class SubscriptionTimingTest extends AbstractTimingTest {
List<Metric> _metrics;
- List<Metric> get metrics =>
- _metrics ??= metricNames.map((name) => getMetric(name)).toList();
+ List<Metric> get metrics => _metrics ??= metricNames.map(getMetric).toList();
Metric getMetric(String name) {
switch (name) {
diff --git a/pkg/analysis_server/lib/plugin/edit/fix/fix_core.dart b/pkg/analysis_server/lib/plugin/edit/fix/fix_core.dart
index aaf2c00..2a563e0 100644
--- a/pkg/analysis_server/lib/plugin/edit/fix/fix_core.dart
+++ b/pkg/analysis_server/lib/plugin/edit/fix/fix_core.dart
@@ -8,9 +8,9 @@
import 'package:analysis_server/plugin/protocol/protocol.dart'
show SourceChange;
+import 'package:analyzer/error/error.dart';
import 'package:analyzer/file_system/file_system.dart';
import 'package:analyzer/src/generated/engine.dart';
-import 'package:analyzer/src/generated/error.dart';
/**
* A description of a single proposed fix for some problem.
diff --git a/pkg/analysis_server/lib/src/edit/edit_domain.dart b/pkg/analysis_server/lib/src/edit/edit_domain.dart
index 83481a9..44e9ea7 100644
--- a/pkg/analysis_server/lib/src/edit/edit_domain.dart
+++ b/pkg/analysis_server/lib/src/edit/edit_domain.dart
@@ -21,9 +21,10 @@
import 'package:analysis_server/src/services/search/search_engine.dart';
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/element/element.dart';
+import 'package:analyzer/error/error.dart' as engine;
import 'package:analyzer/src/dart/scanner/scanner.dart' as engine;
+import 'package:analyzer/src/error/codes.dart' as engine;
import 'package:analyzer/src/generated/engine.dart' as engine;
-import 'package:analyzer/src/generated/error.dart' as engine;
import 'package:analyzer/src/generated/parser.dart' as engine;
import 'package:analyzer/src/generated/source.dart';
import 'package:analyzer/task/dart.dart';
diff --git a/pkg/analysis_server/lib/src/operation/operation_analysis.dart b/pkg/analysis_server/lib/src/operation/operation_analysis.dart
index 9064b71..634ae54 100644
--- a/pkg/analysis_server/lib/src/operation/operation_analysis.dart
+++ b/pkg/analysis_server/lib/src/operation/operation_analysis.dart
@@ -18,8 +18,8 @@
import 'package:analysis_server/src/services/search/search_engine.dart';
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/element/element.dart';
+import 'package:analyzer/error/error.dart';
import 'package:analyzer/src/generated/engine.dart';
-import 'package:analyzer/src/generated/error.dart';
import 'package:analyzer/src/generated/source.dart';
/**
diff --git a/pkg/analysis_server/lib/src/protocol_server.dart b/pkg/analysis_server/lib/src/protocol_server.dart
index 0a00a17..300f7a0 100644
--- a/pkg/analysis_server/lib/src/protocol_server.dart
+++ b/pkg/analysis_server/lib/src/protocol_server.dart
@@ -17,7 +17,8 @@
import 'package:analyzer/source/error_processor.dart';
import 'package:analyzer/src/dart/ast/utilities.dart' as engine;
import 'package:analyzer/src/generated/engine.dart' as engine;
-import 'package:analyzer/src/generated/error.dart' as engine;
+import 'package:analyzer/error/error.dart' as engine;
+import 'package:analyzer/src/error/codes.dart' as engine;
import 'package:analyzer/src/generated/source.dart' as engine;
import 'package:analyzer/src/generated/utilities_dart.dart' as engine;
diff --git a/pkg/analysis_server/lib/src/services/completion/dart/uri_contributor.dart b/pkg/analysis_server/lib/src/services/completion/dart/uri_contributor.dart
index 01176aa..7b99353 100644
--- a/pkg/analysis_server/lib/src/services/completion/dart/uri_contributor.dart
+++ b/pkg/analysis_server/lib/src/services/completion/dart/uri_contributor.dart
@@ -55,11 +55,39 @@
StringLiteral uri = node.uri;
if (uri is SimpleStringLiteral) {
int offset = request.offset;
- if (uri.offset < offset &&
- (offset < uri.end || offset == uri.offset + 1)) {
- // Handle degenerate case where import or export is only line in file
- // and there is no semicolon
- visitSimpleStringLiteral(uri);
+ int start = uri.offset;
+ int end = uri.end;
+ if (offset > start) {
+ if (offset < end) {
+ // Quoted non-empty string
+ visitSimpleStringLiteral(uri);
+ } else if (offset == end) {
+ if (end == start + 1) {
+ // Quoted empty string
+ visitSimpleStringLiteral(uri);
+ } else {
+ String data = request.source.contents.data;
+ if (end == data.length) {
+ String ch = data[end - 1];
+ if (ch != '"' && ch != "'") {
+ // Insertion point at end of file
+ // and missing closing quote on non-empty string
+ visitSimpleStringLiteral(uri);
+ }
+ }
+ }
+ }
+ }
+ else if (offset == start && offset == end) {
+ String data = request.source.contents.data;
+ if (end == data.length) {
+ String ch = data[end - 1];
+ if (ch == '"' || ch == "'") {
+ // Insertion point at end of file
+ // and missing closing quote on empty string
+ visitSimpleStringLiteral(uri);
+ }
+ }
}
}
}
diff --git a/pkg/analysis_server/lib/src/services/correction/fix.dart b/pkg/analysis_server/lib/src/services/correction/fix.dart
index 05ec763..7f926b4 100644
--- a/pkg/analysis_server/lib/src/services/correction/fix.dart
+++ b/pkg/analysis_server/lib/src/services/correction/fix.dart
@@ -9,10 +9,11 @@
import 'package:analysis_server/plugin/edit/fix/fix_core.dart';
import 'package:analysis_server/src/plugin/server_plugin.dart';
import 'package:analysis_server/src/services/correction/fix_internal.dart';
+import 'package:analyzer/error/error.dart';
import 'package:analyzer/exception/exception.dart';
import 'package:analyzer/file_system/file_system.dart';
+import 'package:analyzer/src/error/codes.dart';
import 'package:analyzer/src/generated/engine.dart';
-import 'package:analyzer/src/generated/error.dart';
import 'package:analyzer/src/generated/parser.dart';
/**
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 6b8ee68..ceadf3c 100644
--- a/pkg/analysis_server/lib/src/services/correction/fix_internal.dart
+++ b/pkg/analysis_server/lib/src/services/correction/fix_internal.dart
@@ -28,14 +28,15 @@
import 'package:analyzer/dart/ast/token.dart';
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/type.dart';
+import 'package:analyzer/error/error.dart';
import 'package:analyzer/file_system/file_system.dart';
import 'package:analyzer/src/dart/ast/token.dart';
import 'package:analyzer/src/dart/ast/utilities.dart';
import 'package:analyzer/src/dart/element/element.dart';
import 'package:analyzer/src/dart/element/member.dart';
import 'package:analyzer/src/dart/element/type.dart';
+import 'package:analyzer/src/error/codes.dart';
import 'package:analyzer/src/generated/engine.dart';
-import 'package:analyzer/src/generated/error.dart';
import 'package:analyzer/src/generated/java_core.dart';
import 'package:analyzer/src/generated/parser.dart';
import 'package:analyzer/src/generated/sdk.dart';
@@ -518,9 +519,10 @@
}
void _addFix_addPartOfDirective() {
+ // TODO(brianwilkerson) Generalize this to allow other valid string literals.
if (node is SimpleStringLiteral && node.parent is PartDirective) {
PartDirective directive = node.parent;
- Source partSource = directive.source;
+ Source partSource = directive.uriSource;
CompilationUnit partUnit;
partUnit = context.getResolvedCompilationUnit2(partSource, partSource);
if (partUnit != null) {
@@ -1186,9 +1188,11 @@
}
void _addFix_createImportUri() {
+ // TODO(brianwilkerson) Generalize this to allow other valid string literals.
+ // TODO(brianwilkerson) Support the case where the node's parent is a Configuration.
if (node is SimpleStringLiteral && node.parent is ImportDirective) {
ImportDirective importDirective = node.parent;
- Source source = importDirective.source;
+ Source source = importDirective.uriSource;
if (source != null) {
String file = source.fullName;
if (isAbsolute(file) && AnalysisEngine.isDartFileName(file)) {
@@ -1406,9 +1410,10 @@
}
void _addFix_createPartUri() {
+ // TODO(brianwilkerson) Generalize this to allow other valid string literals.
if (node is SimpleStringLiteral && node.parent is PartDirective) {
PartDirective partDirective = node.parent;
- Source source = partDirective.source;
+ Source source = partDirective.uriSource;
if (source != null) {
String libName = unitLibraryElement.name;
SourceEdit edit = new SourceEdit(0, 0, 'part of $libName;$eol$eol');
diff --git a/pkg/analysis_server/lib/src/services/correction/organize_directives.dart b/pkg/analysis_server/lib/src/services/correction/organize_directives.dart
index 56d4bb0..57b86c3 100644
--- a/pkg/analysis_server/lib/src/services/correction/organize_directives.dart
+++ b/pkg/analysis_server/lib/src/services/correction/organize_directives.dart
@@ -9,7 +9,8 @@
import 'package:analysis_server/src/services/correction/strings.dart';
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/ast/token.dart';
-import 'package:analyzer/src/generated/error.dart';
+import 'package:analyzer/error/error.dart';
+import 'package:analyzer/src/error/codes.dart';
/**
* Organizer of directives in the [unit].
diff --git a/pkg/analysis_server/lib/src/services/correction/source_range.dart b/pkg/analysis_server/lib/src/services/correction/source_range.dart
index 4440a5c..c3b408bc 100644
--- a/pkg/analysis_server/lib/src/services/correction/source_range.dart
+++ b/pkg/analysis_server/lib/src/services/correction/source_range.dart
@@ -7,7 +7,7 @@
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/ast/token.dart';
import 'package:analyzer/dart/element/element.dart';
-import 'package:analyzer/src/generated/error.dart';
+import 'package:analyzer/error/error.dart';
import 'package:analyzer/src/generated/source.dart';
SourceRange rangeElementName(Element element) {
diff --git a/pkg/analysis_server/lib/src/status/ast_writer.dart b/pkg/analysis_server/lib/src/status/ast_writer.dart
index 424132e..1b292d6 100644
--- a/pkg/analysis_server/lib/src/status/ast_writer.dart
+++ b/pkg/analysis_server/lib/src/status/ast_writer.dart
@@ -62,6 +62,8 @@
properties['abstract keyword'] = node.abstractKeyword;
} else if (node is CompilationUnit) {
properties['element'] = node.element;
+ } else if (node is Configuration) {
+ properties['uriSource'] = node.uriSource;
} else if (node is ConstructorName) {
properties['static element'] = node.staticElement;
} else if (node is DeclaredIdentifier) {
@@ -69,7 +71,8 @@
properties['keyword'] = node.keyword;
} else if (node is ExportDirective) {
properties['element'] = node.element;
- properties['source'] = node.source;
+ properties['selectedSource'] = node.selectedSource;
+ properties['uriSource'] = node.uriSource;
} else if (node is FieldDeclaration) {
properties['static keyword'] = node.staticKeyword;
} else if (node is FormalParameter) {
@@ -88,7 +91,8 @@
properties['propagated type'] = node.propagatedType;
} else if (node is ImportDirective) {
properties['element'] = node.element;
- properties['source'] = node.source;
+ properties['selectedSource'] = node.selectedSource;
+ properties['uriSource'] = node.uriSource;
} else if (node is IndexExpression) {
properties['static element'] = node.staticElement;
properties['static type'] = node.staticType;
@@ -113,7 +117,7 @@
properties['propagated type'] = node.propagatedType;
} else if (node is PartDirective) {
properties['element'] = node.element;
- properties['source'] = node.source;
+ properties['uriSource'] = node.uriSource;
} else if (node is PartOfDirective) {
properties['element'] = node.element;
} else if (node is PostfixExpression) {
diff --git a/pkg/analysis_server/lib/src/status/get_handler.dart b/pkg/analysis_server/lib/src/status/get_handler.dart
index 54293cd..99f88b3 100644
--- a/pkg/analysis_server/lib/src/status/get_handler.dart
+++ b/pkg/analysis_server/lib/src/status/get_handler.dart
@@ -36,7 +36,6 @@
import 'package:analyzer/src/context/source.dart';
import 'package:analyzer/src/dart/sdk/sdk.dart';
import 'package:analyzer/src/generated/engine.dart';
-import 'package:analyzer/src/generated/error.dart';
import 'package:analyzer/src/generated/resolver.dart';
import 'package:analyzer/src/generated/sdk.dart';
import 'package:analyzer/src/generated/source.dart';
@@ -47,6 +46,7 @@
import 'package:analyzer/src/task/driver.dart';
import 'package:analyzer/src/task/html.dart';
import 'package:analyzer/src/task/options.dart';
+import 'package:analyzer/src/task/options.dart' show CONFIGURED_ERROR_PROCESSORS;
import 'package:analyzer/task/dart.dart';
import 'package:analyzer/task/general.dart';
import 'package:analyzer/task/html.dart';
diff --git a/pkg/analysis_server/lib/src/status/validator.dart b/pkg/analysis_server/lib/src/status/validator.dart
index 7c995ea..f25f8bf 100644
--- a/pkg/analysis_server/lib/src/status/validator.dart
+++ b/pkg/analysis_server/lib/src/status/validator.dart
@@ -10,13 +10,13 @@
import 'package:analyzer/dart/ast/token.dart';
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/type.dart';
+import 'package:analyzer/error/error.dart';
import 'package:analyzer/src/context/cache.dart';
import 'package:analyzer/src/context/context.dart';
import 'package:analyzer/src/dart/ast/utilities.dart';
import 'package:analyzer/src/dart/element/element.dart';
import 'package:analyzer/src/generated/engine.dart'
show AnalysisEngine, AnalysisResult, CacheState, ChangeSet;
-import 'package:analyzer/src/generated/error.dart';
import 'package:analyzer/src/generated/resolver.dart';
import 'package:analyzer/src/generated/source.dart';
import 'package:analyzer/src/generated/utilities_collection.dart';
@@ -274,6 +274,7 @@
_write(element.name);
}
}
+
expectedElements.forEach((String name, Element element) {
_write('Expected ');
writeElement(element);
@@ -603,6 +604,7 @@
_write(actual.name);
}
}
+
void compareTypeArguments(
ParameterizedType expected, ParameterizedType actual) {
List<DartType> expectedArguments = expected.typeArguments;
@@ -1597,6 +1599,7 @@
}
buffer.write('}');
}
+
bool needsNewline = false;
if (missingNames.isNotEmpty) {
buffer.write('Has ');
diff --git a/pkg/analysis_server/test/abstract_single_unit.dart b/pkg/analysis_server/test/abstract_single_unit.dart
index 6a73d1c..307f251 100644
--- a/pkg/analysis_server/test/abstract_single_unit.dart
+++ b/pkg/analysis_server/test/abstract_single_unit.dart
@@ -6,8 +6,8 @@
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/element/element.dart';
+import 'package:analyzer/error/error.dart';
import 'package:analyzer/src/dart/ast/utilities.dart';
-import 'package:analyzer/src/generated/error.dart';
import 'package:analyzer/src/generated/java_engine.dart';
import 'package:analyzer/src/generated/source.dart';
import 'package:unittest/unittest.dart';
diff --git a/pkg/analysis_server/test/completion_test.dart b/pkg/analysis_server/test/completion_test.dart
index 70ac854..778b1f0 100644
--- a/pkg/analysis_server/test/completion_test.dart
+++ b/pkg/analysis_server/test/completion_test.dart
@@ -1349,8 +1349,7 @@
"1+dart:math",
"1-dart:_chrome",
"1-dart:_collection.dev"
- ],
- failingTests: '1');
+ ]);
buildTests(
'testCompletion_export_noStringLiteral_noSemicolon',
@@ -1497,8 +1496,7 @@
"1+dart:math",
"1-dart:_chrome",
"1-dart:_collection.dev"
- ],
- failingTests: '1');
+ ]);
buildTests(
'testCompletion_import_hasStringLiteral_noSemicolon',
diff --git a/pkg/analysis_server/test/context_manager_test.dart b/pkg/analysis_server/test/context_manager_test.dart
index c00648c..84ecd4c 100644
--- a/pkg/analysis_server/test/context_manager_test.dart
+++ b/pkg/analysis_server/test/context_manager_test.dart
@@ -8,18 +8,21 @@
import 'dart:io' as io;
import 'package:analysis_server/src/context_manager.dart';
+import 'package:analyzer/error/error.dart';
import 'package:analyzer/file_system/file_system.dart';
import 'package:analyzer/file_system/memory_file_system.dart';
import 'package:analyzer/instrumentation/instrumentation.dart';
import 'package:analyzer/source/error_processor.dart';
import 'package:analyzer/src/context/builder.dart';
import 'package:analyzer/src/dart/sdk/sdk.dart';
+import 'package:analyzer/src/error/codes.dart';
import 'package:analyzer/src/generated/engine.dart';
-import 'package:analyzer/src/generated/error.dart';
import 'package:analyzer/src/generated/sdk.dart';
import 'package:analyzer/src/generated/source.dart';
import 'package:analyzer/src/generated/source_io.dart';
import 'package:analyzer/src/services/lint.dart';
+import 'package:analyzer/src/task/options.dart'
+ show CONFIGURED_ERROR_PROCESSORS;
import 'package:analyzer/src/util/glob.dart';
import 'package:linter/src/plugin/linter_plugin.dart';
import 'package:linter/src/rules/avoid_as.dart';
@@ -442,7 +445,7 @@
newFile([examplePath, ContextManagerImpl.PACKAGE_SPEC_NAME]);
newFile([examplePath, 'example.dart']);
- packageMapProvider.packageMap['proj'] = [
+ packageMapProvider.packageMap['proj'] = <Folder>[
resourceProvider.getResource(libPath)
];
@@ -471,7 +474,7 @@
newFile([examplePath, ContextManagerImpl.PUBSPEC_NAME]);
newFile([examplePath, 'example.dart']);
- packageMapProvider.packageMap['proj'] = [
+ packageMapProvider.packageMap['proj'] = <Folder>[
resourceProvider.getResource(libPath)
];
@@ -570,7 +573,7 @@
newFile([srcPath, 'internal.dart']);
String testFilePath = newFile([testPath, 'main_test.dart']);
- packageMapProvider.packageMap['proj'] = [
+ packageMapProvider.packageMap['proj'] = <Folder>[
resourceProvider.getResource(libPath)
];
diff --git a/pkg/analysis_server/test/domain_analysis_test.dart b/pkg/analysis_server/test/domain_analysis_test.dart
index 1a7671e..d44561b 100644
--- a/pkg/analysis_server/test/domain_analysis_test.dart
+++ b/pkg/analysis_server/test/domain_analysis_test.dart
@@ -11,6 +11,7 @@
import 'package:analysis_server/src/constants.dart';
import 'package:analysis_server/src/domain_analysis.dart';
import 'package:analysis_server/src/plugin/server_plugin.dart';
+import 'package:analyzer/file_system/file_system.dart';
import 'package:analyzer/file_system/memory_file_system.dart';
import 'package:analyzer/instrumentation/instrumentation.dart';
import 'package:analyzer/src/generated/sdk.dart';
@@ -409,7 +410,7 @@
expect(filesErrors[testFile], isNotEmpty);
// Add the package to the package map and tickle the package dependency.
packageMapProvider.packageMap = {
- 'pkgA': [resourceProvider.getResource('/packages/pkgA')]
+ 'pkgA': <Folder>[resourceProvider.getResource('/packages/pkgA')]
};
resourceProvider.modifyFile(pkgDependency, 'new contents');
// Give the server time to notice the file has changed, then let
diff --git a/pkg/analysis_server/test/plugin/protocol_dart_test.dart b/pkg/analysis_server/test/plugin/protocol_dart_test.dart
index 8920e92..ef2cd50 100644
--- a/pkg/analysis_server/test/plugin/protocol_dart_test.dart
+++ b/pkg/analysis_server/test/plugin/protocol_dart_test.dart
@@ -10,9 +10,10 @@
import 'package:analyzer/dart/ast/visitor.dart' as engine;
import 'package:analyzer/dart/element/element.dart' as engine;
import 'package:analyzer/dart/element/type.dart' as engine;
+import 'package:analyzer/error/error.dart' as engine;
import 'package:analyzer/src/dart/ast/utilities.dart' as engine;
import 'package:analyzer/src/dart/element/element.dart' as engine;
-import 'package:analyzer/src/generated/error.dart' as engine;
+import 'package:analyzer/src/error/codes.dart' as engine;
import 'package:analyzer/src/generated/source.dart' as engine;
import 'package:test_reflective_loader/test_reflective_loader.dart';
import 'package:unittest/unittest.dart';
diff --git a/pkg/analysis_server/test/protocol_server_test.dart b/pkg/analysis_server/test/protocol_server_test.dart
index 4a667bb..bcbe18e 100644
--- a/pkg/analysis_server/test/protocol_server_test.dart
+++ b/pkg/analysis_server/test/protocol_server_test.dart
@@ -12,7 +12,8 @@
import 'package:analyzer/dart/ast/ast.dart' as engine;
import 'package:analyzer/dart/element/element.dart' as engine;
import 'package:analyzer/dart/element/type.dart' as engine;
-import 'package:analyzer/src/generated/error.dart' as engine;
+import 'package:analyzer/error/error.dart' as engine;
+import 'package:analyzer/src/error/codes.dart' as engine;
import 'package:analyzer/src/generated/source.dart' as engine;
import 'package:test_reflective_loader/test_reflective_loader.dart';
import 'package:typed_mock/typed_mock.dart';
diff --git a/pkg/analysis_server/test/services/completion/dart/local_declaration_visitor_test.dart b/pkg/analysis_server/test/services/completion/dart/local_declaration_visitor_test.dart
index aa878d5..eff6ab6 100644
--- a/pkg/analysis_server/test/services/completion/dart/local_declaration_visitor_test.dart
+++ b/pkg/analysis_server/test/services/completion/dart/local_declaration_visitor_test.dart
@@ -7,9 +7,9 @@
import 'package:analysis_server/src/services/completion/dart/local_declaration_visitor.dart';
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/ast/token.dart';
+import 'package:analyzer/error/listener.dart';
import 'package:analyzer/src/dart/scanner/reader.dart';
import 'package:analyzer/src/dart/scanner/scanner.dart';
-import 'package:analyzer/src/generated/error.dart';
import 'package:analyzer/src/generated/parser.dart';
import 'package:test_reflective_loader/test_reflective_loader.dart';
import 'package:unittest/unittest.dart';
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 8bd4e6b..99cfd29 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
@@ -96,6 +96,15 @@
assertSuggest('package:', csKind: CompletionSuggestionKind.IMPORT);
}
+ test_import3() async {
+ addTestSource('import "^ import');
+ await computeSuggestions();
+ expect(replacementOffset, completionOffset);
+ expect(replacementLength, 7);
+ assertSuggest('dart:', csKind: CompletionSuggestionKind.IMPORT);
+ assertSuggest('package:', csKind: CompletionSuggestionKind.IMPORT);
+ }
+
test_import_dart() async {
addTestSource('import "d^" import');
await computeSuggestions();
@@ -320,6 +329,58 @@
assertSuggest('package:', csKind: CompletionSuggestionKind.IMPORT);
}
+ test_import_without_any_quotes() async {
+ addTestSource('import ^ import');
+ await computeSuggestions();
+ expect(replacementOffset, completionOffset);
+ expect(replacementLength, 0);
+ assertNoSuggestions();
+ }
+
+ test_import_without_any_quotes_eof() async {
+ addTestSource('import ^');
+ await computeSuggestions();
+ expect(replacementOffset, completionOffset);
+ expect(replacementLength, 0);
+ assertNoSuggestions();
+ }
+
+ test_import_without_closing_quote_eof() async {
+ addTestSource('import "^');
+ await computeSuggestions();
+ expect(replacementOffset, completionOffset);
+ expect(replacementLength, 0);
+ assertSuggest('dart:', csKind: CompletionSuggestionKind.IMPORT);
+ assertSuggest('package:', csKind: CompletionSuggestionKind.IMPORT);
+ }
+
+ test_import_without_closing_quote_eof2() async {
+ addTestSource('import "^d');
+ await computeSuggestions();
+ expect(replacementOffset, completionOffset);
+ expect(replacementLength, 1);
+ assertSuggest('dart:', csKind: CompletionSuggestionKind.IMPORT);
+ assertSuggest('package:', csKind: CompletionSuggestionKind.IMPORT);
+ }
+
+ test_import_without_closing_quote_eof3() async {
+ addTestSource('import "d^');
+ await computeSuggestions();
+ expect(replacementOffset, completionOffset - 1);
+ expect(replacementLength, 1);
+ assertSuggest('dart:', csKind: CompletionSuggestionKind.IMPORT);
+ assertSuggest('package:', csKind: CompletionSuggestionKind.IMPORT);
+ }
+
+ test_import_without_closing_quote_eof4() async {
+ addTestSource('import "d^"');
+ await computeSuggestions();
+ expect(replacementOffset, completionOffset - 1);
+ expect(replacementLength, 1);
+ assertSuggest('dart:', csKind: CompletionSuggestionKind.IMPORT);
+ assertSuggest('package:', csKind: CompletionSuggestionKind.IMPORT);
+ }
+
test_outside_import() async {
addTestSource('import ^"d" import');
await computeSuggestions();
diff --git a/pkg/analysis_server/test/services/correction/fix_test.dart b/pkg/analysis_server/test/services/correction/fix_test.dart
index 5bde966..60897d9 100644
--- a/pkg/analysis_server/test/services/correction/fix_test.dart
+++ b/pkg/analysis_server/test/services/correction/fix_test.dart
@@ -12,9 +12,10 @@
hide AnalysisError;
import 'package:analysis_server/src/services/correction/fix.dart';
import 'package:analysis_server/src/services/correction/fix_internal.dart';
+import 'package:analyzer/error/error.dart';
import 'package:analyzer/file_system/file_system.dart';
import 'package:analyzer/source/package_map_resolver.dart';
-import 'package:analyzer/src/generated/error.dart';
+import 'package:analyzer/src/error/codes.dart';
import 'package:analyzer/src/generated/parser.dart';
import 'package:analyzer/src/generated/source.dart';
import 'package:test_reflective_loader/test_reflective_loader.dart';
@@ -1869,7 +1870,7 @@
Uri.parse('package:my/test.dart'));
// configure SourceFactory
UriResolver pkgResolver = new PackageMapUriResolver(provider, {
- 'my': [provider.getResource('/my/lib')],
+ 'my': <Folder>[provider.getResource('/my/lib')],
});
context.sourceFactory = new SourceFactory(
[AbstractContextTest.SDK_RESOLVER, pkgResolver, resourceResolver]);
diff --git a/pkg/analysis_server/test/services/correction/organize_directives_test.dart b/pkg/analysis_server/test/services/correction/organize_directives_test.dart
index f21b14f..dc03bce 100644
--- a/pkg/analysis_server/test/services/correction/organize_directives_test.dart
+++ b/pkg/analysis_server/test/services/correction/organize_directives_test.dart
@@ -7,7 +7,7 @@
import 'package:analysis_server/plugin/protocol/protocol.dart'
hide AnalysisError;
import 'package:analysis_server/src/services/correction/organize_directives.dart';
-import 'package:analyzer/src/generated/error.dart';
+import 'package:analyzer/error/error.dart';
import 'package:test_reflective_loader/test_reflective_loader.dart';
import 'package:unittest/unittest.dart';
diff --git a/pkg/analysis_server/test/services/correction/source_range_test.dart b/pkg/analysis_server/test/services/correction/source_range_test.dart
index dfc6544..6824519 100644
--- a/pkg/analysis_server/test/services/correction/source_range_test.dart
+++ b/pkg/analysis_server/test/services/correction/source_range_test.dart
@@ -7,7 +7,7 @@
import 'package:analysis_server/src/services/correction/source_range.dart';
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/element/element.dart';
-import 'package:analyzer/src/generated/error.dart';
+import 'package:analyzer/error/error.dart';
import 'package:analyzer/src/generated/parser.dart';
import 'package:analyzer/src/generated/source.dart';
import 'package:test_reflective_loader/test_reflective_loader.dart';
diff --git a/pkg/analysis_server/test/services/refactoring/move_file_test.dart b/pkg/analysis_server/test/services/refactoring/move_file_test.dart
index 9146b93..df2e422 100644
--- a/pkg/analysis_server/test/services/refactoring/move_file_test.dart
+++ b/pkg/analysis_server/test/services/refactoring/move_file_test.dart
@@ -111,7 +111,7 @@
testFile = '/packages/my_pkg/lib/aaa/test.dart';
provider.newFile(testFile, '');
Map<String, List<Folder>> packageMap = {
- 'my_pkg': [provider.getResource('/packages/my_pkg/lib')]
+ 'my_pkg': <Folder>[provider.getResource('/packages/my_pkg/lib')]
};
context.sourceFactory = new SourceFactory([
AbstractContextTest.SDK_RESOLVER,
@@ -243,7 +243,7 @@
context.sourceFactory = new SourceFactory([
AbstractContextTest.SDK_RESOLVER,
new PackageMapUriResolver(provider, <String, List<Folder>>{
- 'testName': [provider.getResource('/testName/lib')]
+ 'testName': <Folder>[provider.getResource('/testName/lib')]
}),
resourceResolver,
]);
diff --git a/pkg/analysis_server/test/stress/replay/replay.dart b/pkg/analysis_server/test/stress/replay/replay.dart
index dd9016d..e5525e7 100644
--- a/pkg/analysis_server/test/stress/replay/replay.dart
+++ b/pkg/analysis_server/test/stress/replay/replay.dart
@@ -13,9 +13,9 @@
import 'package:analysis_server/plugin/protocol/protocol.dart';
import 'package:analyzer/dart/ast/token.dart';
+import 'package:analyzer/error/listener.dart' as error;
import 'package:analyzer/src/dart/scanner/reader.dart';
import 'package:analyzer/src/dart/scanner/scanner.dart';
-import 'package:analyzer/src/generated/error.dart' as error;
import 'package:analyzer/src/generated/java_engine.dart';
import 'package:analyzer/src/generated/source.dart';
import 'package:analyzer/src/util/glob.dart';
diff --git a/pkg/analysis_server/tool/instrumentation/log/log.dart b/pkg/analysis_server/tool/instrumentation/log/log.dart
new file mode 100644
index 0000000..7042fc4
--- /dev/null
+++ b/pkg/analysis_server/tool/instrumentation/log/log.dart
@@ -0,0 +1,807 @@
+// Copyright (c) 2016, 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.
+
+/**
+ * A representation of the contents of an instrumentation log.
+ */
+library analysis_server.tool.instrumentation.log;
+
+import 'dart:collection';
+import 'dart:convert';
+
+import 'package:analyzer/instrumentation/instrumentation.dart';
+
+/**
+ * A range of log entries, represented by the index of the first and last
+ * entries in the range.
+ */
+class EntryRange {
+ /**
+ * The index of the first entry in the range.
+ */
+ int firstIndex;
+
+ /**
+ * The index of the first entry in the range.
+ */
+ int lastIndex;
+
+ /**
+ * Initialize a newly created range to represent the entries between the
+ * [firstIndex] and the [lastIndex], inclusive.
+ */
+ EntryRange(this.firstIndex, this.lastIndex);
+}
+
+/**
+ * A log entry representing an Err entry.
+ */
+class ErrorEntry extends GenericEntry {
+ /**
+ * Initialize a newly created log entry.
+ */
+ ErrorEntry(
+ int index, int timeStamp, String entryKind, List<String> components)
+ : super(index, timeStamp, entryKind, components);
+}
+
+/**
+ * A log entry representing an Ex entry.
+ */
+class ExceptionEntry extends GenericEntry {
+ /**
+ * Initialize a newly created log entry.
+ */
+ ExceptionEntry(
+ int index, int timeStamp, String entryKind, List<String> components)
+ : super(index, timeStamp, entryKind, components);
+}
+
+/**
+ * A representation of a generic log entry.
+ */
+class GenericEntry extends LogEntry {
+ /**
+ * The kind of the log entry.
+ */
+ String entryKind;
+
+ /**
+ * The components in the entry that follow the time stamp and entry kind.
+ */
+ List<String> components;
+
+ /**
+ * Initialize a newly created generic log entry to have the given [timeStamp],
+ * [entryKind] and list of [components]
+ */
+ GenericEntry(int index, int timeStamp, this.entryKind, this.components)
+ : super(index, timeStamp);
+
+ @override
+ String get kind => entryKind;
+
+ @override
+ void _appendDetails(StringBuffer buffer) {
+ super._appendDetails(buffer);
+ for (String component in components) {
+ buffer.write(component);
+ buffer.write('<br>');
+ }
+ }
+}
+
+/**
+ * A representation of an instrumentation log.
+ */
+class InstrumentationLog {
+ /**
+ * The paths of the log files containing the entries.
+ */
+ List<String> logFilePaths;
+
+ /**
+ * The entries in the instrumentation log.
+ */
+ List<LogEntry> logEntries;
+
+ /**
+ * The entries in the instrumentation log that are not instances of
+ * [TaskEntry].
+ */
+ List<LogEntry> nonTaskEntries;
+
+ /**
+ * A table mapping entries that are paired with another entry to the entry
+ * with which they are paired.
+ */
+ Map<LogEntry, LogEntry> _pairedEntries = new HashMap<LogEntry, LogEntry>();
+
+ /**
+ * A table mapping the id's of requests to the entry representing the request.
+ */
+ Map<String, RequestEntry> _requestMap = new HashMap<String, RequestEntry>();
+
+ /**
+ * A table mapping the id's of responses to the entry representing the
+ * response.
+ */
+ Map<String, ResponseEntry> _responseMap =
+ new HashMap<String, ResponseEntry>();
+
+ /**
+ * A table mapping the ids of completion events to the events with those ids.
+ */
+ Map<String, List<NotificationEntry>> _completionMap =
+ new HashMap<String, List<NotificationEntry>>();
+
+ /**
+ * The ranges of entries that are between analysis start and analysis end
+ * notifications.
+ */
+ List<EntryRange> analysisRanges;
+
+ /**
+ * Initialize a newly created instrumentation log by parsing each of the lines
+ * in the [logContent] into a separate entry. The log contents should be the
+ * contents of the files whose paths are in the given list of [logFilePaths].
+ */
+ InstrumentationLog(this.logFilePaths, List<String> logContent) {
+ _parseLogContent(logContent);
+ }
+
+ /**
+ * Return a list of the completion events associated with the given [id].
+ */
+ List<NotificationEntry> completionEventsWithId(String id) =>
+ _completionMap[id];
+
+ /**
+ * Return the entry that is paired with the given [entry], or `null` if there
+ * is no entry paired with it.
+ */
+ LogEntry pairedEntry(LogEntry entry) => _pairedEntries[entry];
+
+ /**
+ * Return the response that corresponds to the given request.
+ */
+ RequestEntry requestFor(ResponseEntry entry) => _requestMap[entry.id];
+
+ /**
+ * Return the response that corresponds to the given request.
+ */
+ ResponseEntry responseFor(RequestEntry entry) => _responseMap[entry.id];
+
+ /**
+ * Return a list containing all of the task entries between the start of
+ * analysis notification at the given [startIndex] and the matching end of
+ * analysis notification (or the end of the log if the log does not contain a
+ * corresponding end notification.
+ */
+ List<TaskEntry> taskEntriesFor(int startIndex) {
+ List<TaskEntry> taskEntries = <TaskEntry>[];
+ NotificationEntry startEntry = nonTaskEntries[startIndex];
+ LogEntry endEntry = pairedEntry(startEntry);
+ int lastIndex = endEntry == null ? logEntries.length : endEntry.index;
+ for (int i = startEntry.index + 1; i < lastIndex; i++) {
+ LogEntry entry = logEntries[i];
+ if (entry is TaskEntry) {
+ taskEntries.add(entry);
+ }
+ }
+ return taskEntries;
+ }
+
+ /**
+ * Merge any multi-line entries into a single line so that every element in
+ * the given [logContent] is a single entry.
+ */
+ void _mergeEntries(List<String> logContent) {
+ bool isStartOfEntry(String line) {
+ return line.startsWith(LogEntry.entryRegExp);
+ }
+
+ String merge(String line, List<String> extraLines) {
+ StringBuffer buffer = new StringBuffer();
+ buffer.writeln(line);
+ for (String extraLine in extraLines) {
+ buffer.writeln(extraLine);
+ }
+ return buffer.toString();
+ }
+
+ List<String> extraLines = <String>[];
+ for (int i = logContent.length - 1; i >= 0; i--) {
+ String line = logContent[i];
+ if (isStartOfEntry(line)) {
+ if (extraLines.isNotEmpty) {
+ logContent[i] = merge(line, extraLines);
+ }
+ } else {
+ logContent.removeAt(i);
+ extraLines.insert(0, line);
+ }
+ }
+ if (extraLines.isNotEmpty) {
+ throw new StateError(
+ '${extraLines.length} non-entry lines before any entry');
+ }
+ }
+
+ /**
+ * Parse the given [logContent] into a list of log entries.
+ */
+ void _parseLogContent(List<String> logContent) {
+ _mergeEntries(logContent);
+ logEntries = <LogEntry>[];
+ nonTaskEntries = <LogEntry>[];
+ analysisRanges = <EntryRange>[];
+ NotificationEntry analysisStartEntry = null;
+ int analysisStartIndex = -1;
+ NotificationEntry pubStartEntry = null;
+ for (String line in logContent) {
+ LogEntry entry = new LogEntry.from(logEntries.length, line);
+ if (entry != null) {
+ logEntries.add(entry);
+ if (entry is! TaskEntry) {
+ nonTaskEntries.add(entry);
+ }
+ if (entry is RequestEntry) {
+ _requestMap[entry.id] = entry;
+ } else if (entry is ResponseEntry) {
+ _responseMap[entry.id] = entry;
+ RequestEntry request = _requestMap[entry.id];
+ _pairedEntries[entry] = request;
+ _pairedEntries[request] = entry;
+ } else if (entry is NotificationEntry) {
+ if (entry.isServerStatus) {
+ var analysisStatus = entry.param('analysis');
+ if (analysisStatus is Map) {
+ if (analysisStatus['isAnalyzing']) {
+ if (analysisStartEntry != null) {
+ analysisStartEntry.recordProblem(
+ 'Analysis started without being terminated.');
+ }
+ analysisStartEntry = entry;
+ analysisStartIndex = logEntries.length - 1;
+ } else {
+ if (analysisStartEntry == null) {
+ entry.recordProblem(
+ 'Analysis terminated without being started.');
+ } else {
+ int analysisEnd = logEntries.length - 1;
+ analysisRanges
+ .add(new EntryRange(analysisStartIndex, analysisEnd));
+ _pairedEntries[entry] = analysisStartEntry;
+ _pairedEntries[analysisStartEntry] = entry;
+ analysisStartEntry = null;
+ analysisStartIndex = -1;
+ }
+ }
+ }
+ var pubStatus = entry.param('pub');
+ if (pubStatus is Map) {
+ if (pubStatus['isListingPackageDirs']) {
+ if (pubStartEntry != null) {
+ pubStartEntry.recordProblem(
+ 'Pub started without previous being terminated.');
+ }
+ pubStartEntry = entry;
+ } else {
+ if (pubStartEntry == null) {
+ entry.recordProblem('Pub terminated without being started.');
+ } else {
+ _pairedEntries[entry] = pubStartEntry;
+ _pairedEntries[pubStartEntry] = entry;
+ pubStartEntry = null;
+ }
+ }
+ }
+ } else if (entry.event == 'completion.results') {
+ String id = entry.param('id');
+ if (id != null) {
+ _completionMap
+ .putIfAbsent(id, () => new List<NotificationEntry>())
+ .add(entry);
+ }
+ }
+ }
+ }
+ }
+ if (analysisStartEntry != null) {
+ analysisStartEntry
+ .recordProblem('Analysis started without being terminated.');
+ }
+ if (pubStartEntry != null) {
+ pubStartEntry
+ .recordProblem('Pub started without previous being terminated.');
+ }
+ }
+}
+
+/**
+ * A log entry that has a single JSON encoded component following the time stamp
+ * and entry kind.
+ */
+abstract class JsonBasedEntry extends LogEntry {
+ /**
+ * The HTML string used to indent text when formatting the JSON [data].
+ */
+ static const String singleIndent = ' ';
+
+ /**
+ * The decoded form of the JSON encoded component.
+ */
+ final Map data;
+
+ /**
+ * Initialize a newly created log entry to have the given [timeStamp] and
+ * [data].
+ */
+ JsonBasedEntry(int index, int timeStamp, this.data) : super(index, timeStamp);
+
+ @override
+ void _appendDetails(StringBuffer buffer) {
+ super._appendDetails(buffer);
+ _format(buffer, '', data);
+ }
+
+ /**
+ * Encode any character in the given [string] that would prevent source code
+ * from being displayed correctly: end of line markers and spaces.
+ */
+ String _encodeSourceCode(String string) {
+ // TODO(brianwilkerson) This method isn't working completely. Some source
+ // code produces an error of
+ // "log?start=3175:261 Uncaught SyntaxError: missing ) after argument list"
+ // in the sample log I was using.
+ StringBuffer buffer = new StringBuffer();
+ int length = string.length;
+ int index = 0;
+ while (index < length) {
+ int char = string.codeUnitAt(index);
+ index++;
+ // TODO(brianwilkerson) Handle tabs and other special characters.
+ if (char == '\r'.codeUnitAt(0)) {
+ if (index < length && string.codeUnitAt(index) == '\n'.codeUnitAt(0)) {
+ index++;
+ }
+ buffer.write('<br>');
+ } else if (char == '\n'.codeUnitAt(0)) {
+ buffer.write('<br>');
+ } else if (char == ' '.codeUnitAt(0)) {
+ // Encode all spaces in order to accurately reproduce the original
+ // source code when displaying it.
+ buffer.write(' ');
+ } else {
+ buffer.writeCharCode(char);
+ }
+ }
+ return buffer.toString();
+ }
+
+ /**
+ * Write an HTML representation the given JSON [object] to the given [buffer],
+ * using the given [indent] to make the output more readable.
+ */
+ void _format(StringBuffer buffer, String indent, Object object) {
+ if (object is String) {
+ buffer.write('"');
+ buffer.write(_encodeSourceCode(object));
+ buffer.write('"');
+ } else if (object is int || object is bool) {
+ buffer.write(object);
+ } else if (object is Map) {
+ buffer.write('{<br>');
+ object.forEach((Object key, Object value) {
+ String newIndent = indent + singleIndent;
+ buffer.write(newIndent);
+ _format(buffer, newIndent, key);
+ buffer.write(' : ');
+ _format(buffer, newIndent, value);
+ buffer.write('<br>');
+ });
+ buffer.write(indent);
+ buffer.write('}');
+ } else if (object is List) {
+ buffer.write('[<br>');
+ object.forEach((Object element) {
+ String newIndent = indent + singleIndent;
+ buffer.write(newIndent);
+ _format(buffer, newIndent, element);
+ buffer.write('<br>');
+ });
+ buffer.write(indent);
+ buffer.write(']');
+ }
+ }
+}
+
+/**
+ * A single entry in an instrumentation log.
+ */
+abstract class LogEntry {
+ /**
+ * The character used to separate fields within an entry.
+ */
+ static final int fieldSeparator = ':'.codeUnitAt(0);
+
+ /**
+ * A regular expression that will match the beginning of a valid log entry.
+ */
+ static final RegExp entryRegExp = new RegExp('[0-9]+\\:');
+
+ /**
+ * A table mapping kinds to the names of those kinds.
+ */
+ static final Map<String, String> kindMap = {
+ 'Err': 'Error',
+ 'Ex': 'Exception',
+ 'Log': 'Log message',
+ 'Noti': 'Notification',
+ 'Read': 'Read file',
+ 'Req': 'Request',
+ 'Res': 'Response',
+ 'Perf': 'Performance data',
+ 'SPResult': 'Subprocess result',
+ 'SPStart': 'Subprocess start',
+ 'Task': 'Task',
+ 'Ver': 'Version information',
+ 'Watch': 'Watch event',
+ };
+
+ /**
+ * The index of this entry in the log file.
+ */
+ final int index;
+
+ /**
+ * The time at which the entry occurred.
+ */
+ final int timeStamp;
+
+ /**
+ * A list containing the descriptions of problems that were found while
+ * processing the log file, or `null` if no problems were found.
+ */
+ List<String> _problems = null;
+
+ /**
+ * Initialize a newly created log entry with the given [timeStamp].
+ */
+ LogEntry(this.index, this.timeStamp);
+
+ /**
+ * Create a log entry from the given encoded form of the [entry].
+ */
+ factory LogEntry.from(int index, String entry) {
+ if (entry.isEmpty) {
+ return null;
+ }
+ List<String> components = _parseComponents(entry);
+ int timeStamp;
+ try {
+ timeStamp = int.parse(components[0]);
+ } catch (exception) {
+ print('Invalid time stamp in "${components[0]}"; entry = "$entry"');
+ return null;
+ }
+ String entryKind = components[1];
+ if (entryKind == InstrumentationService.TAG_ANALYSIS_TASK) {
+ return new TaskEntry(index, timeStamp, components[2], components[3]);
+ } else if (entryKind == InstrumentationService.TAG_ERROR) {
+ return new ErrorEntry(index, timeStamp, entryKind, components.sublist(2));
+ } else if (entryKind == InstrumentationService.TAG_EXCEPTION) {
+ return new ExceptionEntry(
+ index, timeStamp, entryKind, components.sublist(2));
+ } else if (entryKind == InstrumentationService.TAG_FILE_READ) {
+ // Fall through
+ } else if (entryKind == InstrumentationService.TAG_LOG_ENTRY) {
+ // Fall through
+ } else if (entryKind == InstrumentationService.TAG_NOTIFICATION) {
+ Map requestData = JSON.decode(components[2]);
+ return new NotificationEntry(index, timeStamp, requestData);
+ } else if (entryKind == InstrumentationService.TAG_PERFORMANCE) {
+ // Fall through
+ } else if (entryKind == InstrumentationService.TAG_REQUEST) {
+ Map requestData = JSON.decode(components[2]);
+ return new RequestEntry(index, timeStamp, requestData);
+ } else if (entryKind == InstrumentationService.TAG_RESPONSE) {
+ Map responseData = JSON.decode(components[2]);
+ return new ResponseEntry(index, timeStamp, responseData);
+ } else if (entryKind == InstrumentationService.TAG_SUBPROCESS_START) {
+ // Fall through
+ } else if (entryKind == InstrumentationService.TAG_SUBPROCESS_RESULT) {
+ // Fall through
+ } else if (entryKind == InstrumentationService.TAG_VERSION) {
+ // Fall through
+ } else if (entryKind == InstrumentationService.TAG_WATCH_EVENT) {
+ // Fall through
+ }
+ return new GenericEntry(index, timeStamp, entryKind, components.sublist(2));
+ }
+
+ /**
+ * Return `true` if any problems were found while processing the log file.
+ */
+ bool get hasProblems => _problems != null;
+
+ /**
+ * Return the value of the component used to indicate the kind of the entry.
+ * This is the abbreviation recorded in the entry.
+ */
+ String get kind;
+
+ /**
+ * Return a human-readable representation of the kind of this entry.
+ */
+ String get kindName => kindMap[kind] ?? kind;
+
+ /**
+ * Return a list containing the descriptions of problems that were found while
+ * processing the log file, or `null` if no problems were found.
+ */
+ List<String> get problems => _problems;
+
+ /**
+ * Return a date that is equivalent to the [timeStamp].
+ */
+ DateTime get toTime => new DateTime.fromMillisecondsSinceEpoch(timeStamp);
+
+ /**
+ * Return an HTML representation of the details of the entry.
+ */
+ String details() {
+ StringBuffer buffer = new StringBuffer();
+ _appendDetails(buffer);
+ return buffer.toString();
+ }
+
+ /**
+ * Record that the given [problem] was found while processing the log file.
+ */
+ void recordProblem(String problem) {
+ _problems ??= <String>[];
+ _problems.add(problem);
+ }
+
+ /**
+ * Append details related to this entry to the given [buffer].
+ */
+ void _appendDetails(StringBuffer buffer) {
+ if (_problems != null) {
+ for (String problem in _problems) {
+ buffer.write('<p><span class="error">$problem</span></p>');
+ }
+ }
+ }
+
+ /**
+ * Parse the given encoded form of the [entry] into a list of components. The
+ * first component is always the time stamp for when the entry was generated.
+ * The second component is always the kind of the entry. The remaining
+ * components depend on the kind of the entry. Return the components that were
+ * parsed.
+ */
+ static List<String> _parseComponents(String entry) {
+ List<String> components = <String>[];
+ StringBuffer component = new StringBuffer();
+ int length = entry.length;
+ for (int i = 0; i < length; i++) {
+ int char = entry.codeUnitAt(i);
+ if (char == fieldSeparator) {
+ if (entry.codeUnitAt(i + 1) == fieldSeparator) {
+ component.write(':');
+ i++;
+ } else {
+ components.add(component.toString());
+ component.clear();
+ }
+ } else {
+ component.writeCharCode(char);
+ }
+ }
+ components.add(component.toString());
+ return components;
+ }
+}
+
+/**
+ * A log entry representing a notification that was sent from the server to the
+ * client.
+ */
+class NotificationEntry extends JsonBasedEntry {
+ /**
+ * Initialize a newly created response to have the given [timeStamp] and
+ * [notificationData].
+ */
+ NotificationEntry(int index, int timeStamp, Map notificationData)
+ : super(index, timeStamp, notificationData);
+
+ /**
+ * Return the event field of the request.
+ */
+ String get event => data['event'];
+
+ /**
+ * Return `true` if this is a server status notification.
+ */
+ bool get isServerStatus => event == 'server.status';
+
+ @override
+ String get kind => 'Noti';
+
+ /**
+ * Return the value of the parameter with the given [parameterName], or `null`
+ * if there is no such parameter.
+ */
+ dynamic param(String parameterName) {
+ var parameters = data['params'];
+ if (parameters is Map) {
+ return parameters[parameterName];
+ }
+ return null;
+ }
+}
+
+/**
+ * A log entry representing a request that was sent from the client to the
+ * server.
+ */
+class RequestEntry extends JsonBasedEntry {
+ /**
+ * Initialize a newly created response to have the given [timeStamp] and
+ * [requestData].
+ */
+ RequestEntry(int index, int timeStamp, Map requestData)
+ : super(index, timeStamp, requestData);
+
+ /**
+ * Return the clientRequestTime field of the request.
+ */
+ int get clientRequestTime => data['clientRequestTime'];
+
+ /**
+ * Return the id field of the request.
+ */
+ String get id => data['id'];
+
+ @override
+ String get kind => 'Req';
+
+ /**
+ * Return the method field of the request.
+ */
+ String get method => data['method'];
+
+ /**
+ * Return the value of the parameter with the given [parameterName], or `null`
+ * if there is no such parameter.
+ */
+ dynamic param(String parameterName) {
+ var parameters = data['params'];
+ if (parameters is Map) {
+ return parameters[parameterName];
+ }
+ return null;
+ }
+}
+
+/**
+ * A log entry representing a response that was sent from the server to the
+ * client.
+ */
+class ResponseEntry extends JsonBasedEntry {
+ /**
+ * Initialize a newly created response to have the given [timeStamp] and
+ * [responseData].
+ */
+ ResponseEntry(int index, int timeStamp, Map responseData)
+ : super(index, timeStamp, responseData);
+
+ /**
+ * Return the id field of the response.
+ */
+ String get id => data['id'];
+
+ @override
+ String get kind => 'Res';
+
+ /**
+ * Return the value of the result with the given [resultName], or `null` if
+ * there is no such result.
+ */
+ dynamic result(String resultName) {
+ var results = data['result'];
+ if (results is Map) {
+ return results[resultName];
+ }
+ return null;
+ }
+}
+
+class TaskEntry extends LogEntry {
+ /**
+ * The path to the directory at the root of the context in which analysis was
+ * being performed.
+ */
+ final String context;
+
+ /**
+ * A description of the task that was performed.
+ */
+ final String description;
+
+ /**
+ * The name of the class implementing the task.
+ */
+ String _taskName = null;
+
+ /**
+ * The description of the target of the task.
+ */
+ String _target = null;
+
+ /**
+ * Initialize a newly created entry with the given [index] and [timeStamp] to
+ * represent the execution of an analysis task in the given [context] that is
+ * described by the given [description].
+ */
+ TaskEntry(int index, int timeStamp, this.context, this.description)
+ : super(index, timeStamp);
+
+ @override
+ String get kind => 'Task';
+
+ /**
+ * Return the description of the target of the task.
+ */
+ String get target {
+ if (_target == null) {
+ _splitDescription();
+ }
+ return _target;
+ }
+
+ /**
+ * Return the name of the class implementing the task.
+ */
+ String get taskName {
+ if (_taskName == null) {
+ _splitDescription();
+ }
+ return _taskName;
+ }
+
+ @override
+ void _appendDetails(StringBuffer buffer) {
+ super._appendDetails(buffer);
+ buffer.write('<span class="label">Context:</span> ');
+ buffer.write(context);
+ buffer.write('<br><span class="label">Description: </span> ');
+ buffer.write(description);
+ }
+
+ /**
+ * Split the description to get the task name and target description.
+ */
+ void _splitDescription() {
+ int index = description.indexOf(' ');
+ if (index < 0) {
+ _taskName = '';
+ } else {
+ _taskName = description.substring(0, index);
+ }
+ index = description.lastIndexOf(' ');
+ _target = description.substring(index + 1);
+ int slash = context.lastIndexOf('/');
+ if (slash < 0) {
+ slash = context.lastIndexOf('\\');
+ }
+ if (slash >= 0) {
+ String prefix = context.substring(0, slash);
+ _target = _target.replaceAll(prefix, '...');
+ }
+ }
+}
diff --git a/pkg/analysis_server/tool/instrumentation/log_viewer.dart b/pkg/analysis_server/tool/instrumentation/log_viewer.dart
new file mode 100644
index 0000000..1d59e3b
--- /dev/null
+++ b/pkg/analysis_server/tool/instrumentation/log_viewer.dart
@@ -0,0 +1,128 @@
+// Copyright (c) 2016, 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:io' as io;
+
+import 'package:args/args.dart';
+
+import 'log/log.dart';
+import 'server.dart';
+
+/**
+ * Start a web server that will allow an instrumentation log to be viewed.
+ */
+void main(List<String> args) {
+ Driver driver = new Driver();
+ driver.start(args);
+}
+
+/**
+ * The main driver that configures and starts the web server.
+ */
+class Driver {
+ /**
+ * The flag used to specify that the user wants to have help text printed but
+ * that no other work should be done.
+ */
+ static String helpFlag = 'help';
+
+ /**
+ * The option used to specify the port on which the server should listen for
+ * requests.
+ */
+ static String portOption = 'port';
+
+ /**
+ * The port that will be used if no port number is provided on the command
+ * line.
+ */
+ static int defaultPortNumber = 11000;
+
+ /**
+ * Initialize a newly created driver.
+ */
+ Driver();
+
+ /**
+ * Create and return the parser used to parse the command-line arguments.
+ */
+ ArgParser createParser() {
+ ArgParser parser = new ArgParser();
+ parser.addFlag(helpFlag, help: 'Print this help text', negatable: false);
+ parser.addOption(portOption,
+ help: 'The port number on which the server should listen for requests',
+ defaultsTo: defaultPortNumber.toString());
+ return parser;
+ }
+
+ /**
+ * Print usage information.
+ */
+ void printUsage(ArgParser parser,
+ {String error, Object exception, StackTrace stackTrace}) {
+ if (error != null) {
+ print(error);
+ print('');
+ }
+ print('log_viewer [options] logFile');
+ print('');
+ print('Usage:');
+ print('');
+ print(
+ 'The "logFile" is the file containing the content of the log that is being viewed');
+ print('');
+ print('Options:');
+ print(parser.usage);
+ if (exception != null) {
+ print(exception);
+ }
+ if (stackTrace != null) {
+ print(stackTrace);
+ }
+ }
+
+ /**
+ * Use the given command-line [args] to configure and start the web server.
+ */
+ void start(List<String> args) {
+ ArgParser parser = createParser();
+ ArgResults options = parser.parse(args);
+ if (options[helpFlag]) {
+ printUsage(parser);
+ return;
+ }
+
+ int port = defaultPortNumber;
+ try {
+ port = int.parse(options[portOption]);
+ } catch (exception) {
+ printUsage(parser, error: 'Invalid port number');
+ return;
+ }
+
+ List<String> arguments = options.rest;
+ if (arguments == null || arguments.length != 1) {
+ printUsage(parser, error: 'Missing log file');
+ return;
+ }
+ String fileName = arguments[0];
+ io.File logFile = new io.File(fileName);
+ List<String> lines;
+ try {
+ lines = logFile.readAsLinesSync();
+ } catch (exception, stackTrace) {
+ printUsage(parser,
+ error: 'Could not read file "$fileName":',
+ exception: exception,
+ stackTrace: stackTrace);
+ return;
+ }
+
+ InstrumentationLog log =
+ new InstrumentationLog(<String>[logFile.path], lines);
+ WebServer server = new WebServer(log);
+ server.serveHttp(port);
+ print('logViewer is listening on http://localhost:$port/log');
+ }
+}
diff --git a/pkg/analysis_server/tool/instrumentation/page/log_page.dart b/pkg/analysis_server/tool/instrumentation/page/log_page.dart
new file mode 100644
index 0000000..83dd31d
--- /dev/null
+++ b/pkg/analysis_server/tool/instrumentation/page/log_page.dart
@@ -0,0 +1,264 @@
+// Copyright (c) 2016, 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:collection';
+import 'dart:math' as math;
+
+import '../log/log.dart';
+import '../server.dart';
+import 'page_writer.dart';
+
+/**
+ * A page writer that will produce the page containing access to the full
+ * content of the log.
+ */
+class LogPage extends PageWriter {
+ /**
+ * The instrumentation log to be written.
+ */
+ InstrumentationLog log;
+
+ /**
+ * The index of the first entry to be written.
+ */
+ int pageStart = 0;
+
+ /**
+ * The number of entries to be written, or `null` if all of the entries should
+ * be written.
+ */
+ int pageLength = null;
+
+ /**
+ * The number of digits in the event stamps that are the same for every entry.
+ */
+ int prefixLength;
+
+ /**
+ * The number of each kind of log entry. Currently used only for debugging and
+ * should be removed.
+ */
+ Map<String, int> counts = new HashMap<String, int>();
+
+ /**
+ * Initialize a newly created writer to write the content of the given
+ * [instrumentationLog].
+ */
+ LogPage(this.log) {
+ List<LogEntry> entries = log.logEntries;
+ prefixLength = computePrefixLength(entries);
+ for (LogEntry entry in entries) {
+ int count = counts.putIfAbsent(entry.kind, () => 0);
+ counts[entry.kind] = count + 1;
+ }
+ }
+
+ @override
+ void writeBody(StringSink sink) {
+ writeMenu(sink);
+ writeTwoColumns(
+ sink, 'leftColumn', _writeLeftColumn, 'rightColumn', _writeRightColumn);
+ }
+
+ @override
+ void writeScripts(StringSink sink) {
+ super.writeScripts(sink);
+ sink.writeln(r'''
+var highlightedRows = [];
+function clearHighlight() {
+ for (i = 0; i < highlightedRows.length; i++) {
+ setFontWeight(highlightedRows[i], "normal");
+ }
+}
+function highlight(requestId, responseId) {
+ clearHighlight();
+ setFontWeight(requestId, "bold");
+ setFontWeight(responseId, "bold");
+ highlightedRows = [requestId, responseId];
+}
+function setFontWeight(id, weight) {
+ var element = document.getElementById(id);
+ if (element != null) {
+ element.style.fontWeight = weight;
+ }
+}
+function setDetails(detailsContent) {
+ var element = document.getElementById("details");
+ if (element != null) {
+ element.innerHTML = detailsContent;
+ }
+}
+''');
+ }
+
+ /**
+ * Write the content of the style sheet (without the 'script' tag) for the
+ * page to the given [sink].
+ */
+ void writeStyleSheet(StringSink sink) {
+ super.writeStyleSheet(sink);
+ writeTwoColumnStyles(sink, 'leftColumn', 'rightColumn');
+ }
+
+ /**
+ * Return the number of milliseconds elapsed between the [startEntry] and the
+ * [endEntry], or a question .
+ */
+ String _getDuration(LogEntry startEntry, LogEntry endEntry) {
+ if (startEntry != null && endEntry != null) {
+ return (endEntry.timeStamp - startEntry.timeStamp).toString();
+ }
+ return '?';
+ }
+
+ /**
+ * Write the given log [entry] to the given [sink].
+ */
+ void _writeEntry(StringSink sink, LogEntry entry) {
+ String id = null;
+ String clickHandler = 'clearHighlight()';
+ String icon = '';
+ String description = entry.kindName;
+ if (entry is RequestEntry) {
+ String entryId = entry.id;
+ id = 'req$entryId';
+ clickHandler = 'highlight(\'req$entryId\', \'res$entryId\')';
+ icon = '→';
+ description = entry.method;
+ } else if (entry is ResponseEntry) {
+ String entryId = entry.id;
+ RequestEntry request = log.requestFor(entry);
+ id = 'res$entryId';
+ clickHandler = 'highlight(\'req$entryId\', \'res$entryId\')';
+ icon = '←';
+ if (request != null) {
+ int latency = entry.timeStamp - request.timeStamp;
+ description =
+ '${request.method} <span class="gray">($latency ms)</span>';
+ }
+ } else if (entry is NotificationEntry) {
+ id = 'e${entry.index}';
+ LogEntry pairedEntry = log.pairedEntry(entry);
+ if (pairedEntry != null) {
+ String pairedId = 'e${pairedEntry.index}';
+ clickHandler = 'highlight(\'$id\', \'$pairedId\')';
+ }
+ icon = '←';
+ description = entry.event;
+ if (entry.isServerStatus) {
+ var analysisStatus = entry.param('analysis');
+ if (analysisStatus is Map) {
+ if (analysisStatus['isAnalyzing']) {
+ description =
+ '$description <span class="gray">(analysis)</span> (<a href="${WebServer.taskPath}?analysisStart=${entry.index}">tasks</a>)';
+ } else {
+ String duration = _getDuration(pairedEntry, entry);
+ description =
+ '$description <span class="gray">(analysis - $duration ms)</span>';
+ }
+ }
+ var pubStatus = entry.param('pub');
+ if (pubStatus is Map) {
+ if (pubStatus['isListingPackageDirs']) {
+ description = '$description <span class="gray">(pub)</span>';
+ } else {
+ String duration = _getDuration(pairedEntry, entry);
+ description =
+ '$description <span class="gray">(pub - $duration ms)</span>';
+ }
+ }
+ }
+ } else if (entry is TaskEntry) {
+ description = entry.description;
+ } else if (entry is ErrorEntry) {
+ description = '<span class="error">$description</span>';
+ } else if (entry is ExceptionEntry) {
+ description = '<span class="error">$description</span>';
+ }
+ id = id == null ? '' : 'id="$id" ';
+ clickHandler = '$clickHandler; setDetails(\'${escape(entry.details())}\')';
+ String timeStamp = entry.timeStamp.toString();
+ if (prefixLength > 0) {
+ timeStamp = timeStamp.substring(prefixLength);
+ }
+
+ sink.writeln('<tr ${id}onclick="$clickHandler">');
+ sink.writeln('<td>$icon</td>');
+ sink.writeln('<td>');
+ sink.writeln(timeStamp);
+ sink.writeln('</td>');
+ sink.writeln('<td style="white-space:nowrap;">');
+ sink.writeln(description);
+ sink.writeln('</td>');
+ sink.writeln('</tr>');
+ }
+
+ /**
+ * Write the entries in the instrumentation log to the given [sink].
+ */
+ void _writeLeftColumn(StringSink sink) {
+ List<LogEntry> entries = log.nonTaskEntries;
+ int length = entries.length;
+ int pageEnd =
+ pageLength == null ? length : math.min(pageStart + pageLength, length);
+ //
+ // Write the header of the column.
+ //
+ sink.writeln('<div class="columnHeader">');
+ sink.writeln('<div style="float: left">');
+ sink.writeln('Events $pageStart - ${pageEnd - 1} of ${length - 1}');
+ sink.writeln('</div>');
+
+ sink.writeln('<div style="float: right">');
+ if (pageStart == 0) {
+ sink.writeln('<button type="button" disabled><b><</b></button>');
+ } else {
+ sink.write('<button type="button">');
+ sink.write(
+ '<a href="${WebServer.logPath}?start=${pageStart - pageLength}">');
+ sink.write('<b><</b>');
+ sink.writeln('</a></button>');
+ }
+ // TODO(brianwilkerson) Add a text field for selecting the start index.
+ if (pageEnd == length) {
+ sink.writeln('<button type="button" disabled><b>></b></button>');
+ } else {
+ sink.write('<button type="button">');
+ sink.write(
+ '<a href="${WebServer.logPath}?start=${pageStart + pageLength}">');
+ sink.write('<b>></b>');
+ sink.writeln('</a></button>');
+ }
+ sink.writeln('</div>');
+ sink.writeln('</div>');
+ //
+ // Write the main body of the column.
+ //
+ sink.writeln('<table class="fullWidth">');
+ sink.writeln('<tr>');
+ sink.writeln('<th class="narrow"></th>');
+ sink.writeln('<th>Time</th>');
+ sink.writeln('<th>Kind</th>');
+ sink.writeln('</tr>');
+ for (int i = pageStart; i < pageEnd; i++) {
+ LogEntry entry = entries[i];
+ _writeEntry(sink, entry);
+ }
+ sink.writeln('</table>');
+ }
+
+ /**
+ * Write a placeholder to the given [sink] where the details of a selected
+ * entry can be displayed.
+ */
+ void _writeRightColumn(StringSink sink) {
+ //
+ // Write the header of the column.
+ //
+ sink.writeln('<div class="columnHeader">');
+ sink.writeln('<p><b>Entry Details</b></p>');
+ sink.writeln('</div>');
+ sink.writeln('<div id="details"></div>');
+ }
+}
diff --git a/pkg/analysis_server/tool/instrumentation/page/page_writer.dart b/pkg/analysis_server/tool/instrumentation/page/page_writer.dart
new file mode 100644
index 0000000..bd7e769
--- /dev/null
+++ b/pkg/analysis_server/tool/instrumentation/page/page_writer.dart
@@ -0,0 +1,313 @@
+// Copyright (c) 2016, 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:convert';
+
+import '../log/log.dart';
+import '../server.dart';
+
+typedef void Writer(StringSink sink);
+
+/**
+ * A class used to write an HTML page.
+ */
+abstract class PageWriter {
+ /**
+ * The object used to escape special HTML characters.
+ */
+ static final HtmlEscape htmlEscape = new HtmlEscape();
+
+ /**
+ * Initialize a newly create page writer.
+ */
+ PageWriter();
+
+ /**
+ * Return the length of the common prefix for time stamps associated with the
+ * given log [entries].
+ */
+ int computePrefixLength(List<LogEntry> entries) {
+ int length = entries.length;
+ if (length < 2) {
+ return 0;
+ }
+ String firstTime = entries[0].timeStamp.toString();
+ String lastTime = entries[length - 1].timeStamp.toString();
+ int prefixLength = 0;
+ int timeLength = firstTime.length;
+ while (prefixLength < timeLength &&
+ firstTime.codeUnitAt(prefixLength) ==
+ lastTime.codeUnitAt(prefixLength)) {
+ prefixLength++;
+ }
+ return prefixLength;
+ }
+
+ /**
+ * Return an escaped version of the given [unsafe] text.
+ */
+ String escape(String unsafe) {
+ return htmlEscape.convert(unsafe);
+ }
+
+ /**
+ * Write the body of the page (without the 'body' tag) to the given [sink].
+ */
+ void writeBody(StringSink sink);
+
+ /**
+ * Write the given [date] to the given [sink].
+ */
+ void writeDate(StringSink sink, DateTime date) {
+ String isoString = date.toIso8601String();
+ int index = isoString.indexOf('T');
+ String dateString = isoString.substring(0, index);
+ String timeString = isoString.substring(index + 1);
+ sink.write(dateString);
+ sink.write(' at ');
+ sink.write(timeString);
+ }
+
+ /**
+ * Write the body of the page (without the 'body' tag) to the given [sink].
+ */
+ void writeMenu(StringSink sink) {
+ sink.writeln('<div class="menu">');
+ sink.write('<a href="${WebServer.logPath}" class="menuItem">Log</a>');
+ sink.write(' • ');
+ sink.write('<a href="${WebServer.statsPath}" class="menuItem">Stats</a>');
+ sink.writeln('</div>');
+ }
+
+ /**
+ * Write the contents of the instrumentation log to the given [sink].
+ */
+ void writePage(StringSink sink) {
+ sink.writeln('<!DOCTYPE html>');
+ sink.writeln('<html lang="en-US">');
+ sink.writeln('<head>');
+ sink.writeln('<meta charset="utf-8">');
+ sink.writeln(
+ '<meta name="viewport" content="height=device-height, width=device-width, initial-scale=1.0">');
+ sink.writeln('<title>Instrumentation Log</title>');
+ sink.writeln('<style>');
+ writeStyleSheet(sink);
+ sink.writeln('</style>');
+ sink.writeln('<script>');
+ writeScripts(sink);
+ sink.writeln('</script>');
+ sink.writeln('</head>');
+ sink.writeln('<body>');
+ writeBody(sink);
+ sink.writeln('</body>');
+ sink.writeln('</html>');
+ }
+
+ /**
+ * Write the scripts for the page (without the 'script' tag) to the given
+ * [sink].
+ */
+ void writeScripts(StringSink sink) {
+ // No common scripts.
+ }
+
+ /**
+ * Write the content of the style sheet (without the 'script' tag) for the
+ * page to the given [sink].
+ */
+ void writeStyleSheet(StringSink sink) {
+ sink.writeln(r'''
+a {
+ color: #000000;
+ text-decoration: none;
+}
+a.menuItem {
+ font-weight: bold;
+}
+body {
+ font-family: sans-serif;
+ height: 100%;
+ margin: 0px;
+ overflow: hidden;
+ padding: 0px;
+ width: 100%;
+}
+div.columnHeader {
+}
+div.button {
+ display: inline-block;
+ border-radius: 4px;
+ border: 1px solid;
+ height: 16px;
+ text-align: center;
+ vertical-align: middle;
+ width: 16px;
+}
+div.inset {
+ padding: 10px;
+}
+div.menu {
+ background-color: #cce6ff;
+ padding: 5px;
+}
+html {
+ height: 100%;
+ width: 100%;
+}
+span.button {
+ border-radius: 5px;
+ border: 1px solid;
+ height: 16px;
+ width: 16px;
+}
+span.error {
+ color: #ff0000;
+}
+span.gray {
+ color: #777777;
+}
+span.label {
+ font-weight: bold;
+}
+table.fullWidth {
+ border: 0px;
+ width: 100%;
+}
+td.halfWidth {
+ width: 50%;
+ vertical-align: top;
+}
+td.int {
+ text-align: right;
+}
+th {
+ text-align: left;
+}
+th.narrow {
+ width: 16px;
+}
+
+#container {
+ height: 100%;
+ min-height: 100%;
+ position: relative;
+ width: 100%;
+}
+#content {
+ height: 90%;
+ width: 100%;
+}
+''');
+ }
+
+ /**
+ * Write to the given [sink] the HTML required to display content in two
+ * columns. The content of the columns will be written by the functions
+ * [writeLeftColumn], [writeCenterColumn] and [writeRightColumn] and will be
+ * contained in 'div' elements with the id's [leftColumnId], [centerColumnId]
+ * and [rightColumnId].
+ */
+ void writeThreeColumns(
+ StringSink sink,
+ String leftColumnId,
+ Writer writeLeftColumn,
+ String centerColumnId,
+ Writer writeCenterColumn,
+ String rightColumnId,
+ Writer writeRightColumn) {
+ sink.writeln('<div>');
+ sink.writeln(' <div>');
+ sink.writeln(' <div id="$leftColumnId">');
+ sink.writeln(' <div class="inset">');
+ writeLeftColumn(sink);
+ sink.writeln(' </div>');
+ sink.writeln(' </div>');
+ sink.writeln(' <div id="$rightColumnId">');
+ sink.writeln(' <div class="inset">');
+ writeRightColumn(sink);
+ sink.writeln(' </div>');
+ sink.writeln(' </div>');
+ sink.writeln(' <div id="$centerColumnId">');
+ sink.writeln(' <div class="inset">');
+ writeCenterColumn(sink);
+ sink.writeln(' </div>');
+ sink.writeln(' </div>');
+ sink.writeln(' </div>');
+ sink.writeln('</div>');
+ }
+
+ /**
+ * Writeto the given [sink] the styles needed by a three column section where
+ * the columns have the ids [leftColumnId], [centerColumnId] and
+ * [rightColumnId].
+ */
+ void writeThreeColumnStyles(StringSink sink, String leftColumnId,
+ String centerColumnId, String rightColumnId) {
+ sink.writeln('''
+#$leftColumnId {
+ float: left;
+ height: 100%;
+ overflow: auto;
+ width: 33%;
+}
+#$centerColumnId {
+ height: 100%;
+ overflow: auto;
+ width: 33%;
+}
+#$rightColumnId {
+ float: right;
+ height: 100%;
+ overflow: auto;
+ width: 33%;
+}
+''');
+ }
+
+ /**
+ * Write to the given [sink] the HTML required to display content in two
+ * columns. The content of the columns will be written by the functions
+ * [writeLeftColumn] and [writeRightColumn] and will be contained in 'div'
+ * elements with the id's [leftColumnId] and [rightColumnId].
+ */
+ void writeTwoColumns(StringSink sink, String leftColumnId,
+ Writer writeLeftColumn, String rightColumnId, Writer writeRightColumn) {
+ sink.writeln('<div>');
+ sink.writeln(' <div>');
+ sink.writeln(' <div id="$leftColumnId">');
+ sink.writeln(' <div class="inset">');
+ writeLeftColumn(sink);
+ sink.writeln(' </div>');
+ sink.writeln(' </div>');
+ sink.writeln(' <div id="$rightColumnId">');
+ sink.writeln(' <div class="inset">');
+ writeRightColumn(sink);
+ sink.writeln(' </div>');
+ sink.writeln(' </div>');
+ sink.writeln(' </div>');
+ sink.writeln('</div>');
+ }
+
+ /**
+ * Writeto the given [sink] the styles needed by a two column section where
+ * the columns have the ids [leftColumnId] and [rightColumnId].
+ */
+ void writeTwoColumnStyles(
+ StringSink sink, String leftColumnId, String rightColumnId) {
+ sink.writeln('''
+#$leftColumnId {
+ float: left;
+ height: 100%;
+ overflow: auto;
+ width: 50%;
+}
+#$rightColumnId {
+ float: right;
+ height: 100%;
+ overflow: auto;
+ width: 50%;
+}
+''');
+ }
+}
diff --git a/pkg/analysis_server/tool/instrumentation/page/stats_page.dart b/pkg/analysis_server/tool/instrumentation/page/stats_page.dart
new file mode 100644
index 0000000..02ec025
--- /dev/null
+++ b/pkg/analysis_server/tool/instrumentation/page/stats_page.dart
@@ -0,0 +1,232 @@
+// Copyright (c) 2016, 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:collection';
+
+import '../log/log.dart';
+import 'page_writer.dart';
+
+/**
+ * A page writer that will produce the page containing statistics about an
+ * instrumentation log.
+ */
+class StatsPage extends PageWriter {
+ /**
+ * The instrumentation log to be written.
+ */
+ final InstrumentationLog log;
+
+ /**
+ * A table mapping the kinds of entries in the log to the number of each kind.
+ */
+ final Map<String, int> entryCounts = new HashMap<String, int>();
+
+ /**
+ * The number of responses that returned an error.
+ */
+ int errorCount = 0;
+
+ /**
+ * A table mapping request method names to a list of the latencies associated
+ * with those requests, where the latency is defined to be the time between
+ * when the request was sent by the client and when the server started
+ * processing the request.
+ */
+ final Map<String, List<int>> latencyData = new HashMap<String, List<int>>();
+
+ /**
+ * A list of the number of milliseconds between a completion request and the
+ * first event for that request.
+ */
+ final List<int> completionResponseTimes = <int>[];
+
+ /**
+ * Initialize a newly created page writer to write information about the given
+ * instrumentation [log].
+ */
+ StatsPage(this.log) {
+ _processEntries(log.logEntries);
+ }
+
+ @override
+ void writeBody(StringSink sink) {
+ writeMenu(sink);
+ sink.writeln('<div id="container">');
+ sink.writeln(' <div id="content">');
+ sink.writeln(' <div id="leftColumn">');
+ sink.writeln(' <div class="inset">');
+ _writeLeftColumn(sink);
+ sink.writeln(' </div>');
+ sink.writeln(' </div>');
+ sink.writeln(' <div id="rightColumn">');
+ sink.writeln(' <div class="inset">');
+ _writeRightColumn(sink);
+ sink.writeln(' </div>');
+ sink.writeln(' </div>');
+ sink.writeln(' </div>');
+ sink.writeln('</div>');
+ }
+
+ /**
+ * Write the content of the style sheet (without the 'script' tag) for the
+ * page to the given [sink].
+ */
+ void writeStyleSheet(StringSink sink) {
+ super.writeStyleSheet(sink);
+ sink.writeln(r'''
+#leftColumn {
+ float: left;
+ height: 100%;
+ overflow: auto;
+ width: 50%;
+}
+#rightColumn {
+ float: right;
+ height: 100%;
+ overflow: auto;
+ width: 50%;
+}
+''');
+ }
+
+ /**
+ * Return the mean of the values in the given list of [values].
+ */
+ int _mean(List<int> values) {
+ int sum = values.fold(0, (int sum, int latency) => sum + latency);
+ return sum ~/ values.length;
+ }
+
+ /**
+ * Return a table mapping the kinds of the given [entries] to the number of
+ * each kind.
+ */
+ void _processEntries(List<LogEntry> entries) {
+ void increment/*<K>*/(Map<dynamic/*=K*/, int> map, dynamic/*=K*/ key) {
+ map[key] = (map[key] ?? 0) + 1;
+ }
+
+ for (LogEntry entry in entries) {
+ String kind = entry.kind;
+ increment(entryCounts, kind);
+ if (entry is ResponseEntry) {
+ if (entry.result('error') != null) {
+ errorCount++;
+ }
+ }
+
+ if (entry is RequestEntry) {
+ String method = entry.method;
+ int latency = entry.timeStamp - entry.clientRequestTime;
+ latencyData.putIfAbsent(method, () => new List<int>()).add(latency);
+ if (method == 'completion.getSuggestions') {
+ ResponseEntry response = log.responseFor(entry);
+ if (response != null) {
+ String id = response.result('id');
+ if (id != null) {
+ List<NotificationEntry> events = log.completionEventsWithId(id);
+ if (events != null && events.length > 0) {
+ completionResponseTimes
+ .add(events[0].timeStamp - entry.timeStamp);
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ void _writeLeftColumn(StringSink sink) {
+ List<String> filePaths = log.logFilePaths;
+ List<LogEntry> entries = log.logEntries;
+ DateTime startDate = entries[0].toTime;
+ DateTime endDate = entries[entries.length - 1].toTime;
+ Duration duration = endDate.difference(startDate);
+ List<String> entryKinds = entryCounts.keys.toList()..sort();
+
+ sink.writeln('<h3>General</h3>');
+ sink.writeln('<p>');
+ if (filePaths.length == 1) {
+ sink.write('<span class="label">Log file:</span> ');
+ sink.write(filePaths[0]);
+ } else {
+ sink.write('<span class="label">Log files:</span> ');
+ bool needsSeparator = false;
+ for (String path in filePaths) {
+ if (needsSeparator) {
+ sink.write(', ');
+ } else {
+ needsSeparator = true;
+ }
+ sink.write(path);
+ }
+ }
+ sink.writeln('<br>');
+ sink.write('<span class="label">Start time:</span> ');
+ writeDate(sink, startDate);
+ sink.writeln('<br>');
+ sink.write('<span class="label">End time:</span> ');
+ writeDate(sink, endDate);
+ sink.writeln('<br>');
+ sink.write('<span class="label">Duration:</span> ');
+ sink.write(duration.toString());
+ sink.writeln('</p>');
+
+ sink.writeln('<h3>Entries</h3>');
+ sink.write('<p>');
+ sink.write('<span class="label">Number of entries:</span> ');
+ sink.write(entries.length);
+ sink.writeln('</p>');
+ sink.writeln('<table>');
+ sink.writeln('<tr><th>count</th><th>kind</th></tr>');
+ for (String kind in entryKinds) {
+ sink.write('<tr><td class="int">');
+ sink.write(entryCounts[kind]);
+ sink.write('</td><td>');
+ sink.write(kind);
+ sink.writeln('</td></tr>');
+ }
+ sink.write('<tr><td class="int">');
+ sink.write(entries.length);
+ sink.writeln('</td><td>Total</td></tr>');
+ sink.writeln('</table>');
+ }
+
+ void _writeRightColumn(StringSink sink) {
+ List<String> methodNames = latencyData.keys.toList()..sort();
+ completionResponseTimes.sort();
+
+ sink.writeln('<h3>Latency</h3>');
+ sink.write('<p>');
+ sink.write('<span class="label">Latency by method</span>');
+ sink.writeln('</p>');
+ sink.writeln('<table>');
+ sink.writeln(
+ '<tr><th>min</th><th>mean</th><th>max</th><th>method</th></tr>');
+ for (String method in methodNames) {
+ List<int> latencies = latencyData[method]..sort();
+ // TODO(brianwilkerson) Add a spark-line distribution graph.
+ sink.write('<tr><td class="int">');
+ sink.write(latencies[0]);
+ sink.write('</td><td class="int">');
+ sink.write(_mean(latencies));
+ sink.write('</td><td class="int">');
+ sink.write(latencies[latencies.length - 1]);
+ sink.write('</td><td>');
+ sink.write(method);
+ sink.writeln('</td></tr>');
+ }
+ sink.writeln('</table>');
+
+ sink.writeln('<h3>Completion</h3>');
+ sink.write('<p>');
+ sink.write('<span class="label">Time to first notification:</span> ');
+ sink.write(completionResponseTimes[0]);
+ sink.write(', ');
+ sink.write(_mean(completionResponseTimes));
+ sink.write(', ');
+ sink.write(completionResponseTimes[completionResponseTimes.length - 1]);
+ sink.writeln('</p>');
+ }
+}
diff --git a/pkg/analysis_server/tool/instrumentation/page/task_page.dart b/pkg/analysis_server/tool/instrumentation/page/task_page.dart
new file mode 100644
index 0000000..f5cd312
--- /dev/null
+++ b/pkg/analysis_server/tool/instrumentation/page/task_page.dart
@@ -0,0 +1,168 @@
+// Copyright (c) 2016, 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:math' as math;
+
+import '../log/log.dart';
+import '../server.dart';
+import 'page_writer.dart';
+
+/**
+ * A class used to write a human-readable version of the tasks executed within a
+ * single analysis step.
+ */
+class TaskPage extends PageWriter {
+ /**
+ * The instrumentation log to be written.
+ */
+ final InstrumentationLog log;
+
+ /**
+ * The index of the entry representing the start of an analysis session.
+ */
+ int analysisStart = 0;
+
+ /**
+ * The index of the first task to be written.
+ */
+ int pageStart = 0;
+
+ /**
+ * The number of tasks to be written, or `null` if all of the tasks should
+ * be written.
+ */
+ int pageLength = null;
+
+ /**
+ * The number of digits in the event stamps that are the same for every task.
+ */
+ int prefixLength;
+
+ /**
+ * Initialize a newly created page writer to write a single page worth of
+ * tasks.
+ */
+ TaskPage(this.log);
+
+ @override
+ void writeBody(StringSink sink) {
+ writeMenu(sink);
+ writeTwoColumns(
+ sink, 'leftColumn', _writeLeftColumn, 'rightColumn', _writeRightColumn);
+ }
+
+ @override
+ void writeScripts(StringSink sink) {
+ super.writeScripts(sink);
+ sink.writeln(r'''
+function setDetails(detailsContent) {
+ var element = document.getElementById("details");
+ if (element != null) {
+ element.innerHTML = detailsContent;
+ }
+}
+''');
+ }
+
+ /**
+ * Write the content of the style sheet (without the 'script' tag) for the
+ * page to the given [sink].
+ */
+ void writeStyleSheet(StringSink sink) {
+ super.writeStyleSheet(sink);
+ writeTwoColumnStyles(sink, 'leftColumn', 'rightColumn');
+ }
+
+ /**
+ * Write the given log [entry] to the given [sink].
+ */
+ void _writeEntry(StringSink sink, TaskEntry entry) {
+ String clickHandler = 'setDetails(\'${escape(entry.details())}\')';
+ String timeStamp = entry.timeStamp.toString();
+ if (prefixLength > 0) {
+ timeStamp = timeStamp.substring(prefixLength);
+ }
+
+ sink.writeln('<tr onclick="$clickHandler">');
+ sink.writeln('<td>');
+ sink.writeln(timeStamp);
+ sink.writeln('</td>');
+ sink.writeln('<td>');
+ sink.writeln(entry.taskName);
+ sink.writeln('</td>');
+ sink.writeln('<td style="white-space:nowrap;">');
+ sink.writeln(entry.target);
+ sink.writeln('</td>');
+ sink.writeln('</tr>');
+ }
+
+ /**
+ * Write the entries in the instrumentation log to the given [sink].
+ */
+ void _writeLeftColumn(StringSink sink) {
+ List<TaskEntry> entries = log.taskEntriesFor(analysisStart);
+ prefixLength = computePrefixLength(entries);
+ int length = entries.length;
+ int pageEnd =
+ pageLength == null ? length : math.min(pageStart + pageLength, length);
+ //
+ // Write the header of the column.
+ //
+ sink.writeln('<div class="columnHeader">');
+ sink.writeln('<div style="float: left">');
+ sink.writeln('Tasks $pageStart - ${pageEnd - 1} of ${length - 1}');
+ sink.writeln('</div>');
+
+ sink.writeln('<div style="float: right">');
+ if (pageStart == 0) {
+ sink.writeln('<button type="button" disabled><b><</b></button>');
+ } else {
+ sink.write('<button type="button">');
+ sink.write(
+ '<a href="${WebServer.taskPath}?analysisStart=$analysisStart&start=${pageStart - pageLength}">');
+ sink.write('<b><</b>');
+ sink.writeln('</a></button>');
+ }
+ // TODO(brianwilkerson) Add a text field for selecting the start index.
+ if (pageEnd == length) {
+ sink.writeln('<button type="button" disabled><b>></b></button>');
+ } else {
+ sink.write('<button type="button">');
+ sink.write(
+ '<a href="${WebServer.taskPath}?analysisStart=$analysisStart&start=${pageStart + pageLength}">');
+ sink.write('<b>></b>');
+ sink.writeln('</a></button>');
+ }
+ sink.writeln('</div>');
+ sink.writeln('</div>');
+ //
+ // Write the main body of the column.
+ //
+ sink.writeln('<table class="fullWidth">');
+ sink.writeln('<tr>');
+ sink.writeln('<th>Time</th>');
+ sink.writeln('<th>Task</th>');
+ sink.writeln('<th>Target</th>');
+ sink.writeln('</tr>');
+ for (int i = pageStart; i < pageEnd; i++) {
+ LogEntry entry = entries[i];
+ _writeEntry(sink, entry);
+ }
+ sink.writeln('</table>');
+ }
+
+ /**
+ * Write a placeholder to the given [sink] where the details of a selected
+ * entry can be displayed.
+ */
+ void _writeRightColumn(StringSink sink) {
+ //
+ // Write the header of the column.
+ //
+ sink.writeln('<div class="columnHeader">');
+ sink.writeln('<p><b>Task Details</b></p>');
+ sink.writeln('</div>');
+ sink.writeln('<div id="details"></div>');
+ }
+}
diff --git a/pkg/analysis_server/tool/instrumentation/server.dart b/pkg/analysis_server/tool/instrumentation/server.dart
new file mode 100644
index 0000000..324244c
--- /dev/null
+++ b/pkg/analysis_server/tool/instrumentation/server.dart
@@ -0,0 +1,236 @@
+// Copyright (c) 2016, 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 'dart:collection';
+import 'dart:io';
+
+import 'log/log.dart';
+import 'page/log_page.dart';
+import 'page/stats_page.dart';
+import 'page/task_page.dart';
+
+/**
+ * An exception that is thrown when a request is received that cannot be
+ * handled.
+ */
+class UnknownRequest implements Exception {}
+
+/**
+ * A simple web server.
+ */
+class WebServer {
+ /**
+ * The path to the page containing a single page from the instrumentation log.
+ */
+ static final String logPath = '/log';
+
+ /**
+ * The path to the page containing statistics about the instrumentation log.
+ */
+ static final String statsPath = '/stats';
+
+ /**
+ * The path to the page containing statistics about the instrumentation log.
+ */
+ static final String taskPath = '/task';
+
+ /**
+ * The content type for HTML responses.
+ */
+ static final ContentType _htmlContent =
+ new ContentType("text", "html", charset: "utf-8");
+
+ /**
+ * The instrumentation log being served up.
+ */
+ final InstrumentationLog log;
+
+ /**
+ * Future that is completed with the HTTP server once it is running.
+ */
+ Future<HttpServer> _server;
+
+ /**
+ * Initialize a newly created server.
+ */
+ WebServer(this.log);
+
+ Map<String, String> getParameterMap(HttpRequest request) {
+ Map<String, String> parameterMap = new HashMap<String, String>();
+ String query = request.uri.query;
+ if (query != null && query.isNotEmpty) {
+ List<String> pairs = query.split('&');
+ for (String pair in pairs) {
+ List<String> parts = pair.split('=');
+ String value = parts[1].trim();
+ value = value.replaceAll('+', ' ');
+ parameterMap[parts[0].trim()] = value;
+ }
+ }
+ return parameterMap;
+ }
+
+ /**
+ * Return a table mapping the names of properties to the values of those
+ * properties that is extracted from the given HTTP [request].
+ */
+ Future<Map<String, String>> getValueMap(HttpRequest request) async {
+ StringBuffer buffer = new StringBuffer();
+ await request.forEach((List<int> element) {
+ for (int code in element) {
+ buffer.writeCharCode(code);
+ }
+ });
+ Map<String, String> valueMap = new HashMap<String, String>();
+ String parameters = buffer.toString();
+ if (parameters.isNotEmpty) {
+ List<String> pairs = parameters.split('&');
+ for (String pair in pairs) {
+ List<String> parts = pair.split('=');
+ String value = parts[1].trim();
+ value = value.replaceAll('+', ' ');
+ valueMap[parts[0].trim()] = value;
+ }
+ }
+ return valueMap;
+ }
+
+ /**
+ * Begin serving HTTP requests over the given [port].
+ */
+ void serveHttp(int port) {
+ _server = HttpServer.bind(InternetAddress.LOOPBACK_IP_V4, port);
+ _server.then(_handleServer).catchError((_) {/* Ignore errors. */});
+ }
+
+ /**
+ * Handle a GET [request] received by the HTTP server.
+ */
+ void _handleGetRequest(HttpRequest request) {
+ StringBuffer buffer = new StringBuffer();
+ try {
+ String path = request.uri.path;
+ if (path == logPath) {
+ _writeLogPage(request, buffer);
+ } else if (path == statsPath) {
+ _writeStatsPage(request, buffer);
+ } else if (path == taskPath) {
+ _writeTaskPage(request, buffer);
+ } else {
+ _returnUnknownRequest(request);
+ return;
+ }
+ } on UnknownRequest {
+ _returnUnknownRequest(request);
+ return;
+ } catch (exception, stackTrace) {
+ HttpResponse response = request.response;
+ response.statusCode = HttpStatus.OK;
+ response.headers.contentType = _htmlContent;
+ StringBuffer buffer = new StringBuffer();
+ buffer.write('<p><b>Exception while composing page:</b></p>');
+ buffer.write('<p>$exception</p>');
+ buffer.write('<p>');
+ _writeStackTrace(buffer, stackTrace);
+ buffer.write('</p>');
+ response.write(buffer.toString());
+ response.close();
+ return;
+ }
+
+ HttpResponse response = request.response;
+ response.statusCode = HttpStatus.OK;
+ response.headers.contentType = _htmlContent;
+ response.write(buffer.toString());
+ response.close();
+ }
+
+ /**
+ * Handle a POST [request] received by the HTTP server.
+ */
+ Future<Null> _handlePostRequest(HttpRequest request) async {
+ _returnUnknownRequest(request);
+ }
+
+ /**
+ * Attach a listener to a newly created HTTP server.
+ */
+ void _handleServer(HttpServer httpServer) {
+ httpServer.listen((HttpRequest request) {
+ String method = request.method;
+ if (method == 'GET') {
+ _handleGetRequest(request);
+ } else if (method == 'POST') {
+ _handlePostRequest(request);
+ } else {
+ _returnUnknownRequest(request);
+ }
+ });
+ }
+
+ /**
+ * Return an error in response to an unrecognized request received by the HTTP
+ * server.
+ */
+ void _returnUnknownRequest(HttpRequest request) {
+ HttpResponse response = request.response;
+ response.statusCode = HttpStatus.NOT_FOUND;
+ response.headers.contentType =
+ new ContentType("text", "html", charset: "utf-8");
+ response.write(
+ '<html><head></head><body><h3>Page not found: "${request.uri.path}".</h3></body></html>');
+ response.close();
+ }
+
+ void _writeLogPage(HttpRequest request, StringBuffer buffer) {
+ Map<String, String> parameterMap = getParameterMap(request);
+ String startIndex = parameterMap['start'];
+ LogPage page = new LogPage(log);
+ if (startIndex != null) {
+ page.pageStart = int.parse(startIndex);
+ } else {
+ page.pageStart = 0;
+ }
+ page.pageLength = 25;
+ page.writePage(buffer);
+ }
+
+ /**
+ * Write a representation of the given [stackTrace] to the given [sink].
+ */
+ void _writeStackTrace(StringSink sink, StackTrace stackTrace) {
+ if (stackTrace != null) {
+ String trace = stackTrace.toString().replaceAll('#', '<br>#');
+ if (trace.startsWith('<br>#')) {
+ trace = trace.substring(4);
+ }
+ sink.write('<p>');
+ sink.write(trace);
+ sink.write('</p>');
+ }
+ }
+
+ void _writeStatsPage(HttpRequest request, StringBuffer buffer) {
+ new StatsPage(log).writePage(buffer);
+ }
+
+ void _writeTaskPage(HttpRequest request, StringBuffer buffer) {
+ Map<String, String> parameterMap = getParameterMap(request);
+ String analysisStart = parameterMap['analysisStart'];
+ String start = parameterMap['start'];
+ TaskPage page = new TaskPage(log);
+ if (analysisStart == null) {
+ throw new UnknownRequest();
+ }
+ page.analysisStart = int.parse(analysisStart);
+ if (start != null) {
+ page.pageStart = int.parse(start);
+ } else {
+ page.pageStart = 0;
+ }
+ page.pageLength = 25;
+ page.writePage(buffer);
+ }
+}
diff --git a/pkg/analyzer/example/parser_driver.dart b/pkg/analyzer/example/parser_driver.dart
index ccc5bb9..49ff7fb 100644
--- a/pkg/analyzer/example/parser_driver.dart
+++ b/pkg/analyzer/example/parser_driver.dart
@@ -7,9 +7,10 @@
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/ast/visitor.dart';
+import 'package:analyzer/error/error.dart';
+import 'package:analyzer/error/listener.dart';
import 'package:analyzer/src/dart/scanner/reader.dart';
import 'package:analyzer/src/dart/scanner/scanner.dart';
-import 'package:analyzer/src/generated/error.dart';
import 'package:analyzer/src/generated/parser.dart';
main(List<String> args) {
diff --git a/pkg/analyzer/lib/analyzer.dart b/pkg/analyzer/lib/analyzer.dart
index 59fea17..303cc88 100644
--- a/pkg/analyzer/lib/analyzer.dart
+++ b/pkg/analyzer/lib/analyzer.dart
@@ -7,22 +7,25 @@
import 'dart:io';
import 'package:analyzer/dart/ast/ast.dart';
+import 'package:analyzer/error/error.dart';
+import 'package:analyzer/error/listener.dart';
+import 'package:analyzer/file_system/file_system.dart' hide File;
+import 'package:analyzer/file_system/physical_file_system.dart';
import 'package:analyzer/src/dart/scanner/reader.dart';
import 'package:analyzer/src/dart/scanner/scanner.dart';
import 'package:analyzer/src/error.dart';
-import 'package:analyzer/src/generated/error.dart';
import 'package:analyzer/src/generated/parser.dart';
import 'package:analyzer/src/generated/source_io.dart';
import 'package:analyzer/src/string_source.dart';
-import 'package:analyzer/file_system/file_system.dart' hide File;
-import 'package:analyzer/file_system/physical_file_system.dart';
import 'package:path/path.dart' as pathos;
export 'package:analyzer/dart/ast/ast.dart';
export 'package:analyzer/dart/ast/visitor.dart';
+export 'package:analyzer/error/error.dart';
+export 'package:analyzer/error/listener.dart';
export 'package:analyzer/src/dart/ast/utilities.dart';
export 'package:analyzer/src/error.dart';
-export 'package:analyzer/src/generated/error.dart';
+export 'package:analyzer/src/error/codes.dart';
export 'package:analyzer/src/generated/utilities_dart.dart';
/// Parses a string of Dart code into an AST.
diff --git a/pkg/analyzer/lib/context/declared_variables.dart b/pkg/analyzer/lib/context/declared_variables.dart
index 86d6234..50c47dd 100644
--- a/pkg/analyzer/lib/context/declared_variables.dart
+++ b/pkg/analyzer/lib/context/declared_variables.dart
@@ -35,6 +35,12 @@
}
/**
+ * Return the raw string value of the variable with the given [name],
+ * or `null` of the variable is not defined.
+ */
+ String get(String name) => _declaredVariables[name];
+
+ /**
* Return the value of the variable with the given [name] interpreted as a
* 'boolean' value. If the variable is not defined (or [name] is `null`), a
* DartObject representing "unknown" is returned. If the value cannot be
diff --git a/pkg/analyzer/lib/dart/ast/ast.dart b/pkg/analyzer/lib/dart/ast/ast.dart
index 6754062..da18224 100644
--- a/pkg/analyzer/lib/dart/ast/ast.dart
+++ b/pkg/analyzer/lib/dart/ast/ast.dart
@@ -2039,12 +2039,14 @@
* Return the URI of the implementation library to be used if the condition is
* true.
*/
+ @deprecated
StringLiteral get libraryUri;
/**
* Set the URI of the implementation library to be used if the condition is
* true to the given [uri].
*/
+ @deprecated
void set libraryUri(StringLiteral uri);
/**
@@ -2070,6 +2072,28 @@
void set rightParenthesis(Token token);
/**
+ * Return the URI of the implementation library to be used if the condition is
+ * true.
+ */
+ StringLiteral get uri;
+
+ /**
+ * Set the URI of the implementation library to be used if the condition is
+ * true to the given [uri].
+ */
+ void set uri(StringLiteral uri);
+
+ /**
+ * Return the source to which the [uri] was resolved.
+ */
+ Source get uriSource;
+
+ /**
+ * Set the source to which the [uri] was resolved to the given [source].
+ */
+ void set uriSource(Source source);
+
+ /**
* Return the value to which the value of the declared variable will be
* compared, or `null` if the condition does not include an equality test.
*/
@@ -4282,9 +4306,10 @@
TypeName returnType,
SimpleIdentifier identifier,
TypeParameterList typeParameters,
- FormalParameterList parameters) =>
+ FormalParameterList parameters,
+ {Token question: null}) =>
new FunctionTypedFormalParameterImpl(comment, metadata, returnType,
- identifier, typeParameters, parameters);
+ identifier, typeParameters, parameters, question);
/**
* Return the parameters of the function-typed parameter.
@@ -4298,6 +4323,18 @@
void set parameters(FormalParameterList parameters);
/**
+ * Return the question mark marking this as a nullable type, or `null` if
+ * the type is non-nullable.
+ */
+ Token get question;
+
+ /**
+ * Return the question mark marking this as a nullable type to the given
+ * [question].
+ */
+ void set question(Token question);
+
+ /**
* Return the return type of the function, or `null` if the function does not
* have a return type.
*/
@@ -5928,6 +5965,22 @@
void set keyword(Token token);
/**
+ * Return the source that was selected based on the declared variables. This
+ * will be the source from the first configuration whose condition is true, or
+ * the [uriSource] if either there are no configurations or if there are no
+ * configurations whose condition is true.
+ */
+ Source get selectedSource;
+
+ /**
+ * Return the content of the URI that was selected based on the declared
+ * variables. This will be the URI from the first configuration whose
+ * condition is true, or the [uriContent] if either there are no
+ * configurations or if there are no configurations whose condition is true.
+ */
+ String get selectedUriContent;
+
+ /**
* Return the semicolon terminating the directive.
*/
Token get semicolon;
@@ -7706,8 +7759,9 @@
* Initialize a newly created type name. The [typeArguments] can be `null` if
* there are no type arguments.
*/
- factory TypeName(Identifier name, TypeArgumentList typeArguments) =>
- new TypeNameImpl(name, typeArguments);
+ factory TypeName(Identifier name, TypeArgumentList typeArguments,
+ {Token question: null}) =>
+ new TypeNameImpl(name, typeArguments, question);
/**
* Return `true` if this type is a deferred type.
@@ -7728,6 +7782,18 @@
void set name(Identifier identifier);
/**
+ * Return the question mark marking this as a nullable type, or `null` if
+ * the type is non-nullable.
+ */
+ Token get question;
+
+ /**
+ * Return the question mark marking this as a nullable type to the given
+ * [question].
+ */
+ void set question(Token question);
+
+ /**
* Return the type being named, or `null` if the AST structure has not been
* resolved.
*/
@@ -7851,11 +7917,13 @@
/**
* Return the source to which the URI was resolved.
*/
+ @deprecated
Source get source;
/**
* Set the source to which the URI was resolved to the given [source].
*/
+ @deprecated
void set source(Source source);
/**
@@ -7869,24 +7937,34 @@
void set uri(StringLiteral uri);
/**
- * Return the content of the URI.
+ * Return the content of the [uri].
*/
String get uriContent;
/**
- * Set the content of the URI to the given [content].
+ * Set the content of the [uri] to the given [content].
*/
void set uriContent(String content);
/**
- * Return the element associated with the URI of this directive, or `null` if
- * the AST structure has not been resolved or if the URI could not be
+ * Return the element associated with the [uri] of this directive, or `null`
+ * if the AST structure has not been resolved or if the URI could not be
* resolved. Examples of the latter case include a directive that contains an
* invalid URL or a URL that does not exist.
*/
Element get uriElement;
/**
+ * Return the source to which the [uri] was resolved.
+ */
+ Source get uriSource;
+
+ /**
+ * Set the source to which the [uri] was resolved to the given [source].
+ */
+ void set uriSource(Source source);
+
+ /**
* Validate this directive, but do not check for existence. Return a code
* indicating the problem if there is one, or `null` no problem
*/
diff --git a/pkg/analyzer/lib/dart/element/element.dart b/pkg/analyzer/lib/dart/element/element.dart
index 307ad1b..df7db66 100644
--- a/pkg/analyzer/lib/dart/element/element.dart
+++ b/pkg/analyzer/lib/dart/element/element.dart
@@ -1166,6 +1166,11 @@
*/
bool get isEnumConstant;
+ /**
+ * Returns `true` if this field can be overridden in strong mode.
+ */
+ bool get isVirtual;
+
@override
AstNode computeNode();
}
@@ -1613,6 +1618,12 @@
String get defaultValueCode;
/**
+ * Return `true` if this parameter is covariant, meaning it is allowed to have
+ * a narrower type in an override.
+ */
+ bool get isCovariant;
+
+ /**
* Return `true` if this parameter is an initializing formal parameter.
*/
bool get isInitializingFormal;
diff --git a/pkg/analyzer/lib/error/error.dart b/pkg/analyzer/lib/error/error.dart
new file mode 100644
index 0000000..622fe9e
--- /dev/null
+++ b/pkg/analyzer/lib/error/error.dart
@@ -0,0 +1,1067 @@
+// Copyright (c) 2014, 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.
+
+library analyzer.error.error;
+
+import 'dart:collection';
+
+import 'package:analyzer/dart/element/element.dart';
+import 'package:analyzer/error/listener.dart';
+import 'package:analyzer/src/dart/scanner/scanner.dart' show ScannerErrorCode;
+import 'package:analyzer/src/error/codes.dart';
+import 'package:analyzer/src/generated/java_core.dart';
+import 'package:analyzer/src/generated/parser.dart' show ParserErrorCode;
+import 'package:analyzer/src/generated/source.dart';
+
+/**
+ * An error discovered during the analysis of some Dart code.
+ *
+ * See [AnalysisErrorListener].
+ */
+class AnalysisError {
+ /**
+ * An empty array of errors used when no errors are expected.
+ */
+ static const List<AnalysisError> NO_ERRORS = const <AnalysisError>[];
+
+ /**
+ * A [Comparator] that sorts by the name of the file that the [AnalysisError]
+ * was found.
+ */
+ static Comparator<AnalysisError> FILE_COMPARATOR =
+ (AnalysisError o1, AnalysisError o2) =>
+ o1.source.shortName.compareTo(o2.source.shortName);
+
+ /**
+ * A [Comparator] that sorts error codes first by their severity (errors
+ * first, warnings second), and then by the error code type.
+ */
+ static Comparator<AnalysisError> ERROR_CODE_COMPARATOR =
+ (AnalysisError o1, AnalysisError o2) {
+ ErrorCode errorCode1 = o1.errorCode;
+ ErrorCode errorCode2 = o2.errorCode;
+ ErrorSeverity errorSeverity1 = errorCode1.errorSeverity;
+ ErrorSeverity errorSeverity2 = errorCode2.errorSeverity;
+ if (errorSeverity1 == errorSeverity2) {
+ ErrorType errorType1 = errorCode1.type;
+ ErrorType errorType2 = errorCode2.type;
+ return errorType1.compareTo(errorType2);
+ } else {
+ return errorSeverity2.compareTo(errorSeverity1);
+ }
+ };
+
+ /**
+ * The error code associated with the error.
+ */
+ final ErrorCode errorCode;
+
+ /**
+ * The localized error message.
+ */
+ String _message;
+
+ /**
+ * The correction to be displayed for this error, or `null` if there is no
+ * correction information for this error.
+ */
+ String _correction;
+
+ /**
+ * The source in which the error occurred, or `null` if unknown.
+ */
+ final Source source;
+
+ /**
+ * The character offset from the beginning of the source (zero based) where
+ * the error occurred.
+ */
+ int offset = 0;
+
+ /**
+ * The number of characters from the offset to the end of the source which
+ * encompasses the compilation error.
+ */
+ int length = 0;
+
+ /**
+ * A flag indicating whether this error can be shown to be a non-issue because
+ * of the result of type propagation.
+ */
+ bool isStaticOnly = false;
+
+ /**
+ * Initialize a newly created analysis error. The error is associated with the
+ * given [source] and is located at the given [offset] with the given
+ * [length]. The error will have the given [errorCode] and the list of
+ * [arguments] will be used to complete the message.
+ */
+ AnalysisError(this.source, this.offset, this.length, this.errorCode,
+ [List<Object> arguments]) {
+ this._message = formatList(errorCode.message, arguments);
+ String correctionTemplate = errorCode.correction;
+ if (correctionTemplate != null) {
+ this._correction = formatList(correctionTemplate, arguments);
+ }
+ }
+
+ /**
+ * Initialize a newly created analysis error with given values.
+ */
+ AnalysisError.forValues(this.source, this.offset, this.length, this.errorCode,
+ this._message, this._correction);
+
+ /**
+ * Return the template used to create the correction to be displayed for this
+ * error, or `null` if there is no correction information for this error. The
+ * correction should indicate how the user can fix the error.
+ */
+ String get correction => _correction;
+
+ @override
+ int get hashCode {
+ int hashCode = offset;
+ hashCode ^= (_message != null) ? _message.hashCode : 0;
+ hashCode ^= (source != null) ? source.hashCode : 0;
+ return hashCode;
+ }
+
+ /**
+ * Return the message to be displayed for this error. The message should
+ * indicate what is wrong and why it is wrong.
+ */
+ String get message => _message;
+
+ @override
+ bool operator ==(Object other) {
+ if (identical(other, this)) {
+ return true;
+ }
+ // prepare other AnalysisError
+ if (other is AnalysisError) {
+ // Quick checks.
+ if (!identical(errorCode, other.errorCode)) {
+ return false;
+ }
+ if (offset != other.offset || length != other.length) {
+ return false;
+ }
+ if (isStaticOnly != other.isStaticOnly) {
+ return false;
+ }
+ // Deep checks.
+ if (_message != other._message) {
+ return false;
+ }
+ if (source != other.source) {
+ return false;
+ }
+ // OK
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * Return the value of the given [property], or `null` if the given property
+ * is not defined for this error.
+ */
+ Object/*=V*/ getProperty/*<V>*/(ErrorProperty/*<V>*/ property) => null;
+
+ @override
+ String toString() {
+ StringBuffer buffer = new StringBuffer();
+ buffer.write((source != null) ? source.fullName : "<unknown source>");
+ buffer.write("(");
+ buffer.write(offset);
+ buffer.write("..");
+ buffer.write(offset + length - 1);
+ buffer.write("): ");
+ //buffer.write("(" + lineNumber + ":" + columnNumber + "): ");
+ buffer.write(_message);
+ return buffer.toString();
+ }
+
+ /**
+ * Merge all of the errors in the lists in the given list of [errorLists] into
+ * a single list of errors.
+ */
+ static List<AnalysisError> mergeLists(List<List<AnalysisError>> errorLists) {
+ Set<AnalysisError> errors = new HashSet<AnalysisError>();
+ for (List<AnalysisError> errorList in errorLists) {
+ errors.addAll(errorList);
+ }
+ return errors.toList();
+ }
+}
+
+/**
+ * An [AnalysisError] that can have arbitrary properties associated with it.
+ */
+class AnalysisErrorWithProperties extends AnalysisError {
+ /**
+ * The properties associated with this error.
+ */
+ HashMap<ErrorProperty, Object> _propertyMap =
+ new HashMap<ErrorProperty, Object>();
+
+ /**
+ * Initialize a newly created analysis error. The error is associated with the
+ * given [source] and is located at the given [offset] with the given
+ * [length]. The error will have the given [errorCode] and the list of
+ * [arguments] will be used to complete the message.
+ */
+ AnalysisErrorWithProperties(
+ Source source, int offset, int length, ErrorCode errorCode,
+ [List<Object> arguments])
+ : super(source, offset, length, errorCode, arguments);
+
+ @override
+ Object/*=V*/ getProperty/*<V>*/(ErrorProperty/*<V>*/ property) =>
+ _propertyMap[property] as Object/*=V*/;
+
+ /**
+ * Set the value of the given [property] to the given [value]. Using a value
+ * of `null` will effectively remove the property from this error.
+ */
+ void setProperty/*<V>*/(ErrorProperty/*<V>*/ property, Object/*=V*/ value) {
+ _propertyMap[property] = value;
+ }
+}
+
+/**
+ * An error code associated with an [AnalysisError].
+ *
+ * Generally, we want to provide messages that consist of three sentences. From
+ * the user's perspective these sentences should explain:
+ * 1. what is wrong,
+ * 2. why is it wrong, and
+ * 3. how do I fix it.
+ * However, we combine the first two in the [message] and the last in the
+ * [correction].
+ */
+abstract class ErrorCode {
+ /**
+ * Engine error code values.
+ */
+ static const List<ErrorCode> values = const [
+ //
+ // Manually generated. FWIW, this get's you most of the way there:
+ //
+ // > grep 'static const .*Code' (error.dart|parser|scanner.dart)
+ // | awk '{print $3"."$4","}'
+ //
+ // error.dart:
+ //
+ AnalysisOptionsErrorCode.PARSE_ERROR,
+ AnalysisOptionsWarningCode.UNSUPPORTED_OPTION_WITH_LEGAL_VALUES,
+ AnalysisOptionsWarningCode.UNSUPPORTED_OPTION_WITH_LEGAL_VALUE,
+ AnalysisOptionsWarningCode.UNSUPPORTED_VALUE,
+ AnalysisOptionsWarningCode.UNRECOGNIZED_ERROR_CODE,
+ CheckedModeCompileTimeErrorCode.CONST_CONSTRUCTOR_FIELD_TYPE_MISMATCH,
+ CheckedModeCompileTimeErrorCode.CONST_CONSTRUCTOR_PARAM_TYPE_MISMATCH,
+ CheckedModeCompileTimeErrorCode.CONST_FIELD_INITIALIZER_NOT_ASSIGNABLE,
+ CheckedModeCompileTimeErrorCode.LIST_ELEMENT_TYPE_NOT_ASSIGNABLE,
+ CheckedModeCompileTimeErrorCode.MAP_KEY_TYPE_NOT_ASSIGNABLE,
+ CheckedModeCompileTimeErrorCode.MAP_VALUE_TYPE_NOT_ASSIGNABLE,
+ CheckedModeCompileTimeErrorCode.VARIABLE_TYPE_MISMATCH,
+ CompileTimeErrorCode.ACCESS_PRIVATE_ENUM_FIELD,
+ CompileTimeErrorCode.AMBIGUOUS_EXPORT,
+ CompileTimeErrorCode.ANNOTATION_WITH_NON_CLASS,
+ CompileTimeErrorCode.ARGUMENT_DEFINITION_TEST_NON_PARAMETER,
+ CompileTimeErrorCode.ASYNC_FOR_IN_WRONG_CONTEXT,
+ CompileTimeErrorCode.AWAIT_IN_WRONG_CONTEXT,
+ CompileTimeErrorCode.BUILT_IN_IDENTIFIER_AS_TYPE,
+ CompileTimeErrorCode.BUILT_IN_IDENTIFIER_AS_TYPE_NAME,
+ CompileTimeErrorCode.BUILT_IN_IDENTIFIER_AS_TYPEDEF_NAME,
+ CompileTimeErrorCode.BUILT_IN_IDENTIFIER_AS_TYPE_PARAMETER_NAME,
+ CompileTimeErrorCode.CASE_EXPRESSION_TYPE_IMPLEMENTS_EQUALS,
+ CompileTimeErrorCode.COMPILE_TIME_CONSTANT_RAISES_EXCEPTION,
+ CompileTimeErrorCode.CONFLICTING_GETTER_AND_METHOD,
+ CompileTimeErrorCode.CONFLICTING_METHOD_AND_GETTER,
+ CompileTimeErrorCode.CONFLICTING_CONSTRUCTOR_NAME_AND_FIELD,
+ CompileTimeErrorCode.CONFLICTING_CONSTRUCTOR_NAME_AND_METHOD,
+ CompileTimeErrorCode.CONFLICTING_TYPE_VARIABLE_AND_CLASS,
+ CompileTimeErrorCode.CONFLICTING_TYPE_VARIABLE_AND_MEMBER,
+ CompileTimeErrorCode.CONST_CONSTRUCTOR_THROWS_EXCEPTION,
+ CompileTimeErrorCode.CONST_CONSTRUCTOR_WITH_FIELD_INITIALIZED_BY_NON_CONST,
+ CompileTimeErrorCode.CONST_CONSTRUCTOR_WITH_MIXIN,
+ CompileTimeErrorCode.CONST_CONSTRUCTOR_WITH_NON_CONST_SUPER,
+ CompileTimeErrorCode.CONST_CONSTRUCTOR_WITH_NON_FINAL_FIELD,
+ CompileTimeErrorCode.CONST_DEFERRED_CLASS,
+ CompileTimeErrorCode.CONST_FORMAL_PARAMETER,
+ CompileTimeErrorCode.CONST_INITIALIZED_WITH_NON_CONSTANT_VALUE,
+ CompileTimeErrorCode
+ .CONST_INITIALIZED_WITH_NON_CONSTANT_VALUE_FROM_DEFERRED_LIBRARY,
+ CompileTimeErrorCode.CONST_INSTANCE_FIELD,
+ CompileTimeErrorCode.CONST_MAP_KEY_EXPRESSION_TYPE_IMPLEMENTS_EQUALS,
+ CompileTimeErrorCode.CONST_NOT_INITIALIZED,
+ CompileTimeErrorCode.CONST_EVAL_TYPE_BOOL,
+ CompileTimeErrorCode.CONST_EVAL_TYPE_BOOL_NUM_STRING,
+ CompileTimeErrorCode.CONST_EVAL_TYPE_INT,
+ CompileTimeErrorCode.CONST_EVAL_TYPE_NUM,
+ CompileTimeErrorCode.CONST_EVAL_THROWS_EXCEPTION,
+ CompileTimeErrorCode.CONST_EVAL_THROWS_IDBZE,
+ CompileTimeErrorCode.CONST_WITH_INVALID_TYPE_PARAMETERS,
+ CompileTimeErrorCode.CONST_WITH_NON_CONST,
+ CompileTimeErrorCode.CONST_WITH_NON_CONSTANT_ARGUMENT,
+ CompileTimeErrorCode.CONST_WITH_NON_TYPE,
+ CompileTimeErrorCode.CONST_WITH_TYPE_PARAMETERS,
+ CompileTimeErrorCode.CONST_WITH_UNDEFINED_CONSTRUCTOR,
+ CompileTimeErrorCode.CONST_WITH_UNDEFINED_CONSTRUCTOR_DEFAULT,
+ CompileTimeErrorCode.DEFAULT_VALUE_IN_FUNCTION_TYPE_ALIAS,
+ CompileTimeErrorCode.DEFAULT_VALUE_IN_FUNCTION_TYPED_PARAMETER,
+ CompileTimeErrorCode.DEFAULT_VALUE_IN_REDIRECTING_FACTORY_CONSTRUCTOR,
+ CompileTimeErrorCode.DUPLICATE_CONSTRUCTOR_DEFAULT,
+ CompileTimeErrorCode.DUPLICATE_CONSTRUCTOR_NAME,
+ CompileTimeErrorCode.DUPLICATE_DEFINITION,
+ CompileTimeErrorCode.DUPLICATE_DEFINITION_INHERITANCE,
+ CompileTimeErrorCode.DUPLICATE_NAMED_ARGUMENT,
+ CompileTimeErrorCode.EXPORT_INTERNAL_LIBRARY,
+ CompileTimeErrorCode.EXPORT_OF_NON_LIBRARY,
+ CompileTimeErrorCode.EXTENDS_ENUM,
+ CompileTimeErrorCode.EXTENDS_NON_CLASS,
+ CompileTimeErrorCode.EXTENDS_DISALLOWED_CLASS,
+ CompileTimeErrorCode.EXTENDS_DEFERRED_CLASS,
+ CompileTimeErrorCode.EXTRA_ARGUMENT_TO_ASSERT,
+ CompileTimeErrorCode.EXTRA_POSITIONAL_ARGUMENTS,
+ CompileTimeErrorCode.FIELD_INITIALIZED_BY_MULTIPLE_INITIALIZERS,
+ CompileTimeErrorCode.FIELD_INITIALIZED_IN_PARAMETER_AND_INITIALIZER,
+ CompileTimeErrorCode.FINAL_INITIALIZED_MULTIPLE_TIMES,
+ CompileTimeErrorCode.FIELD_INITIALIZER_FACTORY_CONSTRUCTOR,
+ CompileTimeErrorCode.FIELD_INITIALIZER_OUTSIDE_CONSTRUCTOR,
+ CompileTimeErrorCode.FIELD_INITIALIZER_REDIRECTING_CONSTRUCTOR,
+ CompileTimeErrorCode.GETTER_AND_METHOD_WITH_SAME_NAME,
+ CompileTimeErrorCode.IMPLEMENTS_DEFERRED_CLASS,
+ CompileTimeErrorCode.IMPLEMENTS_DISALLOWED_CLASS,
+ CompileTimeErrorCode.IMPLEMENTS_DYNAMIC,
+ CompileTimeErrorCode.IMPLEMENTS_ENUM,
+ CompileTimeErrorCode.IMPLEMENTS_NON_CLASS,
+ CompileTimeErrorCode.IMPLEMENTS_REPEATED,
+ CompileTimeErrorCode.IMPLEMENTS_SUPER_CLASS,
+ CompileTimeErrorCode.IMPLICIT_THIS_REFERENCE_IN_INITIALIZER,
+ CompileTimeErrorCode.IMPORT_INTERNAL_LIBRARY,
+ CompileTimeErrorCode.IMPORT_OF_NON_LIBRARY,
+ CompileTimeErrorCode.INCONSISTENT_CASE_EXPRESSION_TYPES,
+ CompileTimeErrorCode.INITIALIZER_FOR_NON_EXISTENT_FIELD,
+ CompileTimeErrorCode.INITIALIZER_FOR_STATIC_FIELD,
+ CompileTimeErrorCode.INITIALIZING_FORMAL_FOR_NON_EXISTENT_FIELD,
+ CompileTimeErrorCode.INITIALIZING_FORMAL_FOR_STATIC_FIELD,
+ CompileTimeErrorCode.INSTANCE_MEMBER_ACCESS_FROM_FACTORY,
+ CompileTimeErrorCode.INSTANCE_MEMBER_ACCESS_FROM_STATIC,
+ CompileTimeErrorCode.INSTANTIATE_ENUM,
+ CompileTimeErrorCode.INVALID_ANNOTATION,
+ CompileTimeErrorCode.INVALID_ANNOTATION_FROM_DEFERRED_LIBRARY,
+ CompileTimeErrorCode.INVALID_IDENTIFIER_IN_ASYNC,
+ CompileTimeErrorCode.INVALID_MODIFIER_ON_CONSTRUCTOR,
+ CompileTimeErrorCode.INVALID_MODIFIER_ON_SETTER,
+ CompileTimeErrorCode.INVALID_CONSTANT,
+ CompileTimeErrorCode.INVALID_CONSTRUCTOR_NAME,
+ CompileTimeErrorCode.INVALID_FACTORY_NAME_NOT_A_CLASS,
+ CompileTimeErrorCode.INVALID_REFERENCE_TO_THIS,
+ CompileTimeErrorCode.INVALID_TYPE_ARGUMENT_IN_CONST_LIST,
+ CompileTimeErrorCode.INVALID_TYPE_ARGUMENT_IN_CONST_MAP,
+ CompileTimeErrorCode.INVALID_URI,
+ CompileTimeErrorCode.LABEL_IN_OUTER_SCOPE,
+ CompileTimeErrorCode.LABEL_UNDEFINED,
+ CompileTimeErrorCode.MEMBER_WITH_CLASS_NAME,
+ CompileTimeErrorCode.METHOD_AND_GETTER_WITH_SAME_NAME,
+ CompileTimeErrorCode.MISSING_CONST_IN_LIST_LITERAL,
+ CompileTimeErrorCode.MISSING_CONST_IN_MAP_LITERAL,
+ CompileTimeErrorCode.MIXIN_DECLARES_CONSTRUCTOR,
+ CompileTimeErrorCode.MIXIN_DEFERRED_CLASS,
+ CompileTimeErrorCode.MIXIN_HAS_NO_CONSTRUCTORS,
+ CompileTimeErrorCode.MIXIN_INHERITS_FROM_NOT_OBJECT,
+ CompileTimeErrorCode.MIXIN_OF_DISALLOWED_CLASS,
+ CompileTimeErrorCode.MIXIN_OF_ENUM,
+ CompileTimeErrorCode.MIXIN_OF_NON_CLASS,
+ CompileTimeErrorCode.MIXIN_REFERENCES_SUPER,
+ CompileTimeErrorCode.MIXIN_WITH_NON_CLASS_SUPERCLASS,
+ CompileTimeErrorCode.MULTIPLE_REDIRECTING_CONSTRUCTOR_INVOCATIONS,
+ CompileTimeErrorCode.MULTIPLE_SUPER_INITIALIZERS,
+ CompileTimeErrorCode.NO_ANNOTATION_CONSTRUCTOR_ARGUMENTS,
+ CompileTimeErrorCode.NO_DEFAULT_SUPER_CONSTRUCTOR_EXPLICIT,
+ CompileTimeErrorCode.NO_DEFAULT_SUPER_CONSTRUCTOR_IMPLICIT,
+ CompileTimeErrorCode.NON_CONST_MAP_AS_EXPRESSION_STATEMENT,
+ CompileTimeErrorCode.NON_CONSTANT_CASE_EXPRESSION,
+ CompileTimeErrorCode.NON_CONSTANT_CASE_EXPRESSION_FROM_DEFERRED_LIBRARY,
+ CompileTimeErrorCode.NON_CONSTANT_DEFAULT_VALUE,
+ CompileTimeErrorCode.NON_CONSTANT_DEFAULT_VALUE_FROM_DEFERRED_LIBRARY,
+ CompileTimeErrorCode.NON_CONSTANT_LIST_ELEMENT,
+ CompileTimeErrorCode.NON_CONSTANT_LIST_ELEMENT_FROM_DEFERRED_LIBRARY,
+ CompileTimeErrorCode.NON_CONSTANT_MAP_KEY,
+ CompileTimeErrorCode.NON_CONSTANT_MAP_KEY_FROM_DEFERRED_LIBRARY,
+ CompileTimeErrorCode.NON_CONSTANT_MAP_VALUE,
+ CompileTimeErrorCode.NON_CONSTANT_MAP_VALUE_FROM_DEFERRED_LIBRARY,
+ CompileTimeErrorCode.NON_CONSTANT_ANNOTATION_CONSTRUCTOR,
+ CompileTimeErrorCode.NON_CONSTANT_VALUE_IN_INITIALIZER,
+ CompileTimeErrorCode
+ .NON_CONSTANT_VALUE_IN_INITIALIZER_FROM_DEFERRED_LIBRARY,
+ CompileTimeErrorCode.NOT_ENOUGH_REQUIRED_ARGUMENTS,
+ CompileTimeErrorCode.NON_GENERATIVE_CONSTRUCTOR,
+ CompileTimeErrorCode.OBJECT_CANNOT_EXTEND_ANOTHER_CLASS,
+ CompileTimeErrorCode.OPTIONAL_PARAMETER_IN_OPERATOR,
+ CompileTimeErrorCode.PART_OF_NON_PART,
+ CompileTimeErrorCode.PREFIX_COLLIDES_WITH_TOP_LEVEL_MEMBER,
+ CompileTimeErrorCode.PREFIX_IDENTIFIER_NOT_FOLLOWED_BY_DOT,
+ CompileTimeErrorCode.PRIVATE_OPTIONAL_PARAMETER,
+ CompileTimeErrorCode.RECURSIVE_COMPILE_TIME_CONSTANT,
+ CompileTimeErrorCode.RECURSIVE_CONSTRUCTOR_REDIRECT,
+ CompileTimeErrorCode.RECURSIVE_FACTORY_REDIRECT,
+ CompileTimeErrorCode.RECURSIVE_INTERFACE_INHERITANCE,
+ CompileTimeErrorCode.RECURSIVE_INTERFACE_INHERITANCE_BASE_CASE_EXTENDS,
+ CompileTimeErrorCode.RECURSIVE_INTERFACE_INHERITANCE_BASE_CASE_IMPLEMENTS,
+ CompileTimeErrorCode.RECURSIVE_INTERFACE_INHERITANCE_BASE_CASE_WITH,
+ CompileTimeErrorCode.REDIRECT_TO_MISSING_CONSTRUCTOR,
+ CompileTimeErrorCode.REDIRECT_TO_NON_CLASS,
+ CompileTimeErrorCode.REDIRECT_TO_NON_CONST_CONSTRUCTOR,
+ CompileTimeErrorCode.REDIRECT_GENERATIVE_TO_MISSING_CONSTRUCTOR,
+ CompileTimeErrorCode.REDIRECT_GENERATIVE_TO_NON_GENERATIVE_CONSTRUCTOR,
+ CompileTimeErrorCode.REFERENCED_BEFORE_DECLARATION,
+ CompileTimeErrorCode.RETHROW_OUTSIDE_CATCH,
+ CompileTimeErrorCode.RETURN_IN_GENERATIVE_CONSTRUCTOR,
+ CompileTimeErrorCode.RETURN_IN_GENERATOR,
+ CompileTimeErrorCode.SHARED_DEFERRED_PREFIX,
+ CompileTimeErrorCode.SUPER_IN_INVALID_CONTEXT,
+ CompileTimeErrorCode.SUPER_IN_REDIRECTING_CONSTRUCTOR,
+ CompileTimeErrorCode.SUPER_INITIALIZER_IN_OBJECT,
+ CompileTimeErrorCode.TYPE_ARGUMENT_NOT_MATCHING_BOUNDS,
+ CompileTimeErrorCode.TYPE_ALIAS_CANNOT_REFERENCE_ITSELF,
+ CompileTimeErrorCode.UNDEFINED_CLASS,
+ CompileTimeErrorCode.UNDEFINED_CONSTRUCTOR_IN_INITIALIZER,
+ CompileTimeErrorCode.UNDEFINED_CONSTRUCTOR_IN_INITIALIZER_DEFAULT,
+ CompileTimeErrorCode.UNDEFINED_NAMED_PARAMETER,
+ CompileTimeErrorCode.URI_DOES_NOT_EXIST,
+ CompileTimeErrorCode.URI_WITH_INTERPOLATION,
+ CompileTimeErrorCode.WRONG_NUMBER_OF_PARAMETERS_FOR_OPERATOR,
+ CompileTimeErrorCode.WRONG_NUMBER_OF_PARAMETERS_FOR_OPERATOR_MINUS,
+ CompileTimeErrorCode.WRONG_NUMBER_OF_PARAMETERS_FOR_SETTER,
+ CompileTimeErrorCode.YIELD_EACH_IN_NON_GENERATOR,
+ CompileTimeErrorCode.YIELD_IN_NON_GENERATOR,
+ HintCode.ARGUMENT_TYPE_NOT_ASSIGNABLE,
+ HintCode.CAN_BE_NULL_AFTER_NULL_AWARE,
+ HintCode.DEAD_CODE,
+ HintCode.DEAD_CODE_CATCH_FOLLOWING_CATCH,
+ HintCode.DEAD_CODE_ON_CATCH_SUBTYPE,
+ HintCode.DEPRECATED_MEMBER_USE,
+ HintCode.DUPLICATE_IMPORT,
+ HintCode.DIVISION_OPTIMIZATION,
+ HintCode.INVALID_FACTORY_ANNOTATION,
+ HintCode.INVALID_FACTORY_METHOD_DECL,
+ HintCode.INVALID_FACTORY_METHOD_IMPL,
+ HintCode.IS_DOUBLE,
+ HintCode.IS_INT,
+ HintCode.IS_NOT_DOUBLE,
+ HintCode.IS_NOT_INT,
+ HintCode.IMPORT_DEFERRED_LIBRARY_WITH_LOAD_FUNCTION,
+ HintCode.INVALID_ASSIGNMENT,
+ HintCode.INVALID_USE_OF_PROTECTED_MEMBER,
+ HintCode.MISSING_JS_LIB_ANNOTATION,
+ HintCode.MISSING_REQUIRED_PARAM,
+ HintCode.MISSING_REQUIRED_PARAM_WITH_DETAILS,
+ HintCode.MISSING_RETURN,
+ HintCode.NULL_AWARE_IN_CONDITION,
+ HintCode.OVERRIDE_ON_NON_OVERRIDING_GETTER,
+ HintCode.OVERRIDE_ON_NON_OVERRIDING_FIELD,
+ HintCode.OVERRIDE_ON_NON_OVERRIDING_METHOD,
+ HintCode.OVERRIDE_ON_NON_OVERRIDING_SETTER,
+ HintCode.OVERRIDE_EQUALS_BUT_NOT_HASH_CODE,
+ HintCode.TYPE_CHECK_IS_NOT_NULL,
+ HintCode.TYPE_CHECK_IS_NULL,
+ HintCode.UNDEFINED_GETTER,
+ HintCode.UNDEFINED_HIDDEN_NAME,
+ HintCode.UNDEFINED_METHOD,
+ HintCode.UNDEFINED_OPERATOR,
+ HintCode.UNDEFINED_SETTER,
+ HintCode.UNDEFINED_SHOWN_NAME,
+ HintCode.UNNECESSARY_CAST,
+ HintCode.UNNECESSARY_NO_SUCH_METHOD,
+ HintCode.UNNECESSARY_TYPE_CHECK_FALSE,
+ HintCode.UNNECESSARY_TYPE_CHECK_TRUE,
+ HintCode.UNUSED_ELEMENT,
+ HintCode.UNUSED_FIELD,
+ HintCode.UNUSED_IMPORT,
+ HintCode.UNUSED_CATCH_CLAUSE,
+ HintCode.UNUSED_CATCH_STACK,
+ HintCode.UNUSED_LOCAL_VARIABLE,
+ HintCode.UNUSED_SHOWN_NAME,
+ HintCode.USE_OF_VOID_RESULT,
+ HintCode.FILE_IMPORT_INSIDE_LIB_REFERENCES_FILE_OUTSIDE,
+ HintCode.FILE_IMPORT_OUTSIDE_LIB_REFERENCES_FILE_INSIDE,
+ HintCode.PACKAGE_IMPORT_CONTAINS_DOT_DOT,
+ HtmlErrorCode.PARSE_ERROR,
+ HtmlWarningCode.INVALID_URI,
+ HtmlWarningCode.URI_DOES_NOT_EXIST,
+ StaticTypeWarningCode.EXPECTED_ONE_LIST_TYPE_ARGUMENTS,
+ StaticTypeWarningCode.EXPECTED_TWO_MAP_TYPE_ARGUMENTS,
+ StaticTypeWarningCode.ILLEGAL_ASYNC_GENERATOR_RETURN_TYPE,
+ StaticTypeWarningCode.ILLEGAL_ASYNC_RETURN_TYPE,
+ StaticTypeWarningCode.ILLEGAL_SYNC_GENERATOR_RETURN_TYPE,
+ StaticTypeWarningCode.INACCESSIBLE_SETTER,
+ StaticTypeWarningCode.INCONSISTENT_METHOD_INHERITANCE,
+ StaticTypeWarningCode.INSTANCE_ACCESS_TO_STATIC_MEMBER,
+ StaticTypeWarningCode.INVALID_ASSIGNMENT,
+ StaticTypeWarningCode.INVOCATION_OF_NON_FUNCTION,
+ StaticTypeWarningCode.INVOCATION_OF_NON_FUNCTION_EXPRESSION,
+ StaticTypeWarningCode.NON_BOOL_CONDITION,
+ StaticTypeWarningCode.NON_BOOL_EXPRESSION,
+ StaticTypeWarningCode.NON_BOOL_NEGATION_EXPRESSION,
+ StaticTypeWarningCode.NON_BOOL_OPERAND,
+ StaticTypeWarningCode.NON_NULLABLE_FIELD_NOT_INITIALIZED,
+ StaticTypeWarningCode.NON_TYPE_AS_TYPE_ARGUMENT,
+ StaticTypeWarningCode.RETURN_OF_INVALID_TYPE,
+ StaticTypeWarningCode.TYPE_ARGUMENT_NOT_MATCHING_BOUNDS,
+ StaticTypeWarningCode.TYPE_PARAMETER_SUPERTYPE_OF_ITS_BOUND,
+ StaticTypeWarningCode.UNDEFINED_ENUM_CONSTANT,
+ StaticTypeWarningCode.UNDEFINED_FUNCTION,
+ StaticTypeWarningCode.UNDEFINED_GETTER,
+ StaticTypeWarningCode.UNDEFINED_METHOD,
+ StaticTypeWarningCode.UNDEFINED_METHOD_WITH_CONSTRUCTOR,
+ StaticTypeWarningCode.UNDEFINED_OPERATOR,
+ StaticTypeWarningCode.UNDEFINED_SETTER,
+ StaticTypeWarningCode.UNDEFINED_SUPER_GETTER,
+ StaticTypeWarningCode.UNDEFINED_SUPER_METHOD,
+ StaticTypeWarningCode.UNDEFINED_SUPER_OPERATOR,
+ StaticTypeWarningCode.UNDEFINED_SUPER_SETTER,
+ StaticTypeWarningCode.UNQUALIFIED_REFERENCE_TO_NON_LOCAL_STATIC_MEMBER,
+ StaticTypeWarningCode.WRONG_NUMBER_OF_TYPE_ARGUMENTS,
+ StaticTypeWarningCode.YIELD_OF_INVALID_TYPE,
+ StaticTypeWarningCode.FOR_IN_OF_INVALID_TYPE,
+ StaticTypeWarningCode.FOR_IN_OF_INVALID_ELEMENT_TYPE,
+ StaticWarningCode.AMBIGUOUS_IMPORT,
+ StaticWarningCode.ARGUMENT_TYPE_NOT_ASSIGNABLE,
+ StaticWarningCode.ASSIGNMENT_TO_CONST,
+ StaticWarningCode.ASSIGNMENT_TO_FINAL,
+ StaticWarningCode.ASSIGNMENT_TO_FINAL_NO_SETTER,
+ StaticWarningCode.ASSIGNMENT_TO_FUNCTION,
+ StaticWarningCode.ASSIGNMENT_TO_METHOD,
+ StaticWarningCode.ASSIGNMENT_TO_TYPE,
+ StaticWarningCode.CASE_BLOCK_NOT_TERMINATED,
+ StaticWarningCode.CAST_TO_NON_TYPE,
+ StaticWarningCode.CONCRETE_CLASS_WITH_ABSTRACT_MEMBER,
+ StaticWarningCode.CONFLICTING_DART_IMPORT,
+ StaticWarningCode.CONFLICTING_INSTANCE_GETTER_AND_SUPERCLASS_MEMBER,
+ StaticWarningCode.CONFLICTING_INSTANCE_METHOD_SETTER,
+ StaticWarningCode.CONFLICTING_INSTANCE_METHOD_SETTER2,
+ StaticWarningCode.CONFLICTING_INSTANCE_SETTER_AND_SUPERCLASS_MEMBER,
+ StaticWarningCode.CONFLICTING_STATIC_GETTER_AND_INSTANCE_SETTER,
+ StaticWarningCode.CONFLICTING_STATIC_SETTER_AND_INSTANCE_MEMBER,
+ StaticWarningCode.CONST_WITH_ABSTRACT_CLASS,
+ StaticWarningCode.EQUAL_KEYS_IN_MAP,
+ StaticWarningCode.EXPORT_DUPLICATED_LIBRARY_NAMED,
+ StaticWarningCode.EXTRA_POSITIONAL_ARGUMENTS,
+ StaticWarningCode.FIELD_INITIALIZED_IN_INITIALIZER_AND_DECLARATION,
+ StaticWarningCode.FINAL_INITIALIZED_IN_DECLARATION_AND_CONSTRUCTOR,
+ StaticWarningCode.FIELD_INITIALIZER_NOT_ASSIGNABLE,
+ StaticWarningCode.FIELD_INITIALIZING_FORMAL_NOT_ASSIGNABLE,
+ StaticWarningCode.FINAL_NOT_INITIALIZED,
+ StaticWarningCode.FINAL_NOT_INITIALIZED_CONSTRUCTOR_1,
+ StaticWarningCode.FINAL_NOT_INITIALIZED_CONSTRUCTOR_2,
+ StaticWarningCode.FINAL_NOT_INITIALIZED_CONSTRUCTOR_3_PLUS,
+ StaticWarningCode.FUNCTION_WITHOUT_CALL,
+ StaticWarningCode.IMPORT_DUPLICATED_LIBRARY_NAMED,
+ StaticWarningCode.IMPORT_OF_NON_LIBRARY,
+ StaticWarningCode.INCONSISTENT_METHOD_INHERITANCE_GETTER_AND_METHOD,
+ StaticWarningCode.INSTANCE_METHOD_NAME_COLLIDES_WITH_SUPERCLASS_STATIC,
+ StaticWarningCode.INVALID_GETTER_OVERRIDE_RETURN_TYPE,
+ StaticWarningCode.INVALID_METHOD_OVERRIDE_NAMED_PARAM_TYPE,
+ StaticWarningCode.INVALID_METHOD_OVERRIDE_TYPE_PARAMETERS,
+ StaticWarningCode.INVALID_METHOD_OVERRIDE_TYPE_PARAMETER_BOUND,
+ StaticWarningCode.INVALID_METHOD_OVERRIDE_NORMAL_PARAM_TYPE,
+ StaticWarningCode.INVALID_METHOD_OVERRIDE_OPTIONAL_PARAM_TYPE,
+ StaticWarningCode.INVALID_METHOD_OVERRIDE_RETURN_TYPE,
+ StaticWarningCode.INVALID_OVERRIDE_DIFFERENT_DEFAULT_VALUES_NAMED,
+ StaticWarningCode.INVALID_OVERRIDE_DIFFERENT_DEFAULT_VALUES_POSITIONAL,
+ StaticWarningCode.INVALID_OVERRIDE_NAMED,
+ StaticWarningCode.INVALID_OVERRIDE_POSITIONAL,
+ StaticWarningCode.INVALID_OVERRIDE_REQUIRED,
+ StaticWarningCode.INVALID_SETTER_OVERRIDE_NORMAL_PARAM_TYPE,
+ StaticWarningCode.LIST_ELEMENT_TYPE_NOT_ASSIGNABLE,
+ StaticWarningCode.MAP_KEY_TYPE_NOT_ASSIGNABLE,
+ StaticWarningCode.MAP_VALUE_TYPE_NOT_ASSIGNABLE,
+ StaticWarningCode.MISMATCHED_GETTER_AND_SETTER_TYPES,
+ StaticWarningCode.MISMATCHED_GETTER_AND_SETTER_TYPES_FROM_SUPERTYPE,
+ StaticWarningCode.MIXED_RETURN_TYPES,
+ StaticWarningCode.NEW_WITH_ABSTRACT_CLASS,
+ StaticWarningCode.NEW_WITH_INVALID_TYPE_PARAMETERS,
+ StaticWarningCode.NEW_WITH_NON_TYPE,
+ StaticWarningCode.NEW_WITH_UNDEFINED_CONSTRUCTOR,
+ StaticWarningCode.NEW_WITH_UNDEFINED_CONSTRUCTOR_DEFAULT,
+ StaticWarningCode.NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER_FIVE_PLUS,
+ StaticWarningCode.NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER_FOUR,
+ StaticWarningCode.NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER_ONE,
+ StaticWarningCode.NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER_THREE,
+ StaticWarningCode.NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER_TWO,
+ StaticWarningCode.NON_TYPE_IN_CATCH_CLAUSE,
+ StaticWarningCode.NON_VOID_RETURN_FOR_OPERATOR,
+ StaticWarningCode.NON_VOID_RETURN_FOR_SETTER,
+ StaticWarningCode.NOT_A_TYPE,
+ StaticWarningCode.NOT_ENOUGH_REQUIRED_ARGUMENTS,
+ StaticWarningCode.PART_OF_DIFFERENT_LIBRARY,
+ StaticWarningCode.REDIRECT_TO_INVALID_FUNCTION_TYPE,
+ StaticWarningCode.REDIRECT_TO_INVALID_RETURN_TYPE,
+ StaticWarningCode.REDIRECT_TO_MISSING_CONSTRUCTOR,
+ StaticWarningCode.REDIRECT_TO_NON_CLASS,
+ StaticWarningCode.RETURN_WITHOUT_VALUE,
+ StaticWarningCode.STATIC_ACCESS_TO_INSTANCE_MEMBER,
+ StaticWarningCode.SWITCH_EXPRESSION_NOT_ASSIGNABLE,
+ StaticWarningCode.TYPE_ANNOTATION_DEFERRED_CLASS,
+ StaticWarningCode.TYPE_TEST_WITH_NON_TYPE,
+ StaticWarningCode.TYPE_TEST_WITH_UNDEFINED_NAME,
+ StaticWarningCode.TYPE_PARAMETER_REFERENCED_BY_STATIC,
+ StaticWarningCode.UNDEFINED_CLASS,
+ StaticWarningCode.UNDEFINED_CLASS_BOOLEAN,
+ StaticWarningCode.UNDEFINED_GETTER,
+ StaticWarningCode.UNDEFINED_IDENTIFIER,
+ StaticWarningCode.UNDEFINED_NAMED_PARAMETER,
+ StaticWarningCode.UNDEFINED_SETTER,
+ StaticWarningCode.UNDEFINED_STATIC_METHOD_OR_GETTER,
+ StaticWarningCode.UNDEFINED_SUPER_GETTER,
+ StaticWarningCode.UNDEFINED_SUPER_SETTER,
+ StaticWarningCode.VOID_RETURN_FOR_GETTER,
+ StaticWarningCode.MISSING_ENUM_CONSTANT_IN_SWITCH,
+ StrongModeCode.ASSIGNMENT_CAST,
+ StrongModeCode.DOWN_CAST_COMPOSITE,
+ StrongModeCode.DOWN_CAST_IMPLICIT,
+ StrongModeCode.DYNAMIC_CAST,
+ StrongModeCode.DYNAMIC_INVOKE,
+ StrongModeCode.IMPLICIT_DYNAMIC_FIELD,
+ StrongModeCode.IMPLICIT_DYNAMIC_FUNCTION,
+ StrongModeCode.IMPLICIT_DYNAMIC_INVOKE,
+ StrongModeCode.IMPLICIT_DYNAMIC_LIST_LITERAL,
+ StrongModeCode.IMPLICIT_DYNAMIC_MAP_LITERAL,
+ StrongModeCode.IMPLICIT_DYNAMIC_METHOD,
+ StrongModeCode.IMPLICIT_DYNAMIC_PARAMETER,
+ StrongModeCode.IMPLICIT_DYNAMIC_RETURN,
+ StrongModeCode.IMPLICIT_DYNAMIC_TYPE,
+ StrongModeCode.IMPLICIT_DYNAMIC_VARIABLE,
+ StrongModeCode.INFERRED_TYPE,
+ StrongModeCode.INFERRED_TYPE_ALLOCATION,
+ StrongModeCode.INFERRED_TYPE_CLOSURE,
+ StrongModeCode.INFERRED_TYPE_LITERAL,
+ StrongModeCode.INVALID_FIELD_OVERRIDE,
+ StrongModeCode.INVALID_METHOD_OVERRIDE,
+ StrongModeCode.INVALID_METHOD_OVERRIDE_FROM_BASE,
+ StrongModeCode.INVALID_METHOD_OVERRIDE_FROM_MIXIN,
+ StrongModeCode.INVALID_PARAMETER_DECLARATION,
+ StrongModeCode.INVALID_SUPER_INVOCATION,
+ StrongModeCode.NON_GROUND_TYPE_CHECK_INFO,
+ StrongModeCode.STATIC_TYPE_ERROR,
+ StrongModeCode.UNSAFE_BLOCK_CLOSURE_INFERENCE,
+ TodoCode.TODO,
+ //
+ // parser.dart:
+ //
+ ParserErrorCode.ABSTRACT_CLASS_MEMBER,
+ ParserErrorCode.ABSTRACT_ENUM,
+ ParserErrorCode.ABSTRACT_STATIC_METHOD,
+ ParserErrorCode.ABSTRACT_TOP_LEVEL_FUNCTION,
+ ParserErrorCode.ABSTRACT_TOP_LEVEL_VARIABLE,
+ ParserErrorCode.ABSTRACT_TYPEDEF,
+ ParserErrorCode.ANNOTATION_ON_ENUM_CONSTANT,
+ ParserErrorCode.ASYNC_KEYWORD_USED_AS_IDENTIFIER,
+ ParserErrorCode.ASYNC_NOT_SUPPORTED,
+ ParserErrorCode.BREAK_OUTSIDE_OF_LOOP,
+ ParserErrorCode.CLASS_IN_CLASS,
+ ParserErrorCode.COLON_IN_PLACE_OF_IN,
+ ParserErrorCode.CONST_AND_FINAL,
+ ParserErrorCode.CONST_AND_VAR,
+ ParserErrorCode.CONST_CLASS,
+ ParserErrorCode.CONST_CONSTRUCTOR_WITH_BODY,
+ ParserErrorCode.CONST_ENUM,
+ ParserErrorCode.CONST_FACTORY,
+ ParserErrorCode.CONST_METHOD,
+ ParserErrorCode.CONST_TYPEDEF,
+ ParserErrorCode.CONSTRUCTOR_WITH_RETURN_TYPE,
+ ParserErrorCode.CONTINUE_OUTSIDE_OF_LOOP,
+ ParserErrorCode.CONTINUE_WITHOUT_LABEL_IN_CASE,
+ ParserErrorCode.DEPRECATED_CLASS_TYPE_ALIAS,
+ ParserErrorCode.DIRECTIVE_AFTER_DECLARATION,
+ ParserErrorCode.DUPLICATE_LABEL_IN_SWITCH_STATEMENT,
+ ParserErrorCode.DUPLICATED_MODIFIER,
+ ParserErrorCode.EMPTY_ENUM_BODY,
+ ParserErrorCode.ENUM_IN_CLASS,
+ ParserErrorCode.EQUALITY_CANNOT_BE_EQUALITY_OPERAND,
+ ParserErrorCode.EXPECTED_CASE_OR_DEFAULT,
+ ParserErrorCode.EXPECTED_CLASS_MEMBER,
+ ParserErrorCode.EXPECTED_EXECUTABLE,
+ ParserErrorCode.EXPECTED_LIST_OR_MAP_LITERAL,
+ ParserErrorCode.EXPECTED_STRING_LITERAL,
+ ParserErrorCode.EXPECTED_TOKEN,
+ ParserErrorCode.EXPECTED_TYPE_NAME,
+ ParserErrorCode.EXPORT_DIRECTIVE_AFTER_PART_DIRECTIVE,
+ ParserErrorCode.EXTERNAL_AFTER_CONST,
+ ParserErrorCode.EXTERNAL_AFTER_FACTORY,
+ ParserErrorCode.EXTERNAL_AFTER_STATIC,
+ ParserErrorCode.EXTERNAL_CLASS,
+ ParserErrorCode.EXTERNAL_CONSTRUCTOR_WITH_BODY,
+ ParserErrorCode.EXTERNAL_ENUM,
+ ParserErrorCode.EXTERNAL_FIELD,
+ ParserErrorCode.EXTERNAL_GETTER_WITH_BODY,
+ ParserErrorCode.EXTERNAL_METHOD_WITH_BODY,
+ ParserErrorCode.EXTERNAL_OPERATOR_WITH_BODY,
+ ParserErrorCode.EXTERNAL_SETTER_WITH_BODY,
+ ParserErrorCode.EXTERNAL_TYPEDEF,
+ ParserErrorCode.FACTORY_TOP_LEVEL_DECLARATION,
+ ParserErrorCode.FACTORY_WITH_INITIALIZERS,
+ ParserErrorCode.FACTORY_WITHOUT_BODY,
+ ParserErrorCode.FIELD_INITIALIZER_OUTSIDE_CONSTRUCTOR,
+ ParserErrorCode.FINAL_AND_VAR,
+ ParserErrorCode.FINAL_CLASS,
+ ParserErrorCode.FINAL_CONSTRUCTOR,
+ ParserErrorCode.FINAL_ENUM,
+ ParserErrorCode.FINAL_METHOD,
+ ParserErrorCode.FINAL_TYPEDEF,
+ ParserErrorCode.FUNCTION_TYPED_PARAMETER_VAR,
+ ParserErrorCode.GETTER_IN_FUNCTION,
+ ParserErrorCode.GETTER_WITH_PARAMETERS,
+ ParserErrorCode.ILLEGAL_ASSIGNMENT_TO_NON_ASSIGNABLE,
+ ParserErrorCode.IMPLEMENTS_BEFORE_EXTENDS,
+ ParserErrorCode.IMPLEMENTS_BEFORE_WITH,
+ ParserErrorCode.IMPORT_DIRECTIVE_AFTER_PART_DIRECTIVE,
+ ParserErrorCode.INITIALIZED_VARIABLE_IN_FOR_EACH,
+ ParserErrorCode.INVALID_AWAIT_IN_FOR,
+ ParserErrorCode.INVALID_CODE_POINT,
+ ParserErrorCode.INVALID_COMMENT_REFERENCE,
+ ParserErrorCode.INVALID_HEX_ESCAPE,
+ ParserErrorCode.INVALID_LITERAL_IN_CONFIGURATION,
+ ParserErrorCode.INVALID_OPERATOR,
+ ParserErrorCode.INVALID_OPERATOR_FOR_SUPER,
+ ParserErrorCode.INVALID_STAR_AFTER_ASYNC,
+ ParserErrorCode.INVALID_SYNC,
+ ParserErrorCode.INVALID_UNICODE_ESCAPE,
+ ParserErrorCode.LIBRARY_DIRECTIVE_NOT_FIRST,
+ ParserErrorCode.LOCAL_FUNCTION_DECLARATION_MODIFIER,
+ ParserErrorCode.MISSING_ASSIGNABLE_SELECTOR,
+ ParserErrorCode.MISSING_ASSIGNMENT_IN_INITIALIZER,
+ ParserErrorCode.MISSING_CATCH_OR_FINALLY,
+ ParserErrorCode.MISSING_CLASS_BODY,
+ ParserErrorCode.MISSING_CLOSING_PARENTHESIS,
+ ParserErrorCode.MISSING_CONST_FINAL_VAR_OR_TYPE,
+ ParserErrorCode.MISSING_ENUM_BODY,
+ ParserErrorCode.MISSING_EXPRESSION_IN_INITIALIZER,
+ ParserErrorCode.MISSING_EXPRESSION_IN_THROW,
+ ParserErrorCode.MISSING_FUNCTION_BODY,
+ ParserErrorCode.MISSING_FUNCTION_PARAMETERS,
+ ParserErrorCode.MISSING_METHOD_PARAMETERS,
+ ParserErrorCode.MISSING_GET,
+ ParserErrorCode.MISSING_IDENTIFIER,
+ ParserErrorCode.MISSING_INITIALIZER,
+ ParserErrorCode.MISSING_KEYWORD_OPERATOR,
+ ParserErrorCode.MISSING_NAME_IN_LIBRARY_DIRECTIVE,
+ ParserErrorCode.MISSING_NAME_IN_PART_OF_DIRECTIVE,
+ ParserErrorCode.MISSING_PREFIX_IN_DEFERRED_IMPORT,
+ ParserErrorCode.MISSING_STAR_AFTER_SYNC,
+ ParserErrorCode.MISSING_STATEMENT,
+ ParserErrorCode.MISSING_TERMINATOR_FOR_PARAMETER_GROUP,
+ ParserErrorCode.MISSING_TYPEDEF_PARAMETERS,
+ ParserErrorCode.MISSING_VARIABLE_IN_FOR_EACH,
+ ParserErrorCode.MIXED_PARAMETER_GROUPS,
+ ParserErrorCode.MULTIPLE_EXTENDS_CLAUSES,
+ ParserErrorCode.MULTIPLE_IMPLEMENTS_CLAUSES,
+ ParserErrorCode.MULTIPLE_LIBRARY_DIRECTIVES,
+ ParserErrorCode.MULTIPLE_NAMED_PARAMETER_GROUPS,
+ ParserErrorCode.MULTIPLE_PART_OF_DIRECTIVES,
+ ParserErrorCode.MULTIPLE_POSITIONAL_PARAMETER_GROUPS,
+ ParserErrorCode.MULTIPLE_VARIABLES_IN_FOR_EACH,
+ ParserErrorCode.MULTIPLE_WITH_CLAUSES,
+ ParserErrorCode.NAMED_FUNCTION_EXPRESSION,
+ ParserErrorCode.NAMED_PARAMETER_OUTSIDE_GROUP,
+ ParserErrorCode.NATIVE_CLAUSE_IN_NON_SDK_CODE,
+ ParserErrorCode.NATIVE_FUNCTION_BODY_IN_NON_SDK_CODE,
+ ParserErrorCode.NON_CONSTRUCTOR_FACTORY,
+ ParserErrorCode.NON_IDENTIFIER_LIBRARY_NAME,
+ ParserErrorCode.NON_PART_OF_DIRECTIVE_IN_PART,
+ ParserErrorCode.NON_STRING_LITERAL_AS_URI,
+ ParserErrorCode.NON_USER_DEFINABLE_OPERATOR,
+ ParserErrorCode.NORMAL_BEFORE_OPTIONAL_PARAMETERS,
+ ParserErrorCode.POSITIONAL_AFTER_NAMED_ARGUMENT,
+ ParserErrorCode.POSITIONAL_PARAMETER_OUTSIDE_GROUP,
+ ParserErrorCode.REDIRECTING_CONSTRUCTOR_WITH_BODY,
+ ParserErrorCode.REDIRECTION_IN_NON_FACTORY_CONSTRUCTOR,
+ ParserErrorCode.SETTER_IN_FUNCTION,
+ ParserErrorCode.STATIC_AFTER_CONST,
+ ParserErrorCode.STATIC_AFTER_FINAL,
+ ParserErrorCode.STATIC_AFTER_VAR,
+ ParserErrorCode.STATIC_CONSTRUCTOR,
+ ParserErrorCode.STATIC_GETTER_WITHOUT_BODY,
+ ParserErrorCode.STATIC_OPERATOR,
+ ParserErrorCode.STATIC_SETTER_WITHOUT_BODY,
+ ParserErrorCode.STATIC_TOP_LEVEL_DECLARATION,
+ ParserErrorCode.SWITCH_HAS_CASE_AFTER_DEFAULT_CASE,
+ ParserErrorCode.SWITCH_HAS_MULTIPLE_DEFAULT_CASES,
+ ParserErrorCode.TOP_LEVEL_OPERATOR,
+ ParserErrorCode.TYPEDEF_IN_CLASS,
+ ParserErrorCode.UNEXPECTED_TERMINATOR_FOR_PARAMETER_GROUP,
+ ParserErrorCode.UNEXPECTED_TOKEN,
+ ParserErrorCode.WITH_BEFORE_EXTENDS,
+ ParserErrorCode.WITH_WITHOUT_EXTENDS,
+ ParserErrorCode.WRONG_SEPARATOR_FOR_NAMED_PARAMETER,
+ ParserErrorCode.WRONG_SEPARATOR_FOR_POSITIONAL_PARAMETER,
+ ParserErrorCode.WRONG_TERMINATOR_FOR_PARAMETER_GROUP,
+ ParserErrorCode.VAR_AND_TYPE,
+ ParserErrorCode.VAR_AS_TYPE_NAME,
+ ParserErrorCode.VAR_CLASS,
+ ParserErrorCode.VAR_ENUM,
+ ParserErrorCode.VAR_RETURN_TYPE,
+ ParserErrorCode.VAR_TYPEDEF,
+ ParserErrorCode.VOID_PARAMETER,
+ ParserErrorCode.VOID_VARIABLE,
+ //
+ // scanner.dart:
+ //
+ ScannerErrorCode.ILLEGAL_CHARACTER,
+ ScannerErrorCode.MISSING_DIGIT,
+ ScannerErrorCode.MISSING_HEX_DIGIT,
+ ScannerErrorCode.MISSING_QUOTE,
+ ScannerErrorCode.UNABLE_GET_CONTENT,
+ ScannerErrorCode.UNTERMINATED_MULTI_LINE_COMMENT,
+ ScannerErrorCode.UNTERMINATED_STRING_LITERAL,
+ ];
+
+ /**
+ * The lazy initialized map from [uniqueName] to the [ErrorCode] instance.
+ */
+ static HashMap<String, ErrorCode> _uniqueNameToCodeMap;
+
+ /**
+ * An empty list of error codes.
+ */
+ static const List<ErrorCode> EMPTY_LIST = const <ErrorCode>[];
+
+ /**
+ * The name of the error code.
+ */
+ final String name;
+
+ /**
+ * The template used to create the message to be displayed for this error. The
+ * message should indicate what is wrong and why it is wrong.
+ */
+ final String message;
+
+ /**
+ * The template used to create the correction to be displayed for this error,
+ * or `null` if there is no correction information for this error. The
+ * correction should indicate how the user can fix the error.
+ */
+ final String correction;
+
+ /**
+ * Initialize a newly created error code to have the given [name]. The message
+ * associated with the error will be created from the given [message]
+ * template. The correction associated with the error will be created from the
+ * given [correction] template.
+ */
+ const ErrorCode(this.name, this.message, [this.correction]);
+
+ /**
+ * The severity of the error.
+ */
+ ErrorSeverity get errorSeverity;
+
+ /**
+ * The type of the error.
+ */
+ ErrorType get type;
+
+ /**
+ * The unique name of this error code.
+ */
+ String get uniqueName => "$runtimeType.$name";
+
+ @override
+ String toString() => uniqueName;
+
+ /**
+ * Return the [ErrorCode] with the given [uniqueName], or `null` if not
+ * found.
+ */
+ static ErrorCode byUniqueName(String uniqueName) {
+ if (_uniqueNameToCodeMap == null) {
+ _uniqueNameToCodeMap = new HashMap<String, ErrorCode>();
+ for (ErrorCode errorCode in values) {
+ _uniqueNameToCodeMap[errorCode.uniqueName] = errorCode;
+ }
+ }
+ return _uniqueNameToCodeMap[uniqueName];
+ }
+}
+
+/**
+ * The properties that can be associated with an [AnalysisError].
+ */
+class ErrorProperty<V> extends Enum<ErrorProperty> {
+ /**
+ * A property whose value is a list of [FieldElement]s that are final, but
+ * not initialized by a constructor.
+ */
+ static const ErrorProperty<List<FieldElement>> NOT_INITIALIZED_FIELDS =
+ const ErrorProperty<List<FieldElement>>('NOT_INITIALIZED_FIELDS', 0);
+
+ /**
+ * A property whose value is the name of the library that is used by all
+ * of the "part of" directives, so should be used in the "library" directive.
+ * Is `null` if there is no a single name used by all of the parts.
+ */
+ static const ErrorProperty<String> PARTS_LIBRARY_NAME =
+ const ErrorProperty<String>('PARTS_LIBRARY_NAME', 1);
+
+ /**
+ * A property whose value is a list of [ExecutableElement] that should
+ * be but are not implemented by a concrete class.
+ */
+ static const ErrorProperty<List<ExecutableElement>> UNIMPLEMENTED_METHODS =
+ const ErrorProperty<List<ExecutableElement>>('UNIMPLEMENTED_METHODS', 2);
+
+ static const List<ErrorProperty> values = const [
+ NOT_INITIALIZED_FIELDS,
+ PARTS_LIBRARY_NAME,
+ UNIMPLEMENTED_METHODS
+ ];
+
+ const ErrorProperty(String name, int ordinal) : super(name, ordinal);
+}
+
+/**
+ * The severity of an [ErrorCode].
+ */
+class ErrorSeverity extends Enum<ErrorSeverity> {
+ /**
+ * The severity representing a non-error. This is never used for any error
+ * code, but is useful for clients.
+ */
+ static const ErrorSeverity NONE = const ErrorSeverity('NONE', 0, " ", "none");
+
+ /**
+ * The severity representing an informational level analysis issue.
+ */
+ static const ErrorSeverity INFO = const ErrorSeverity('INFO', 1, "I", "info");
+
+ /**
+ * The severity representing a warning. Warnings can become errors if the `-Werror` command
+ * line flag is specified.
+ */
+ static const ErrorSeverity WARNING =
+ const ErrorSeverity('WARNING', 2, "W", "warning");
+
+ /**
+ * The severity representing an error.
+ */
+ static const ErrorSeverity ERROR =
+ const ErrorSeverity('ERROR', 3, "E", "error");
+
+ static const List<ErrorSeverity> values = const [NONE, INFO, WARNING, ERROR];
+
+ /**
+ * The name of the severity used when producing machine output.
+ */
+ final String machineCode;
+
+ /**
+ * The name of the severity used when producing readable output.
+ */
+ final String displayName;
+
+ /**
+ * Initialize a newly created severity with the given names.
+ *
+ * Parameters:
+ * 0: the name of the severity used when producing machine output
+ * 1: the name of the severity used when producing readable output
+ */
+ const ErrorSeverity(
+ String name, int ordinal, this.machineCode, this.displayName)
+ : super(name, ordinal);
+
+ /**
+ * Return the severity constant that represents the greatest severity.
+ */
+ ErrorSeverity max(ErrorSeverity severity) =>
+ this.ordinal >= severity.ordinal ? this : severity;
+}
+
+/**
+ * The type of an [ErrorCode].
+ */
+class ErrorType extends Enum<ErrorType> {
+ /**
+ * Task (todo) comments in user code.
+ */
+ static const ErrorType TODO = const ErrorType('TODO', 0, ErrorSeverity.INFO);
+
+ /**
+ * Extra analysis run over the code to follow best practices, which are not in
+ * the Dart Language Specification.
+ */
+ static const ErrorType HINT = const ErrorType('HINT', 1, ErrorSeverity.INFO);
+
+ /**
+ * Compile-time errors are errors that preclude execution. A compile time
+ * error must be reported by a Dart compiler before the erroneous code is
+ * executed.
+ */
+ static const ErrorType COMPILE_TIME_ERROR =
+ const ErrorType('COMPILE_TIME_ERROR', 2, ErrorSeverity.ERROR);
+
+ /**
+ * Checked mode compile-time errors are errors that preclude execution in
+ * checked mode.
+ */
+ static const ErrorType CHECKED_MODE_COMPILE_TIME_ERROR = const ErrorType(
+ 'CHECKED_MODE_COMPILE_TIME_ERROR', 3, ErrorSeverity.ERROR);
+
+ /**
+ * Static warnings are those warnings reported by the static checker. They
+ * have no effect on execution. Static warnings must be provided by Dart
+ * compilers used during development.
+ */
+ static const ErrorType STATIC_WARNING =
+ const ErrorType('STATIC_WARNING', 4, ErrorSeverity.WARNING);
+
+ /**
+ * Many, but not all, static warnings relate to types, in which case they are
+ * known as static type warnings.
+ */
+ static const ErrorType STATIC_TYPE_WARNING =
+ const ErrorType('STATIC_TYPE_WARNING', 5, ErrorSeverity.WARNING);
+
+ /**
+ * Syntactic errors are errors produced as a result of input that does not
+ * conform to the grammar.
+ */
+ static const ErrorType SYNTACTIC_ERROR =
+ const ErrorType('SYNTACTIC_ERROR', 6, ErrorSeverity.ERROR);
+
+ /**
+ * Lint warnings describe style and best practice recommendations that can be
+ * used to formalize a project's style guidelines.
+ */
+ static const ErrorType LINT = const ErrorType('LINT', 7, ErrorSeverity.INFO);
+
+ static const List<ErrorType> values = const [
+ TODO,
+ HINT,
+ COMPILE_TIME_ERROR,
+ CHECKED_MODE_COMPILE_TIME_ERROR,
+ STATIC_WARNING,
+ STATIC_TYPE_WARNING,
+ SYNTACTIC_ERROR,
+ LINT
+ ];
+
+ /**
+ * The severity of this type of error.
+ */
+ final ErrorSeverity severity;
+
+ /**
+ * Initialize a newly created error type to have the given [name] and
+ * [severity].
+ */
+ const ErrorType(String name, int ordinal, this.severity)
+ : super(name, ordinal);
+
+ String get displayName => name.toLowerCase().replaceAll('_', ' ');
+}
diff --git a/pkg/analyzer/lib/error/listener.dart b/pkg/analyzer/lib/error/listener.dart
new file mode 100644
index 0000000..1f75fcb
--- /dev/null
+++ b/pkg/analyzer/lib/error/listener.dart
@@ -0,0 +1,322 @@
+// Copyright (c) 2014, 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.
+
+library analyzer.error.listener;
+
+import 'dart:collection';
+
+import 'package:analyzer/dart/ast/ast.dart' show AstNode;
+import 'package:analyzer/dart/ast/token.dart';
+import 'package:analyzer/dart/element/element.dart';
+import 'package:analyzer/dart/element/type.dart';
+import 'package:analyzer/error/error.dart';
+import 'package:analyzer/src/dart/element/type.dart';
+import 'package:analyzer/src/generated/source.dart';
+import 'package:source_span/source_span.dart';
+
+/**
+ * An object that listen for [AnalysisError]s being produced by the analysis
+ * engine.
+ */
+abstract class AnalysisErrorListener {
+ /**
+ * An error listener that ignores errors that are reported to it.
+ */
+ static final AnalysisErrorListener NULL_LISTENER = new _NullErrorListener();
+
+ /**
+ * This method is invoked when an [error] has been found by the analysis
+ * engine.
+ */
+ void onError(AnalysisError error);
+}
+
+/**
+ * An [AnalysisErrorListener] that keeps track of whether any error has been
+ * reported to it.
+ */
+class BooleanErrorListener implements AnalysisErrorListener {
+ /**
+ * A flag indicating whether an error has been reported to this listener.
+ */
+ bool _errorReported = false;
+
+ /**
+ * Return `true` if an error has been reported to this listener.
+ */
+ bool get errorReported => _errorReported;
+
+ @override
+ void onError(AnalysisError error) {
+ _errorReported = true;
+ }
+}
+
+/**
+ * An object used to create analysis errors and report then to an error
+ * listener.
+ */
+class ErrorReporter {
+ /**
+ * The error listener to which errors will be reported.
+ */
+ final AnalysisErrorListener _errorListener;
+
+ /**
+ * The default source to be used when reporting errors.
+ */
+ final Source _defaultSource;
+
+ /**
+ * The source to be used when reporting errors.
+ */
+ Source _source;
+
+ /**
+ * Initialize a newly created error reporter that will report errors to the
+ * given [_errorListener]. Errors will be reported against the
+ * [_defaultSource] unless another source is provided later.
+ */
+ ErrorReporter(this._errorListener, this._defaultSource) {
+ if (_errorListener == null) {
+ throw new ArgumentError("An error listener must be provided");
+ } else if (_defaultSource == null) {
+ throw new ArgumentError("A default source must be provided");
+ }
+ this._source = _defaultSource;
+ }
+
+ Source get source => _source;
+
+ /**
+ * Set the source to be used when reporting errors to the given [source].
+ * Setting the source to `null` will cause the default source to be used.
+ */
+ void set source(Source source) {
+ this._source = source ?? _defaultSource;
+ }
+
+ /**
+ * Creates an error with properties with the given [errorCode] and
+ * [arguments]. The [node] is used to compute the location of the error.
+ */
+ AnalysisErrorWithProperties newErrorWithProperties(
+ ErrorCode errorCode, AstNode node, List<Object> arguments) =>
+ new AnalysisErrorWithProperties(
+ _source, node.offset, node.length, errorCode, arguments);
+
+ /**
+ * Report the given [error].
+ */
+ void reportError(AnalysisError error) {
+ _errorListener.onError(error);
+ }
+
+ /**
+ * Report an error with the given [errorCode] and [arguments]. The [element]
+ * is used to compute the location of the error.
+ */
+ void reportErrorForElement(ErrorCode errorCode, Element element,
+ [List<Object> arguments]) {
+ int length = 0;
+ if (element is ImportElement) {
+ length = 6; // 'import'.length
+ } else if (element is ExportElement) {
+ length = 6; // 'export'.length
+ } else {
+ length = element.nameLength;
+ }
+ reportErrorForOffset(errorCode, element.nameOffset, length, arguments);
+ }
+
+ /**
+ * Report an error with the given [errorCode] and [arguments].
+ * The [node] is used to compute the location of the error.
+ *
+ * If the arguments contain the names of two or more types, the method
+ * [reportTypeErrorForNode] should be used and the types
+ * themselves (rather than their names) should be passed as arguments.
+ */
+ void reportErrorForNode(ErrorCode errorCode, AstNode node,
+ [List<Object> arguments]) {
+ reportErrorForOffset(errorCode, node.offset, node.length, arguments);
+ }
+
+ /**
+ * Report an error with the given [errorCode] and [arguments]. The location of
+ * the error is specified by the given [offset] and [length].
+ */
+ void reportErrorForOffset(ErrorCode errorCode, int offset, int length,
+ [List<Object> arguments]) {
+ _errorListener.onError(
+ new AnalysisError(_source, offset, length, errorCode, arguments));
+ }
+
+ /**
+ * Report an error with the given [errorCode] and [arguments]. The location of
+ * the error is specified by the given [span].
+ */
+ void reportErrorForSpan(ErrorCode errorCode, SourceSpan span,
+ [List<Object> arguments]) {
+ reportErrorForOffset(errorCode, span.start.offset, span.length, arguments);
+ }
+
+ /**
+ * Report an error with the given [errorCode] and [arguments]. The [token] is
+ * used to compute the location of the error.
+ */
+ void reportErrorForToken(ErrorCode errorCode, Token token,
+ [List<Object> arguments]) {
+ reportErrorForOffset(errorCode, token.offset, token.length, arguments);
+ }
+
+ /**
+ * Report an error with the given [errorCode] and [arguments]. The [node] is
+ * used to compute the location of the error. The arguments are expected to
+ * contain two or more types. Convert the types into strings by using the
+ * display names of the types, unless there are two or more types with the
+ * same names, in which case the extended display names of the types will be
+ * used in order to clarify the message.
+ *
+ * If there are not two or more types in the argument list, the method
+ * [reportErrorForNode] should be used instead.
+ */
+ void reportTypeErrorForNode(
+ ErrorCode errorCode, AstNode node, List<Object> arguments) {
+ _convertTypeNames(arguments);
+ reportErrorForOffset(errorCode, node.offset, node.length, arguments);
+ }
+
+ /**
+ * Given an array of [arguments] that is expected to contain two or more
+ * types, convert the types into strings by using the display names of the
+ * types, unless there are two or more types with the same names, in which
+ * case the extended display names of the types will be used in order to
+ * clarify the message.
+ */
+ void _convertTypeNames(List<Object> arguments) {
+ String displayName(DartType type) {
+ if (type is FunctionType) {
+ String name = type.name;
+ if (name != null && name.length > 0) {
+ StringBuffer buffer = new StringBuffer();
+ buffer.write(name);
+ (type as TypeImpl).appendTo(buffer);
+ return buffer.toString();
+ }
+ }
+ return type.displayName;
+ }
+
+ if (_hasEqualTypeNames(arguments)) {
+ int count = arguments.length;
+ for (int i = 0; i < count; i++) {
+ Object argument = arguments[i];
+ if (argument is DartType) {
+ Element element = argument.element;
+ if (element == null) {
+ arguments[i] = displayName(argument);
+ } else {
+ arguments[i] =
+ element.getExtendedDisplayName(displayName(argument));
+ }
+ }
+ }
+ } else {
+ int count = arguments.length;
+ for (int i = 0; i < count; i++) {
+ Object argument = arguments[i];
+ if (argument is DartType) {
+ arguments[i] = displayName(argument);
+ }
+ }
+ }
+ }
+
+ /**
+ * Return `true` if the given array of [arguments] contains two or more types
+ * with the same display name.
+ */
+ bool _hasEqualTypeNames(List<Object> arguments) {
+ int count = arguments.length;
+ HashSet<String> typeNames = new HashSet<String>();
+ for (int i = 0; i < count; i++) {
+ Object argument = arguments[i];
+ if (argument is DartType && !typeNames.add(argument.displayName)) {
+ return true;
+ }
+ }
+ return false;
+ }
+}
+
+/**
+ * An error listener that will record the errors that are reported to it in a
+ * way that is appropriate for caching those errors within an analysis context.
+ */
+class RecordingErrorListener implements AnalysisErrorListener {
+ /**
+ * A map of sets containing the errors that were collected, keyed by each
+ * source.
+ */
+ Map<Source, HashSet<AnalysisError>> _errors =
+ new HashMap<Source, HashSet<AnalysisError>>();
+
+ /**
+ * Return the errors collected by the listener.
+ */
+ List<AnalysisError> get errors {
+ int numEntries = _errors.length;
+ if (numEntries == 0) {
+ return AnalysisError.NO_ERRORS;
+ }
+ List<AnalysisError> resultList = new List<AnalysisError>();
+ for (HashSet<AnalysisError> errors in _errors.values) {
+ resultList.addAll(errors);
+ }
+ return resultList;
+ }
+
+ /**
+ * Add all of the errors recorded by the given [listener] to this listener.
+ */
+ void addAll(RecordingErrorListener listener) {
+ for (AnalysisError error in listener.errors) {
+ onError(error);
+ }
+ }
+
+ /**
+ * Return the errors collected by the listener for the given [source].
+ */
+ List<AnalysisError> getErrorsForSource(Source source) {
+ HashSet<AnalysisError> errorsForSource = _errors[source];
+ if (errorsForSource == null) {
+ return AnalysisError.NO_ERRORS;
+ } else {
+ return new List.from(errorsForSource);
+ }
+ }
+
+ @override
+ void onError(AnalysisError error) {
+ Source source = error.source;
+ HashSet<AnalysisError> errorsForSource = _errors[source];
+ if (_errors[source] == null) {
+ errorsForSource = new HashSet<AnalysisError>();
+ _errors[source] = errorsForSource;
+ }
+ errorsForSource.add(error);
+ }
+}
+
+/**
+ * An [AnalysisErrorListener] that ignores error.
+ */
+class _NullErrorListener implements AnalysisErrorListener {
+ @override
+ void onError(AnalysisError event) {
+ // Ignore errors
+ }
+}
diff --git a/pkg/analyzer/lib/plugin/options.dart b/pkg/analyzer/lib/plugin/options.dart
index 725315e..632c4d9 100644
--- a/pkg/analyzer/lib/plugin/options.dart
+++ b/pkg/analyzer/lib/plugin/options.dart
@@ -6,8 +6,8 @@
/// analysis options file.
library analyzer.plugin.options;
+import 'package:analyzer/error/listener.dart';
import 'package:analyzer/src/generated/engine.dart';
-import 'package:analyzer/src/generated/error.dart';
import 'package:analyzer/src/plugin/options_plugin.dart';
import 'package:plugin/plugin.dart';
import 'package:yaml/yaml.dart';
diff --git a/pkg/analyzer/lib/source/custom_resolver.dart b/pkg/analyzer/lib/source/custom_resolver.dart
new file mode 100644
index 0000000..f5bbf46
--- /dev/null
+++ b/pkg/analyzer/lib/source/custom_resolver.dart
@@ -0,0 +1,30 @@
+// Copyright (c) 2016, 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.
+
+library analyzer.source.custom_resolver;
+
+import 'package:analyzer/file_system/file_system.dart';
+import 'package:analyzer/src/generated/source.dart';
+
+class CustomUriResolver extends UriResolver {
+ final ResourceProvider resourceProvider;
+ final Map<String, String> _urlMappings;
+
+ CustomUriResolver(this.resourceProvider, this._urlMappings);
+
+ @override
+ Source resolveAbsolute(Uri uri, [Uri actualUri]) {
+ String mapping = _urlMappings[uri.toString()];
+ if (mapping == null) {
+ return null;
+ }
+ Uri fileUri = new Uri.file(mapping);
+ if (!fileUri.isAbsolute) {
+ return null;
+ }
+ return resourceProvider
+ .getFile(resourceProvider.pathContext.fromUri(fileUri))
+ .createSource(actualUri ?? uri);
+ }
+}
diff --git a/pkg/analyzer/lib/source/error_processor.dart b/pkg/analyzer/lib/source/error_processor.dart
index 81778bc..b5fe38f 100644
--- a/pkg/analyzer/lib/source/error_processor.dart
+++ b/pkg/analyzer/lib/source/error_processor.dart
@@ -4,9 +4,12 @@
library analyzer.source.error_processor;
+import 'package:analyzer/error/error.dart';
+import 'package:analyzer/src/error/codes.dart';
import 'package:analyzer/src/generated/engine.dart';
-import 'package:analyzer/src/generated/error.dart';
import 'package:analyzer/src/generated/utilities_general.dart';
+import 'package:analyzer/src/task/options.dart'
+ show CONFIGURED_ERROR_PROCESSORS;
import 'package:analyzer/src/task/options.dart';
import 'package:yaml/yaml.dart';
diff --git a/pkg/analyzer/lib/src/context/context.dart b/pkg/analyzer/lib/src/context/context.dart
index ba82c4d..7e8b4d3 100644
--- a/pkg/analyzer/lib/src/context/context.dart
+++ b/pkg/analyzer/lib/src/context/context.dart
@@ -10,6 +10,7 @@
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/type.dart';
+import 'package:analyzer/error/error.dart';
import 'package:analyzer/exception/exception.dart';
import 'package:analyzer/instrumentation/instrumentation.dart';
import 'package:analyzer/plugin/resolver_provider.dart';
@@ -21,7 +22,6 @@
import 'package:analyzer/src/dart/element/type.dart';
import 'package:analyzer/src/generated/constant.dart';
import 'package:analyzer/src/generated/engine.dart';
-import 'package:analyzer/src/generated/error.dart';
import 'package:analyzer/src/generated/incremental_resolver.dart';
import 'package:analyzer/src/generated/resolver.dart';
import 'package:analyzer/src/generated/sdk.dart' show DartSdk;
diff --git a/pkg/analyzer/lib/src/dart/ast/ast.dart b/pkg/analyzer/lib/src/dart/ast/ast.dart
index d5ed4cf..eca142a 100644
--- a/pkg/analyzer/lib/src/dart/ast/ast.dart
+++ b/pkg/analyzer/lib/src/dart/ast/ast.dart
@@ -16,6 +16,7 @@
import 'package:analyzer/src/dart/element/element.dart';
import 'package:analyzer/src/dart/element/type.dart';
import 'package:analyzer/src/generated/engine.dart' show AnalysisEngine;
+import 'package:analyzer/src/generated/java_core.dart';
import 'package:analyzer/src/generated/java_engine.dart';
import 'package:analyzer/src/generated/parser.dart';
import 'package:analyzer/src/generated/source.dart' show LineInfo, Source;
@@ -938,9 +939,9 @@
@override
String toSource() {
- StringBuffer buffer = new StringBuffer();
- accept(new ToSourceVisitor(buffer));
- return buffer.toString();
+ PrintStringWriter writer = new PrintStringWriter();
+ accept(new ToSourceVisitor(writer));
+ return writer.toString();
}
@override
@@ -2594,15 +2595,24 @@
class ConfigurationImpl extends AstNodeImpl implements Configuration {
@override
Token ifKeyword;
+
@override
Token leftParenthesis;
+
DottedName _name;
+
@override
Token equalToken;
+
StringLiteral _value;
+
@override
Token rightParenthesis;
- StringLiteral _libraryUri;
+
+ StringLiteral _uri;
+
+ @override
+ Source uriSource;
ConfigurationImpl(
this.ifKeyword,
@@ -2614,7 +2624,7 @@
StringLiteralImpl libraryUri) {
_name = _becomeParentOf(name);
_value = _becomeParentOf(value);
- _libraryUri = _becomeParentOf(libraryUri);
+ _uri = _becomeParentOf(libraryUri);
}
@override
@@ -2628,17 +2638,19 @@
..add(equalToken)
..add(_value)
..add(rightParenthesis)
- ..add(_libraryUri);
+ ..add(_uri);
@override
- Token get endToken => _libraryUri.endToken;
+ Token get endToken => _uri.endToken;
+ @deprecated
@override
- StringLiteral get libraryUri => _libraryUri;
+ StringLiteral get libraryUri => _uri;
+ @deprecated
@override
void set libraryUri(StringLiteral libraryUri) {
- _libraryUri = _becomeParentOf(libraryUri as AstNodeImpl);
+ _uri = _becomeParentOf(libraryUri as AstNodeImpl);
}
@override
@@ -2650,6 +2662,14 @@
}
@override
+ StringLiteral get uri => _uri;
+
+ @override
+ void set uri(StringLiteral uri) {
+ _uri = _becomeParentOf(uri as AstNodeImpl);
+ }
+
+ @override
StringLiteral get value => _value;
@override
@@ -2665,7 +2685,7 @@
void visitChildren(AstVisitor visitor) {
_name?.accept(visitor);
_value?.accept(visitor);
- _libraryUri?.accept(visitor);
+ _uri?.accept(visitor);
}
}
@@ -5443,6 +5463,9 @@
*/
FormalParameterList _parameters;
+ @override
+ Token question;
+
/**
* Initialize a newly created formal parameter. Either or both of the
* [comment] and [metadata] can be `null` if the parameter does not have the
@@ -5455,7 +5478,8 @@
TypeNameImpl returnType,
SimpleIdentifierImpl identifier,
TypeParameterListImpl typeParameters,
- FormalParameterListImpl parameters)
+ FormalParameterListImpl parameters,
+ this.question)
: super(comment, metadata, identifier) {
_returnType = _becomeParentOf(returnType);
_typeParameters = _becomeParentOf(typeParameters);
@@ -7454,6 +7478,12 @@
@override
Token semicolon;
+ @override
+ String selectedUriContent;
+
+ @override
+ Source selectedSource;
+
/**
* Initialize a newly created namespace directive. Either or both of the
* [comment] and [metadata] can be `null` if the directive does not have the
@@ -7485,6 +7515,16 @@
@override
Token get firstTokenAfterCommentAndMetadata => keyword;
+ @deprecated
+ @override
+ Source get source => selectedSource;
+
+ @deprecated
+ @override
+ void set source(Source source) {
+ selectedSource = source;
+ }
+
@override
LibraryElement get uriElement;
}
@@ -10267,6 +10307,9 @@
*/
TypeArgumentList _typeArguments;
+ @override
+ Token question;
+
/**
* The type being named, or `null` if the AST structure has not been resolved.
*/
@@ -10276,7 +10319,8 @@
* Initialize a newly created type name. The [typeArguments] can be `null` if
* there are no type arguments.
*/
- TypeNameImpl(IdentifierImpl name, TypeArgumentListImpl typeArguments) {
+ TypeNameImpl(
+ IdentifierImpl name, TypeArgumentListImpl typeArguments, this.question) {
_name = _becomeParentOf(name);
_typeArguments = _becomeParentOf(typeArguments);
}
@@ -10495,15 +10539,11 @@
*/
StringLiteral _uri;
- /**
- * The content of the URI.
- */
+ @override
String uriContent;
- /**
- * The source to which the URI was resolved.
- */
- Source source;
+ @override
+ Source uriSource;
/**
* Initialize a newly create URI-based directive. Either or both of the
@@ -10516,6 +10556,16 @@
_uri = _becomeParentOf(uri);
}
+ @deprecated
+ @override
+ Source get source => uriSource;
+
+ @deprecated
+ @override
+ void set source(Source source) {
+ uriSource = source;
+ }
+
@override
StringLiteral get uri => _uri;
@@ -10526,15 +10576,28 @@
@override
UriValidationCode validate() {
- StringLiteral uriLiteral = this.uri;
+ return validateUri(this is ImportDirective, uri, uriContent);
+ }
+
+ @override
+ void visitChildren(AstVisitor visitor) {
+ super.visitChildren(visitor);
+ _uri?.accept(visitor);
+ }
+
+ /**
+ * Validate this directive, but do not check for existence. Return a code
+ * indicating the problem if there is one, or `null` no problem.
+ */
+ static UriValidationCode validateUri(
+ bool isImport, StringLiteral uriLiteral, String uriContent) {
if (uriLiteral is StringInterpolation) {
return UriValidationCode.URI_WITH_INTERPOLATION;
}
- String uriContent = this.uriContent;
if (uriContent == null) {
return UriValidationCode.INVALID_URI;
}
- if (this is ImportDirective && uriContent.startsWith(_DART_EXT_SCHEME)) {
+ if (isImport && uriContent.startsWith(_DART_EXT_SCHEME)) {
return UriValidationCode.URI_WITH_DART_EXT_SCHEME;
}
Uri uri;
@@ -10548,12 +10611,6 @@
}
return null;
}
-
- @override
- void visitChildren(AstVisitor visitor) {
- super.visitChildren(visitor);
- _uri?.accept(visitor);
- }
}
/**
diff --git a/pkg/analyzer/lib/src/dart/ast/utilities.dart b/pkg/analyzer/lib/src/dart/ast/utilities.dart
index c128343..f8ecce5 100644
--- a/pkg/analyzer/lib/src/dart/ast/utilities.dart
+++ b/pkg/analyzer/lib/src/dart/ast/utilities.dart
@@ -11,8 +11,10 @@
import 'package:analyzer/dart/ast/visitor.dart';
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/exception/exception.dart';
+import 'package:analyzer/src/dart/ast/ast.dart';
import 'package:analyzer/src/dart/ast/token.dart';
import 'package:analyzer/src/generated/engine.dart' show AnalysisEngine;
+import 'package:analyzer/src/generated/java_core.dart';
import 'package:analyzer/src/generated/utilities_collection.dart' show TokenMap;
import 'package:analyzer/src/generated/utilities_dart.dart';
@@ -275,7 +277,7 @@
cloneToken(node.equalToken),
cloneNode(node.value),
cloneToken(node.rightParenthesis),
- cloneNode(node.libraryUri));
+ cloneNode(node.uri));
@override
ConstructorDeclaration visitConstructorDeclaration(
@@ -374,7 +376,7 @@
@override
ExportDirective visitExportDirective(ExportDirective node) {
- ExportDirective directive = new ExportDirective(
+ ExportDirectiveImpl directive = new ExportDirective(
cloneNode(node.documentationComment),
cloneNodeList(node.metadata),
cloneToken(node.keyword),
@@ -382,7 +384,9 @@
cloneNodeList(node.configurations),
cloneNodeList(node.combinators),
cloneToken(node.semicolon));
- directive.source = node.source;
+ directive.selectedUriContent = node.selectedUriContent;
+ directive.selectedSource = node.selectedSource;
+ directive.uriSource = node.uriSource;
directive.uriContent = node.uriContent;
return directive;
}
@@ -545,7 +549,7 @@
@override
ImportDirective visitImportDirective(ImportDirective node) {
- ImportDirective directive = new ImportDirective(
+ ImportDirectiveImpl directive = new ImportDirective(
cloneNode(node.documentationComment),
cloneNodeList(node.metadata),
cloneToken(node.keyword),
@@ -556,7 +560,9 @@
cloneNode(node.prefix),
cloneNodeList(node.combinators),
cloneToken(node.semicolon));
- directive.source = node.source;
+ directive.selectedUriContent = node.selectedUriContent;
+ directive.selectedSource = node.selectedSource;
+ directive.uriSource = node.uriSource;
directive.uriContent = node.uriContent;
return directive;
}
@@ -704,7 +710,7 @@
cloneToken(node.partKeyword),
cloneNode(node.uri),
cloneToken(node.semicolon));
- directive.source = node.source;
+ directive.uriSource = node.uriSource;
directive.uriContent = node.uriContent;
return directive;
}
@@ -1263,7 +1269,7 @@
isEqualTokens(node.equalToken, other.equalToken) &&
isEqualNodes(node.value, other.value) &&
isEqualTokens(node.rightParenthesis, other.rightParenthesis) &&
- isEqualNodes(node.libraryUri, other.libraryUri);
+ isEqualNodes(node.uri, other.uri);
}
@override
@@ -2852,7 +2858,7 @@
_mapToken(node.equalToken),
_cloneNode(node.value),
_mapToken(node.rightParenthesis),
- _cloneNode(node.libraryUri));
+ _cloneNode(node.uri));
@override
ConstructorDeclaration visitConstructorDeclaration(
@@ -4166,8 +4172,8 @@
} else if (identical(node.value, _oldNode)) {
node.value = _newNode as StringLiteral;
return true;
- } else if (identical(node.libraryUri, _oldNode)) {
- node.libraryUri = _newNode as StringLiteral;
+ } else if (identical(node.uri, _oldNode)) {
+ node.uri = _newNode as StringLiteral;
return true;
}
return visitNode(node);
@@ -5356,7 +5362,7 @@
_isEqualTokens(node.equalToken, toNode.equalToken),
_isEqualNodes(node.value, toNode.value),
_isEqualTokens(node.rightParenthesis, toNode.rightParenthesis),
- _isEqualNodes(node.libraryUri, toNode.libraryUri))) {
+ _isEqualNodes(node.uri, toNode.uri))) {
return true;
}
return false;
@@ -6695,15 +6701,15 @@
*/
class ToSourceVisitor implements AstVisitor<Object> {
/**
- * The buffer to which the source is to be written.
+ * The writer to which the source is to be written.
*/
- final StringBuffer _buffer;
+ final PrintWriter _writer;
/**
* Initialize a newly created visitor to write source code representing the
- * visited nodes to the given [_buffer].
+ * visited nodes to the given [writer].
*/
- ToSourceVisitor(this._buffer);
+ ToSourceVisitor(this._writer);
@override
Object visitAdjacentStrings(AdjacentStrings node) {
@@ -6713,7 +6719,7 @@
@override
Object visitAnnotation(Annotation node) {
- _buffer.write('@');
+ _writer.print('@');
_visitNode(node.name);
_visitNodeWithPrefix(".", node.constructorName);
_visitNode(node.arguments);
@@ -6722,45 +6728,45 @@
@override
Object visitArgumentList(ArgumentList node) {
- _buffer.write('(');
+ _writer.print('(');
_visitNodeListWithSeparator(node.arguments, ", ");
- _buffer.write(')');
+ _writer.print(')');
return null;
}
@override
Object visitAsExpression(AsExpression node) {
_visitNode(node.expression);
- _buffer.write(" as ");
+ _writer.print(" as ");
_visitNode(node.type);
return null;
}
@override
Object visitAssertStatement(AssertStatement node) {
- _buffer.write("assert (");
+ _writer.print("assert (");
_visitNode(node.condition);
if (node.message != null) {
- _buffer.write(', ');
+ _writer.print(', ');
_visitNode(node.message);
}
- _buffer.write(");");
+ _writer.print(");");
return null;
}
@override
Object visitAssignmentExpression(AssignmentExpression node) {
_visitNode(node.leftHandSide);
- _buffer.write(' ');
- _buffer.write(node.operator.lexeme);
- _buffer.write(' ');
+ _writer.print(' ');
+ _writer.print(node.operator.lexeme);
+ _writer.print(' ');
_visitNode(node.rightHandSide);
return null;
}
@override
Object visitAwaitExpression(AwaitExpression node) {
- _buffer.write("await ");
+ _writer.print("await ");
_visitNode(node.expression);
return null;
}
@@ -6768,18 +6774,18 @@
@override
Object visitBinaryExpression(BinaryExpression node) {
_visitNode(node.leftOperand);
- _buffer.write(' ');
- _buffer.write(node.operator.lexeme);
- _buffer.write(' ');
+ _writer.print(' ');
+ _writer.print(node.operator.lexeme);
+ _writer.print(' ');
_visitNode(node.rightOperand);
return null;
}
@override
Object visitBlock(Block node) {
- _buffer.write('{');
+ _writer.print('{');
_visitNodeListWithSeparator(node.statements, " ");
- _buffer.write('}');
+ _writer.print('}');
return null;
}
@@ -6787,11 +6793,11 @@
Object visitBlockFunctionBody(BlockFunctionBody node) {
Token keyword = node.keyword;
if (keyword != null) {
- _buffer.write(keyword.lexeme);
+ _writer.print(keyword.lexeme);
if (node.star != null) {
- _buffer.write('*');
+ _writer.print('*');
}
- _buffer.write(' ');
+ _writer.print(' ');
}
_visitNode(node.block);
return null;
@@ -6799,15 +6805,15 @@
@override
Object visitBooleanLiteral(BooleanLiteral node) {
- _buffer.write(node.literal.lexeme);
+ _writer.print(node.literal.lexeme);
return null;
}
@override
Object visitBreakStatement(BreakStatement node) {
- _buffer.write("break");
+ _writer.print("break");
_visitNodeWithPrefix(" ", node.label);
- _buffer.write(";");
+ _writer.print(";");
return null;
}
@@ -6823,14 +6829,14 @@
_visitNodeWithPrefix("on ", node.exceptionType);
if (node.catchKeyword != null) {
if (node.exceptionType != null) {
- _buffer.write(' ');
+ _writer.print(' ');
}
- _buffer.write("catch (");
+ _writer.print("catch (");
_visitNode(node.exceptionParameter);
_visitNodeWithPrefix(", ", node.stackTraceParameter);
- _buffer.write(") ");
+ _writer.print(") ");
} else {
- _buffer.write(" ");
+ _writer.print(" ");
}
_visitNode(node.body);
return null;
@@ -6840,15 +6846,15 @@
Object visitClassDeclaration(ClassDeclaration node) {
_visitNodeListWithSeparatorAndSuffix(node.metadata, " ", " ");
_visitTokenWithSuffix(node.abstractKeyword, " ");
- _buffer.write("class ");
+ _writer.print("class ");
_visitNode(node.name);
_visitNode(node.typeParameters);
_visitNodeWithPrefix(" ", node.extendsClause);
_visitNodeWithPrefix(" ", node.withClause);
_visitNodeWithPrefix(" ", node.implementsClause);
- _buffer.write(" {");
+ _writer.print(" {");
_visitNodeListWithSeparator(node.members, " ");
- _buffer.write("}");
+ _writer.print("}");
return null;
}
@@ -6856,16 +6862,16 @@
Object visitClassTypeAlias(ClassTypeAlias node) {
_visitNodeListWithSeparatorAndSuffix(node.metadata, " ", " ");
if (node.abstractKeyword != null) {
- _buffer.write("abstract ");
+ _writer.print("abstract ");
}
- _buffer.write("class ");
+ _writer.print("class ");
_visitNode(node.name);
_visitNode(node.typeParameters);
- _buffer.write(" = ");
+ _writer.print(" = ");
_visitNode(node.superclass);
_visitNodeWithPrefix(" ", node.withClause);
_visitNodeWithPrefix(" ", node.implementsClause);
- _buffer.write(";");
+ _writer.print(";");
return null;
}
@@ -6890,20 +6896,20 @@
@override
Object visitConditionalExpression(ConditionalExpression node) {
_visitNode(node.condition);
- _buffer.write(" ? ");
+ _writer.print(" ? ");
_visitNode(node.thenExpression);
- _buffer.write(" : ");
+ _writer.print(" : ");
_visitNode(node.elseExpression);
return null;
}
@override
Object visitConfiguration(Configuration node) {
- _buffer.write('if (');
+ _writer.print('if (');
_visitNode(node.name);
_visitNodeWithPrefix(" == ", node.value);
- _buffer.write(') ');
- _visitNode(node.libraryUri);
+ _writer.print(') ');
+ _visitNode(node.uri);
return null;
}
@@ -6926,7 +6932,7 @@
Object visitConstructorFieldInitializer(ConstructorFieldInitializer node) {
_visitTokenWithSuffix(node.thisKeyword, ".");
_visitNode(node.fieldName);
- _buffer.write(" = ");
+ _writer.print(" = ");
_visitNode(node.expression);
return null;
}
@@ -6940,9 +6946,9 @@
@override
Object visitContinueStatement(ContinueStatement node) {
- _buffer.write("continue");
+ _writer.print("continue");
_visitNodeWithPrefix(" ", node.label);
- _buffer.write(";");
+ _writer.print(";");
return null;
}
@@ -6959,8 +6965,8 @@
Object visitDefaultFormalParameter(DefaultFormalParameter node) {
_visitNode(node.parameter);
if (node.separator != null) {
- _buffer.write(" ");
- _buffer.write(node.separator.lexeme);
+ _writer.print(" ");
+ _writer.print(node.separator.lexeme);
_visitNodeWithPrefix(" ", node.defaultValue);
}
return null;
@@ -6968,11 +6974,11 @@
@override
Object visitDoStatement(DoStatement node) {
- _buffer.write("do ");
+ _writer.print("do ");
_visitNode(node.body);
- _buffer.write(" while (");
+ _writer.print(" while (");
_visitNode(node.condition);
- _buffer.write(");");
+ _writer.print(");");
return null;
}
@@ -6984,19 +6990,19 @@
@override
Object visitDoubleLiteral(DoubleLiteral node) {
- _buffer.write(node.literal.lexeme);
+ _writer.print(node.literal.lexeme);
return null;
}
@override
Object visitEmptyFunctionBody(EmptyFunctionBody node) {
- _buffer.write(';');
+ _writer.print(';');
return null;
}
@override
Object visitEmptyStatement(EmptyStatement node) {
- _buffer.write(';');
+ _writer.print(';');
return null;
}
@@ -7010,21 +7016,21 @@
@override
Object visitEnumDeclaration(EnumDeclaration node) {
_visitNodeListWithSeparatorAndSuffix(node.metadata, " ", " ");
- _buffer.write("enum ");
+ _writer.print("enum ");
_visitNode(node.name);
- _buffer.write(" {");
+ _writer.print(" {");
_visitNodeListWithSeparator(node.constants, ", ");
- _buffer.write("}");
+ _writer.print("}");
return null;
}
@override
Object visitExportDirective(ExportDirective node) {
_visitNodeListWithSeparatorAndSuffix(node.metadata, " ", " ");
- _buffer.write("export ");
+ _writer.print("export ");
_visitNode(node.uri);
_visitNodeListWithSeparatorAndPrefix(" ", node.combinators, " ");
- _buffer.write(';');
+ _writer.print(';');
return null;
}
@@ -7032,13 +7038,13 @@
Object visitExpressionFunctionBody(ExpressionFunctionBody node) {
Token keyword = node.keyword;
if (keyword != null) {
- _buffer.write(keyword.lexeme);
- _buffer.write(' ');
+ _writer.print(keyword.lexeme);
+ _writer.print(' ');
}
- _buffer.write("=> ");
+ _writer.print("=> ");
_visitNode(node.expression);
if (node.semicolon != null) {
- _buffer.write(';');
+ _writer.print(';');
}
return null;
}
@@ -7046,13 +7052,13 @@
@override
Object visitExpressionStatement(ExpressionStatement node) {
_visitNode(node.expression);
- _buffer.write(';');
+ _writer.print(';');
return null;
}
@override
Object visitExtendsClause(ExtendsClause node) {
- _buffer.write("extends ");
+ _writer.print("extends ");
_visitNode(node.superclass);
return null;
}
@@ -7062,7 +7068,7 @@
_visitNodeListWithSeparatorAndSuffix(node.metadata, " ", " ");
_visitTokenWithSuffix(node.staticKeyword, " ");
_visitNode(node.fields);
- _buffer.write(";");
+ _writer.print(";");
return null;
}
@@ -7071,7 +7077,7 @@
_visitNodeListWithSeparatorAndSuffix(node.metadata, ' ', ' ');
_visitTokenWithSuffix(node.keyword, " ");
_visitNodeWithSuffix(node.type, " ");
- _buffer.write("this.");
+ _writer.print("this.");
_visitNode(node.identifier);
_visitNode(node.typeParameters);
_visitNode(node.parameters);
@@ -7082,17 +7088,17 @@
Object visitForEachStatement(ForEachStatement node) {
DeclaredIdentifier loopVariable = node.loopVariable;
if (node.awaitKeyword != null) {
- _buffer.write("await ");
+ _writer.print("await ");
}
- _buffer.write("for (");
+ _writer.print("for (");
if (loopVariable == null) {
_visitNode(node.identifier);
} else {
_visitNode(loopVariable);
}
- _buffer.write(" in ");
+ _writer.print(" in ");
_visitNode(node.iterable);
- _buffer.write(") ");
+ _writer.print(") ");
_visitNode(node.body);
return null;
}
@@ -7100,46 +7106,46 @@
@override
Object visitFormalParameterList(FormalParameterList node) {
String groupEnd = null;
- _buffer.write('(');
+ _writer.print('(');
NodeList<FormalParameter> parameters = node.parameters;
int size = parameters.length;
for (int i = 0; i < size; i++) {
FormalParameter parameter = parameters[i];
if (i > 0) {
- _buffer.write(", ");
+ _writer.print(", ");
}
if (groupEnd == null && parameter is DefaultFormalParameter) {
if (parameter.kind == ParameterKind.NAMED) {
groupEnd = "}";
- _buffer.write('{');
+ _writer.print('{');
} else {
groupEnd = "]";
- _buffer.write('[');
+ _writer.print('[');
}
}
parameter.accept(this);
}
if (groupEnd != null) {
- _buffer.write(groupEnd);
+ _writer.print(groupEnd);
}
- _buffer.write(')');
+ _writer.print(')');
return null;
}
@override
Object visitForStatement(ForStatement node) {
Expression initialization = node.initialization;
- _buffer.write("for (");
+ _writer.print("for (");
if (initialization != null) {
_visitNode(initialization);
} else {
_visitNode(node.variables);
}
- _buffer.write(";");
+ _writer.print(";");
_visitNodeWithPrefix(" ", node.condition);
- _buffer.write(";");
+ _writer.print(";");
_visitNodeListWithSeparatorAndPrefix(" ", node.updaters, ", ");
- _buffer.write(") ");
+ _writer.print(") ");
_visitNode(node.body);
return null;
}
@@ -7166,7 +7172,7 @@
_visitNode(node.typeParameters);
_visitNode(node.parameters);
if (node.body is! EmptyFunctionBody) {
- _buffer.write(' ');
+ _writer.print(' ');
}
_visitNode(node.body);
return null;
@@ -7183,12 +7189,12 @@
@override
Object visitFunctionTypeAlias(FunctionTypeAlias node) {
_visitNodeListWithSeparatorAndSuffix(node.metadata, " ", " ");
- _buffer.write("typedef ");
+ _writer.print("typedef ");
_visitNodeWithSuffix(node.returnType, " ");
_visitNode(node.name);
_visitNode(node.typeParameters);
_visitNode(node.parameters);
- _buffer.write(";");
+ _writer.print(";");
return null;
}
@@ -7199,21 +7205,24 @@
_visitNode(node.identifier);
_visitNode(node.typeParameters);
_visitNode(node.parameters);
+ if (node.question != null) {
+ _writer.print('?');
+ }
return null;
}
@override
Object visitHideCombinator(HideCombinator node) {
- _buffer.write("hide ");
+ _writer.print("hide ");
_visitNodeListWithSeparator(node.hiddenNames, ", ");
return null;
}
@override
Object visitIfStatement(IfStatement node) {
- _buffer.write("if (");
+ _writer.print("if (");
_visitNode(node.condition);
- _buffer.write(") ");
+ _writer.print(") ");
_visitNode(node.thenStatement);
_visitNodeWithPrefix(" else ", node.elseStatement);
return null;
@@ -7221,7 +7230,7 @@
@override
Object visitImplementsClause(ImplementsClause node) {
- _buffer.write("implements ");
+ _writer.print("implements ");
_visitNodeListWithSeparator(node.interfaces, ", ");
return null;
}
@@ -7229,27 +7238,27 @@
@override
Object visitImportDirective(ImportDirective node) {
_visitNodeListWithSeparatorAndSuffix(node.metadata, " ", " ");
- _buffer.write("import ");
+ _writer.print("import ");
_visitNode(node.uri);
if (node.deferredKeyword != null) {
- _buffer.write(" deferred");
+ _writer.print(" deferred");
}
_visitNodeWithPrefix(" as ", node.prefix);
_visitNodeListWithSeparatorAndPrefix(" ", node.combinators, " ");
- _buffer.write(';');
+ _writer.print(';');
return null;
}
@override
Object visitIndexExpression(IndexExpression node) {
if (node.isCascaded) {
- _buffer.write("..");
+ _writer.print("..");
} else {
_visitNode(node.target);
}
- _buffer.write('[');
+ _writer.print('[');
_visitNode(node.index);
- _buffer.write(']');
+ _writer.print(']');
return null;
}
@@ -7263,18 +7272,18 @@
@override
Object visitIntegerLiteral(IntegerLiteral node) {
- _buffer.write(node.literal.lexeme);
+ _writer.print(node.literal.lexeme);
return null;
}
@override
Object visitInterpolationExpression(InterpolationExpression node) {
if (node.rightBracket != null) {
- _buffer.write("\${");
+ _writer.print("\${");
_visitNode(node.expression);
- _buffer.write("}");
+ _writer.print("}");
} else {
- _buffer.write("\$");
+ _writer.print("\$");
_visitNode(node.expression);
}
return null;
@@ -7282,7 +7291,7 @@
@override
Object visitInterpolationString(InterpolationString node) {
- _buffer.write(node.contents.lexeme);
+ _writer.print(node.contents.lexeme);
return null;
}
@@ -7290,9 +7299,9 @@
Object visitIsExpression(IsExpression node) {
_visitNode(node.expression);
if (node.notOperator == null) {
- _buffer.write(" is ");
+ _writer.print(" is ");
} else {
- _buffer.write(" is! ");
+ _writer.print(" is! ");
}
_visitNode(node.type);
return null;
@@ -7301,7 +7310,7 @@
@override
Object visitLabel(Label node) {
_visitNode(node.label);
- _buffer.write(":");
+ _writer.print(":");
return null;
}
@@ -7315,48 +7324,48 @@
@override
Object visitLibraryDirective(LibraryDirective node) {
_visitNodeListWithSeparatorAndSuffix(node.metadata, " ", " ");
- _buffer.write("library ");
+ _writer.print("library ");
_visitNode(node.name);
- _buffer.write(';');
+ _writer.print(';');
return null;
}
@override
Object visitLibraryIdentifier(LibraryIdentifier node) {
- _buffer.write(node.name);
+ _writer.print(node.name);
return null;
}
@override
Object visitListLiteral(ListLiteral node) {
if (node.constKeyword != null) {
- _buffer.write(node.constKeyword.lexeme);
- _buffer.write(' ');
+ _writer.print(node.constKeyword.lexeme);
+ _writer.print(' ');
}
_visitNodeWithSuffix(node.typeArguments, " ");
- _buffer.write("[");
+ _writer.print("[");
_visitNodeListWithSeparator(node.elements, ", ");
- _buffer.write("]");
+ _writer.print("]");
return null;
}
@override
Object visitMapLiteral(MapLiteral node) {
if (node.constKeyword != null) {
- _buffer.write(node.constKeyword.lexeme);
- _buffer.write(' ');
+ _writer.print(node.constKeyword.lexeme);
+ _writer.print(' ');
}
_visitNodeWithSuffix(node.typeArguments, " ");
- _buffer.write("{");
+ _writer.print("{");
_visitNodeListWithSeparator(node.entries, ", ");
- _buffer.write("}");
+ _writer.print("}");
return null;
}
@override
Object visitMapLiteralEntry(MapLiteralEntry node) {
_visitNode(node.key);
- _buffer.write(" : ");
+ _writer.print(" : ");
_visitNode(node.value);
return null;
}
@@ -7381,11 +7390,11 @@
@override
Object visitMethodInvocation(MethodInvocation node) {
if (node.isCascaded) {
- _buffer.write("..");
+ _writer.print("..");
} else {
if (node.target != null) {
node.target.accept(this);
- _buffer.write(node.operator.lexeme);
+ _writer.print(node.operator.lexeme);
}
}
_visitNode(node.methodName);
@@ -7403,69 +7412,69 @@
@override
Object visitNativeClause(NativeClause node) {
- _buffer.write("native ");
+ _writer.print("native ");
_visitNode(node.name);
return null;
}
@override
Object visitNativeFunctionBody(NativeFunctionBody node) {
- _buffer.write("native ");
+ _writer.print("native ");
_visitNode(node.stringLiteral);
- _buffer.write(';');
+ _writer.print(';');
return null;
}
@override
Object visitNullLiteral(NullLiteral node) {
- _buffer.write("null");
+ _writer.print("null");
return null;
}
@override
Object visitParenthesizedExpression(ParenthesizedExpression node) {
- _buffer.write('(');
+ _writer.print('(');
_visitNode(node.expression);
- _buffer.write(')');
+ _writer.print(')');
return null;
}
@override
Object visitPartDirective(PartDirective node) {
_visitNodeListWithSeparatorAndSuffix(node.metadata, " ", " ");
- _buffer.write("part ");
+ _writer.print("part ");
_visitNode(node.uri);
- _buffer.write(';');
+ _writer.print(';');
return null;
}
@override
Object visitPartOfDirective(PartOfDirective node) {
_visitNodeListWithSeparatorAndSuffix(node.metadata, " ", " ");
- _buffer.write("part of ");
+ _writer.print("part of ");
_visitNode(node.libraryName);
- _buffer.write(';');
+ _writer.print(';');
return null;
}
@override
Object visitPostfixExpression(PostfixExpression node) {
_visitNode(node.operand);
- _buffer.write(node.operator.lexeme);
+ _writer.print(node.operator.lexeme);
return null;
}
@override
Object visitPrefixedIdentifier(PrefixedIdentifier node) {
_visitNode(node.prefix);
- _buffer.write('.');
+ _writer.print('.');
_visitNode(node.identifier);
return null;
}
@override
Object visitPrefixExpression(PrefixExpression node) {
- _buffer.write(node.operator.lexeme);
+ _writer.print(node.operator.lexeme);
_visitNode(node.operand);
return null;
}
@@ -7473,10 +7482,10 @@
@override
Object visitPropertyAccess(PropertyAccess node) {
if (node.isCascaded) {
- _buffer.write("..");
+ _writer.print("..");
} else {
_visitNode(node.target);
- _buffer.write(node.operator.lexeme);
+ _writer.print(node.operator.lexeme);
}
_visitNode(node.propertyName);
return null;
@@ -7485,7 +7494,7 @@
@override
Object visitRedirectingConstructorInvocation(
RedirectingConstructorInvocation node) {
- _buffer.write("this");
+ _writer.print("this");
_visitNodeWithPrefix(".", node.constructorName);
_visitNode(node.argumentList);
return null;
@@ -7493,7 +7502,7 @@
@override
Object visitRethrowExpression(RethrowExpression node) {
- _buffer.write("rethrow");
+ _writer.print("rethrow");
return null;
}
@@ -7501,24 +7510,24 @@
Object visitReturnStatement(ReturnStatement node) {
Expression expression = node.expression;
if (expression == null) {
- _buffer.write("return;");
+ _writer.print("return;");
} else {
- _buffer.write("return ");
+ _writer.print("return ");
expression.accept(this);
- _buffer.write(";");
+ _writer.print(";");
}
return null;
}
@override
Object visitScriptTag(ScriptTag node) {
- _buffer.write(node.scriptTag.lexeme);
+ _writer.print(node.scriptTag.lexeme);
return null;
}
@override
Object visitShowCombinator(ShowCombinator node) {
- _buffer.write("show ");
+ _writer.print("show ");
_visitNodeListWithSeparator(node.shownNames, ", ");
return null;
}
@@ -7534,13 +7543,13 @@
@override
Object visitSimpleIdentifier(SimpleIdentifier node) {
- _buffer.write(node.token.lexeme);
+ _writer.print(node.token.lexeme);
return null;
}
@override
Object visitSimpleStringLiteral(SimpleStringLiteral node) {
- _buffer.write(node.literal.lexeme);
+ _writer.print(node.literal.lexeme);
return null;
}
@@ -7552,7 +7561,7 @@
@override
Object visitSuperConstructorInvocation(SuperConstructorInvocation node) {
- _buffer.write("super");
+ _writer.print("super");
_visitNodeWithPrefix(".", node.constructorName);
_visitNode(node.argumentList);
return null;
@@ -7560,16 +7569,16 @@
@override
Object visitSuperExpression(SuperExpression node) {
- _buffer.write("super");
+ _writer.print("super");
return null;
}
@override
Object visitSwitchCase(SwitchCase node) {
_visitNodeListWithSeparatorAndSuffix(node.labels, " ", " ");
- _buffer.write("case ");
+ _writer.print("case ");
_visitNode(node.expression);
- _buffer.write(": ");
+ _writer.print(": ");
_visitNodeListWithSeparator(node.statements, " ");
return null;
}
@@ -7577,43 +7586,43 @@
@override
Object visitSwitchDefault(SwitchDefault node) {
_visitNodeListWithSeparatorAndSuffix(node.labels, " ", " ");
- _buffer.write("default: ");
+ _writer.print("default: ");
_visitNodeListWithSeparator(node.statements, " ");
return null;
}
@override
Object visitSwitchStatement(SwitchStatement node) {
- _buffer.write("switch (");
+ _writer.print("switch (");
_visitNode(node.expression);
- _buffer.write(") {");
+ _writer.print(") {");
_visitNodeListWithSeparator(node.members, " ");
- _buffer.write("}");
+ _writer.print("}");
return null;
}
@override
Object visitSymbolLiteral(SymbolLiteral node) {
- _buffer.write("#");
+ _writer.print("#");
List<Token> components = node.components;
for (int i = 0; i < components.length; i++) {
if (i > 0) {
- _buffer.write(".");
+ _writer.print(".");
}
- _buffer.write(components[i].lexeme);
+ _writer.print(components[i].lexeme);
}
return null;
}
@override
Object visitThisExpression(ThisExpression node) {
- _buffer.write("this");
+ _writer.print("this");
return null;
}
@override
Object visitThrowExpression(ThrowExpression node) {
- _buffer.write("throw ");
+ _writer.print("throw ");
_visitNode(node.expression);
return null;
}
@@ -7626,7 +7635,7 @@
@override
Object visitTryStatement(TryStatement node) {
- _buffer.write("try ");
+ _writer.print("try ");
_visitNode(node.body);
_visitNodeListWithSeparatorAndPrefix(" ", node.catchClauses, " ");
_visitNodeWithPrefix(" finally ", node.finallyBlock);
@@ -7635,9 +7644,9 @@
@override
Object visitTypeArgumentList(TypeArgumentList node) {
- _buffer.write('<');
+ _writer.print('<');
_visitNodeListWithSeparator(node.arguments, ", ");
- _buffer.write('>');
+ _writer.print('>');
return null;
}
@@ -7645,6 +7654,9 @@
Object visitTypeName(TypeName node) {
_visitNode(node.name);
_visitNode(node.typeArguments);
+ if (node.question != null) {
+ _writer.print('?');
+ }
return null;
}
@@ -7658,9 +7670,9 @@
@override
Object visitTypeParameterList(TypeParameterList node) {
- _buffer.write('<');
+ _writer.print('<');
_visitNodeListWithSeparator(node.typeParameters, ", ");
- _buffer.write('>');
+ _writer.print('>');
return null;
}
@@ -7684,22 +7696,22 @@
@override
Object visitVariableDeclarationStatement(VariableDeclarationStatement node) {
_visitNode(node.variables);
- _buffer.write(";");
+ _writer.print(";");
return null;
}
@override
Object visitWhileStatement(WhileStatement node) {
- _buffer.write("while (");
+ _writer.print("while (");
_visitNode(node.condition);
- _buffer.write(") ");
+ _writer.print(") ");
_visitNode(node.body);
return null;
}
@override
Object visitWithClause(WithClause node) {
- _buffer.write("with ");
+ _writer.print("with ");
_visitNodeListWithSeparator(node.mixinTypes, ", ");
return null;
}
@@ -7707,12 +7719,12 @@
@override
Object visitYieldStatement(YieldStatement node) {
if (node.star != null) {
- _buffer.write("yield* ");
+ _writer.print("yield* ");
} else {
- _buffer.write("yield ");
+ _writer.print("yield ");
}
_visitNode(node.expression);
- _buffer.write(";");
+ _writer.print(";");
return null;
}
@@ -7722,7 +7734,7 @@
*/
void _visitFunctionWithPrefix(String prefix, FunctionBody body) {
if (body is! EmptyFunctionBody) {
- _buffer.write(prefix);
+ _writer.print(prefix);
}
_visitNode(body);
}
@@ -7751,7 +7763,7 @@
int size = nodes.length;
for (int i = 0; i < size; i++) {
if (i > 0) {
- _buffer.write(separator);
+ _writer.print(separator);
}
nodes[i].accept(this);
}
@@ -7767,10 +7779,10 @@
if (nodes != null) {
int size = nodes.length;
if (size > 0) {
- _buffer.write(prefix);
+ _writer.print(prefix);
for (int i = 0; i < size; i++) {
if (i > 0) {
- _buffer.write(separator);
+ _writer.print(separator);
}
nodes[i].accept(this);
}
@@ -7789,11 +7801,11 @@
if (size > 0) {
for (int i = 0; i < size; i++) {
if (i > 0) {
- _buffer.write(separator);
+ _writer.print(separator);
}
nodes[i].accept(this);
}
- _buffer.write(suffix);
+ _writer.print(suffix);
}
}
}
@@ -7804,7 +7816,7 @@
*/
void _visitNodeWithPrefix(String prefix, AstNode node) {
if (node != null) {
- _buffer.write(prefix);
+ _writer.print(prefix);
node.accept(this);
}
}
@@ -7816,7 +7828,7 @@
void _visitNodeWithSuffix(AstNode node, String suffix) {
if (node != null) {
node.accept(this);
- _buffer.write(suffix);
+ _writer.print(suffix);
}
}
@@ -7826,8 +7838,8 @@
*/
void _visitTokenWithSuffix(Token token, String suffix) {
if (token != null) {
- _buffer.write(token.lexeme);
- _buffer.write(suffix);
+ _writer.print(token.lexeme);
+ _writer.print(suffix);
}
}
}
diff --git a/pkg/analyzer/lib/src/dart/constant/evaluation.dart b/pkg/analyzer/lib/src/dart/constant/evaluation.dart
index ffd2cc8..c335351 100644
--- a/pkg/analyzer/lib/src/dart/constant/evaluation.dart
+++ b/pkg/analyzer/lib/src/dart/constant/evaluation.dart
@@ -13,14 +13,16 @@
import 'package:analyzer/dart/constant/value.dart';
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/type.dart';
+import 'package:analyzer/error/error.dart';
+import 'package:analyzer/error/listener.dart';
import 'package:analyzer/src/dart/constant/utilities.dart';
import 'package:analyzer/src/dart/constant/value.dart';
import 'package:analyzer/src/dart/element/element.dart';
import 'package:analyzer/src/dart/element/member.dart';
+import 'package:analyzer/src/error/codes.dart';
import 'package:analyzer/src/generated/engine.dart';
import 'package:analyzer/src/generated/engine.dart'
show AnalysisEngine, RecordingErrorListener;
-import 'package:analyzer/src/generated/error.dart';
import 'package:analyzer/src/generated/resolver.dart' show TypeProvider;
import 'package:analyzer/src/generated/type_system.dart'
show TypeSystem, TypeSystemImpl;
diff --git a/pkg/analyzer/lib/src/dart/constant/value.dart b/pkg/analyzer/lib/src/dart/constant/value.dart
index 177e271..db4de37 100644
--- a/pkg/analyzer/lib/src/dart/constant/value.dart
+++ b/pkg/analyzer/lib/src/dart/constant/value.dart
@@ -12,7 +12,8 @@
import 'package:analyzer/dart/constant/value.dart';
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/type.dart';
-import 'package:analyzer/src/generated/error.dart';
+import 'package:analyzer/error/error.dart';
+import 'package:analyzer/src/error/codes.dart';
import 'package:analyzer/src/generated/resolver.dart' show TypeProvider;
import 'package:analyzer/src/generated/utilities_general.dart';
diff --git a/pkg/analyzer/lib/src/dart/element/builder.dart b/pkg/analyzer/lib/src/dart/element/builder.dart
index 2cf5a0b..7e06a56 100644
--- a/pkg/analyzer/lib/src/dart/element/builder.dart
+++ b/pkg/analyzer/lib/src/dart/element/builder.dart
@@ -11,11 +11,12 @@
import 'package:analyzer/dart/ast/visitor.dart';
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/type.dart';
+import 'package:analyzer/error/error.dart';
import 'package:analyzer/exception/exception.dart';
import 'package:analyzer/src/dart/element/element.dart';
import 'package:analyzer/src/dart/element/type.dart';
+import 'package:analyzer/src/error/codes.dart';
import 'package:analyzer/src/generated/engine.dart';
-import 'package:analyzer/src/generated/error.dart';
import 'package:analyzer/src/generated/resolver.dart';
import 'package:analyzer/src/generated/sdk.dart';
import 'package:analyzer/src/generated/source.dart';
@@ -168,7 +169,7 @@
Object visitExportDirective(ExportDirective node) {
// Remove previous element. (It will remain null if the target is missing.)
node.element = null;
- Source exportedSource = node.source;
+ Source exportedSource = node.selectedSource;
int exportedTime = sourceModificationTimeMap[exportedSource] ?? -1;
// The exported source will be null if the URI in the export
// directive was invalid.
@@ -181,7 +182,7 @@
exportElement.uriOffset = uriLiteral.offset;
exportElement.uriEnd = uriLiteral.end;
}
- exportElement.uri = node.uriContent;
+ exportElement.uri = node.selectedUriContent;
exportElement.combinators = _buildCombinators(node);
exportElement.exportedLibrary = exportedLibrary;
setElementDocumentationComment(exportElement, node);
@@ -210,7 +211,7 @@
Object visitImportDirective(ImportDirective node) {
// Remove previous element. (It will remain null if the target is missing.)
node.element = null;
- Source importedSource = node.source;
+ Source importedSource = node.selectedSource;
int importedTime = sourceModificationTimeMap[importedSource] ?? -1;
// The imported source will be null if the URI in the import
// directive was invalid.
@@ -226,7 +227,7 @@
importElement.uriOffset = uriLiteral.offset;
importElement.uriEnd = uriLiteral.end;
}
- importElement.uri = node.uriContent;
+ importElement.uri = node.selectedUriContent;
importElement.deferred = node.deferredKeyword != null;
importElement.combinators = _buildCombinators(node);
importElement.importedLibrary = importedLibrary;
diff --git a/pkg/analyzer/lib/src/dart/element/element.dart b/pkg/analyzer/lib/src/dart/element/element.dart
index 00cad13..5d70df8 100644
--- a/pkg/analyzer/lib/src/dart/element/element.dart
+++ b/pkg/analyzer/lib/src/dart/element/element.dart
@@ -17,10 +17,10 @@
import 'package:analyzer/src/dart/constant/value.dart';
import 'package:analyzer/src/dart/element/handle.dart';
import 'package:analyzer/src/dart/element/type.dart';
+import 'package:analyzer/src/error/codes.dart' show CompileTimeErrorCode;
import 'package:analyzer/src/generated/constant.dart' show EvaluationResultImpl;
import 'package:analyzer/src/generated/engine.dart'
show AnalysisContext, AnalysisEngine;
-import 'package:analyzer/src/generated/error.dart' show CompileTimeErrorCode;
import 'package:analyzer/src/generated/java_core.dart';
import 'package:analyzer/src/generated/java_engine.dart';
import 'package:analyzer/src/generated/resolver.dart';
@@ -2441,6 +2441,12 @@
*/
class ElementAnnotationImpl implements ElementAnnotation {
/**
+ * The name of the top-level variable used to mark a method parameter as
+ * covariant.
+ */
+ static String _COVARIANT_VARIABLE_NAME = "checked";
+
+ /**
* The name of the class used to mark an element as being deprecated.
*/
static String _DEPRECATED_CLASS_NAME = "Deprecated";
@@ -2508,6 +2514,12 @@
static String _REQUIRED_VARIABLE_NAME = "required";
/**
+ * The name of the top-level variable used to mark a member as intended to be
+ * overridden.
+ */
+ static String _VIRTUAL_VARIABLE_NAME = "virtual";
+
+ /**
* The element representing the field, variable, or constructor being used as
* an annotation.
*/
@@ -2543,6 +2555,15 @@
@override
AnalysisContext get context => compilationUnit.library.context;
+ /**
+ * Return `true` if this annotation marks the associated parameter as being
+ * covariant, meaning it is allowed to have a narrower type in an override.
+ */
+ bool get isCovariant =>
+ element is PropertyAccessorElement &&
+ element.name == _COVARIANT_VARIABLE_NAME &&
+ element.library?.name == _META_LIB_NAME;
+
@override
bool get isDeprecated {
if (element?.library?.isDartCore == true) {
@@ -2601,6 +2622,18 @@
element.library?.name == _META_LIB_NAME;
/**
+ * Return `true` if this annotation marks the associated member as supporting
+ * overrides.
+ *
+ * This is currently used by fields in Strong Mode, as other members are
+ * already virtual-by-default.
+ */
+ bool get isVirtual =>
+ element is PropertyAccessorElement &&
+ element.name == _VIRTUAL_VARIABLE_NAME &&
+ element.library?.name == _META_LIB_NAME;
+
+ /**
* Get the library containing this annotation.
*/
Source get librarySource => compilationUnit.librarySource;
@@ -3954,10 +3987,11 @@
@override
void visitChildren(ElementVisitor visitor) {
super.visitChildren(visitor);
+ safelyVisitChildren(typeParameters, visitor);
+ safelyVisitChildren(parameters, visitor);
safelyVisitChildren(_functions, visitor);
safelyVisitChildren(_labels, visitor);
safelyVisitChildren(_localVariables, visitor);
- safelyVisitChildren(parameters, visitor);
}
}
@@ -3988,6 +4022,11 @@
List<NamespaceCombinator> _combinators;
/**
+ * The URI that was selected based on the [context] declared variables.
+ */
+ String _selectedUri;
+
+ /**
* Initialize a newly created export element at the given [offset].
*/
ExportElementImpl(int offset)
@@ -4020,8 +4059,7 @@
LibraryElement get exportedLibrary {
if (_unlinkedExportNonPublic != null && _exportedLibrary == null) {
LibraryElementImpl library = enclosingElement as LibraryElementImpl;
- _exportedLibrary = library.resynthesizerContext
- .buildExportedLibrary(_unlinkedExportPublic.uri);
+ _exportedLibrary = library.resynthesizerContext.buildExportedLibrary(uri);
}
return _exportedLibrary;
}
@@ -4063,7 +4101,8 @@
@override
String get uri {
if (_unlinkedExportPublic != null) {
- return _unlinkedExportPublic.uri;
+ return _selectedUri ??= _selectUri(
+ _unlinkedExportPublic.uri, _unlinkedExportPublic.configurations);
}
return super.uri;
}
@@ -4167,6 +4206,16 @@
}
@override
+ bool get isVirtual {
+ for (ElementAnnotationImpl annotation in metadata) {
+ if (annotation.isVirtual) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ @override
ElementKind get kind => ElementKind.FIELD;
/**
@@ -4852,6 +4901,11 @@
PrefixElement _prefix;
/**
+ * The URI that was selected based on the [context] declared variables.
+ */
+ String _selectedUri;
+
+ /**
* Initialize a newly created import element at the given [offset].
* The offset may be `-1` if the import is synthetic.
*/
@@ -4991,7 +5045,8 @@
if (_unlinkedImport.isImplicit) {
return null;
}
- return _unlinkedImport.uri;
+ return _selectedUri ??=
+ _selectUri(_unlinkedImport.uri, _unlinkedImport.configurations);
}
return super.uri;
}
@@ -6753,6 +6808,13 @@
int _visibleRangeLength = -1;
/**
+ * True if this parameter inherits from a covariant parameter. This happens
+ * when it overrides a method in a supertype that has a corresponding
+ * covariant parameter.
+ */
+ bool inheritsCovariant = false;
+
+ /**
* Initialize a newly created parameter element to have the given [name] and
* [nameOffset].
*/
@@ -6907,6 +6969,19 @@
}
@override
+ bool get isCovariant {
+ if (inheritsCovariant) {
+ return true;
+ }
+ for (ElementAnnotationImpl annotation in metadata) {
+ if (annotation.isCovariant) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ @override
bool get isFinal {
if (_unlinkedParam != null) {
return false;
@@ -7163,6 +7238,19 @@
}
@override
+ bool get isCovariant {
+ if (inheritsCovariant) {
+ return true;
+ }
+ for (ElementAnnotationImpl annotation in setter.variable.metadata) {
+ if (annotation.isCovariant) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ @override
DartType get type => setter.variable.type;
@override
@@ -8154,6 +8242,17 @@
void set uriOffset(int offset) {
_uriOffset = offset;
}
+
+ String _selectUri(
+ String defaultUri, List<UnlinkedConfiguration> configurations) {
+ for (UnlinkedConfiguration configuration in configurations) {
+ if (context.declaredVariables.get(configuration.name) ==
+ configuration.value) {
+ return configuration.uri;
+ }
+ }
+ return defaultUri;
+ }
}
/**
diff --git a/pkg/analyzer/lib/src/dart/element/handle.dart b/pkg/analyzer/lib/src/dart/element/handle.dart
index 9538b2a..93edeca 100644
--- a/pkg/analyzer/lib/src/dart/element/handle.dart
+++ b/pkg/analyzer/lib/src/dart/element/handle.dart
@@ -585,6 +585,9 @@
bool get isEnumConstant => actualElement.isEnumConstant;
@override
+ bool get isVirtual => actualElement.isVirtual;
+
+ @override
ElementKind get kind => ElementKind.FIELD;
@override
@@ -895,6 +898,9 @@
String get defaultValueCode => actualElement.defaultValueCode;
@override
+ bool get isCovariant => actualElement.isCovariant;
+
+ @override
bool get isInitializingFormal => actualElement.isInitializingFormal;
@override
diff --git a/pkg/analyzer/lib/src/dart/element/member.dart b/pkg/analyzer/lib/src/dart/element/member.dart
index 5ee9634..0ee331a 100644
--- a/pkg/analyzer/lib/src/dart/element/member.dart
+++ b/pkg/analyzer/lib/src/dart/element/member.dart
@@ -233,6 +233,9 @@
: super(baseElement, definingType, type);
@override
+ bool get isCovariant => baseElement.isCovariant;
+
+ @override
FieldElement get field {
FieldElement field = (baseElement as FieldFormalParameterElement).field;
if (field is FieldElement) {
@@ -273,6 +276,9 @@
bool get isEnumConstant => baseElement.isEnumConstant;
@override
+ bool get isVirtual => baseElement.isVirtual;
+
+ @override
DartType get propagatedType => substituteFor(baseElement.propagatedType);
@override
@@ -675,6 +681,9 @@
int get hashCode => baseElement.hashCode;
@override
+ bool get isCovariant => baseElement.isCovariant;
+
+ @override
bool get isInitializingFormal => baseElement.isInitializingFormal;
@override
diff --git a/pkg/analyzer/lib/src/dart/element/type.dart b/pkg/analyzer/lib/src/dart/element/type.dart
index 914c8e0..4c2e971 100644
--- a/pkg/analyzer/lib/src/dart/element/type.dart
+++ b/pkg/analyzer/lib/src/dart/element/type.dart
@@ -797,14 +797,17 @@
return relate(
this,
type,
- (DartType t, DartType s) =>
+ (DartType t, DartType s, _, __) =>
(t as TypeImpl).isMoreSpecificThan(s, withDynamic),
new TypeSystemImpl().instantiateToBounds);
}
@override
bool isSubtypeOf(DartType type) {
- return relate(this, type, (DartType t, DartType s) => t.isAssignableTo(s),
+ return relate(
+ this,
+ type,
+ (DartType t, DartType s, _, __) => t.isAssignableTo(s),
new TypeSystemImpl().instantiateToBounds);
}
@@ -966,17 +969,18 @@
*
* Used for the various relations on function types which have the same
* structural rules for handling optional parameters and arity, but use their
- * own relation for comparing corresponding paramaters or return types.
+ * own relation for comparing corresponding parameters or return types.
*
* If [returnRelation] is omitted, uses [parameterRelation] for both.
*/
static bool relate(
FunctionType t,
DartType other,
- bool parameterRelation(DartType t, DartType s),
+ bool parameterRelation(
+ DartType t, DartType s, bool tIsCovariant, bool sIsCovariant),
DartType instantiateToBounds(DartType t),
{bool returnRelation(DartType t, DartType s)}) {
- returnRelation ??= parameterRelation;
+ returnRelation ??= (t, s) => parameterRelation(t, s, false, false);
// Trivial base cases.
if (other == null) {
@@ -1014,12 +1018,39 @@
}
// Test the parameter types.
- List<DartType> tRequired = t.normalParameterTypes;
- List<DartType> sRequired = s.normalParameterTypes;
- List<DartType> tOptional = t.optionalParameterTypes;
- List<DartType> sOptional = s.optionalParameterTypes;
- Map<String, DartType> tNamed = t.namedParameterTypes;
- Map<String, DartType> sNamed = s.namedParameterTypes;
+
+ // TODO(jmesserly): this could be implemented with less allocation if we
+ // wanted, by taking advantage of the fact that positional arguments must
+ // appear before named ones.
+ var tRequired = <ParameterElement>[];
+ var tOptional = <ParameterElement>[];
+ var tNamed = <String, ParameterElement>{};
+ for (var p in t.parameters) {
+ var kind = p.parameterKind;
+ if (kind == ParameterKind.REQUIRED) {
+ tRequired.add(p);
+ } else if (kind == ParameterKind.POSITIONAL) {
+ tOptional.add(p);
+ } else {
+ assert(kind == ParameterKind.NAMED);
+ tNamed[p.name] = p;
+ }
+ }
+
+ var sRequired = <ParameterElement>[];
+ var sOptional = <ParameterElement>[];
+ var sNamed = <String, ParameterElement>{};
+ for (var p in s.parameters) {
+ var kind = p.parameterKind;
+ if (kind == ParameterKind.REQUIRED) {
+ sRequired.add(p);
+ } else if (kind == ParameterKind.POSITIONAL) {
+ sOptional.add(p);
+ } else {
+ assert(kind == ParameterKind.NAMED);
+ sNamed[p.name] = p;
+ }
+ }
// If one function has positional and the other has named parameters,
// they don't relate.
@@ -1037,19 +1068,21 @@
// For each named parameter in s, make sure we have a corresponding one
// that relates.
for (String key in sNamed.keys) {
- var tParamType = tNamed[key];
- if (tParamType == null) {
+ var tParam = tNamed[key];
+ if (tParam == null) {
return false;
}
- if (!parameterRelation(tParamType, sNamed[key])) {
+ var sParam = sNamed[key];
+ if (!parameterRelation(
+ tParam.type, sParam.type, tParam.isCovariant, sParam.isCovariant)) {
return false;
}
}
// Make sure all of the positional parameters (both required and optional)
// relate to each other.
- List<DartType> tPositional = tRequired;
- List<DartType> sPositional = sRequired;
+ var tPositional = tRequired;
+ var sPositional = sRequired;
if (tOptional.isNotEmpty) {
tPositional = tPositional.toList()..addAll(tOptional);
@@ -1070,7 +1103,10 @@
}
for (int i = 0; i < sPositional.length; i++) {
- if (!parameterRelation(tPositional[i], sPositional[i])) {
+ var tParam = tPositional[i];
+ var sParam = sPositional[i];
+ if (!parameterRelation(
+ tParam.type, sParam.type, tParam.isCovariant, sParam.isCovariant)) {
return false;
}
}
diff --git a/pkg/analyzer/lib/src/dart/resolver/inheritance_manager.dart b/pkg/analyzer/lib/src/dart/resolver/inheritance_manager.dart
index e31ef5f..57c4169 100644
--- a/pkg/analyzer/lib/src/dart/resolver/inheritance_manager.dart
+++ b/pkg/analyzer/lib/src/dart/resolver/inheritance_manager.dart
@@ -8,12 +8,13 @@
import 'package:analyzer/dart/ast/token.dart';
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/type.dart';
+import 'package:analyzer/error/error.dart';
import 'package:analyzer/exception/exception.dart';
import 'package:analyzer/src/dart/ast/token.dart';
import 'package:analyzer/src/dart/element/element.dart';
import 'package:analyzer/src/dart/element/member.dart';
import 'package:analyzer/src/dart/element/type.dart';
-import 'package:analyzer/src/generated/error.dart';
+import 'package:analyzer/src/error/codes.dart';
import 'package:analyzer/src/generated/type_system.dart';
import 'package:analyzer/src/generated/utilities_dart.dart';
diff --git a/pkg/analyzer/lib/src/dart/resolver/scope.dart b/pkg/analyzer/lib/src/dart/resolver/scope.dart
index e554947..1fc385e 100644
--- a/pkg/analyzer/lib/src/dart/resolver/scope.dart
+++ b/pkg/analyzer/lib/src/dart/resolver/scope.dart
@@ -8,9 +8,10 @@
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/element/element.dart';
+import 'package:analyzer/error/error.dart';
import 'package:analyzer/src/dart/element/element.dart';
+import 'package:analyzer/src/error/codes.dart';
import 'package:analyzer/src/generated/engine.dart';
-import 'package:analyzer/src/generated/error.dart';
import 'package:analyzer/src/generated/java_engine.dart';
import 'package:analyzer/src/generated/source.dart';
diff --git a/pkg/analyzer/lib/src/dart/scanner/scanner.dart b/pkg/analyzer/lib/src/dart/scanner/scanner.dart
index 0e60a90..4ea8f2c 100644
--- a/pkg/analyzer/lib/src/dart/scanner/scanner.dart
+++ b/pkg/analyzer/lib/src/dart/scanner/scanner.dart
@@ -5,9 +5,10 @@
library analyzer.src.dart.scanner.scanner;
import 'package:analyzer/dart/ast/token.dart';
+import 'package:analyzer/error/error.dart';
+import 'package:analyzer/error/listener.dart';
import 'package:analyzer/src/dart/ast/token.dart';
import 'package:analyzer/src/dart/scanner/reader.dart';
-import 'package:analyzer/src/generated/error.dart';
import 'package:analyzer/src/generated/java_engine.dart';
import 'package:analyzer/src/generated/source.dart';
import 'package:charcode/ascii.dart';
@@ -803,7 +804,8 @@
int _tokenizeFractionPart(int next, int start) {
bool done = false;
bool hasDigit = false;
- LOOP: while (!done) {
+ LOOP:
+ while (!done) {
if ($0 <= next && next <= $9) {
hasDigit = true;
} else if ($e == next || $E == next) {
@@ -1037,7 +1039,8 @@
int _tokenizeMultiLineRawString(int quoteChar, int start) {
int next = _reader.advance();
- outer: while (next != -1) {
+ outer:
+ while (next != -1) {
while (next != quoteChar) {
if (next == -1) {
break outer;
diff --git a/pkg/analyzer/lib/src/dart/sdk/sdk.dart b/pkg/analyzer/lib/src/dart/sdk/sdk.dart
index 675ce9b..7ab8272 100644
--- a/pkg/analyzer/lib/src/dart/sdk/sdk.dart
+++ b/pkg/analyzer/lib/src/dart/sdk/sdk.dart
@@ -9,6 +9,7 @@
import 'dart:io' as io;
import 'package:analyzer/dart/ast/ast.dart';
+import 'package:analyzer/error/listener.dart';
import 'package:analyzer/exception/exception.dart';
import 'package:analyzer/file_system/file_system.dart';
import 'package:analyzer/file_system/memory_file_system.dart';
@@ -16,7 +17,6 @@
import 'package:analyzer/src/dart/scanner/reader.dart';
import 'package:analyzer/src/dart/scanner/scanner.dart';
import 'package:analyzer/src/generated/engine.dart';
-import 'package:analyzer/src/generated/error.dart';
import 'package:analyzer/src/generated/java_engine_io.dart';
import 'package:analyzer/src/generated/parser.dart';
import 'package:analyzer/src/generated/sdk.dart';
@@ -155,9 +155,12 @@
@override
PackageBundle getLinkedBundle() {
- bool strongMode = _analysisOptions?.strongMode ?? false;
- _sdkBundle ??= getSummarySdkBundle(strongMode);
- return _sdkBundle;
+ if (_useSummary) {
+ bool strongMode = _analysisOptions?.strongMode ?? false;
+ _sdkBundle ??= getSummarySdkBundle(strongMode);
+ return _sdkBundle;
+ }
+ return null;
}
String getRelativePathFromFile(File file);
diff --git a/pkg/analyzer/lib/src/error.dart b/pkg/analyzer/lib/src/error.dart
index f39d1ae..5039da5 100644
--- a/pkg/analyzer/lib/src/error.dart
+++ b/pkg/analyzer/lib/src/error.dart
@@ -5,7 +5,7 @@
import 'dart:collection';
-import 'package:analyzer/src/generated/error.dart';
+import 'package:analyzer/error/error.dart';
/// The maximum line length when printing extracted source code when converting
/// an [AnalyzerError] to a string.
diff --git a/pkg/analyzer/lib/src/error/codes.dart b/pkg/analyzer/lib/src/error/codes.dart
new file mode 100644
index 0000000..9ca769e
--- /dev/null
+++ b/pkg/analyzer/lib/src/error/codes.dart
@@ -0,0 +1,4823 @@
+// Copyright (c) 2014, 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.
+
+library analyzer.src.error.codes;
+
+import 'package:analyzer/error/error.dart';
+import 'package:analyzer/src/dart/element/element.dart';
+import 'package:analyzer/src/generated/generated/shared_messages.dart'
+ as shared_messages;
+
+/**
+ * The error codes used for errors in analysis options files. The convention for
+ * this class is for the name of the error code to indicate the problem that
+ * caused the error to be generated and for the error message to explain what is
+ * wrong and, when appropriate, how the problem can be corrected.
+ */
+class AnalysisOptionsErrorCode extends ErrorCode {
+ /**
+ * An error code indicating that there is a syntactic error in the file.
+ *
+ * Parameters:
+ * 0: the error message from the parse error
+ */
+ static const AnalysisOptionsErrorCode PARSE_ERROR =
+ const AnalysisOptionsErrorCode('PARSE_ERROR', '{0}');
+
+ /**
+ * Initialize a newly created error code to have the given [name].
+ */
+ const AnalysisOptionsErrorCode(String name, String message,
+ [String correction])
+ : super(name, message, correction);
+
+ @override
+ ErrorSeverity get errorSeverity => ErrorSeverity.ERROR;
+
+ @override
+ ErrorType get type => ErrorType.COMPILE_TIME_ERROR;
+}
+
+/**
+ * The error codes used for warnings in analysis options files. The convention
+ * for this class is for the name of the error code to indicate the problem that
+ * caused the error to be generated and for the error message to explain what is
+ * wrong and, when appropriate, how the problem can be corrected.
+ */
+class AnalysisOptionsWarningCode extends ErrorCode {
+ /**
+ * An error code indicating that a plugin is being configured with an
+ * unsupported option and legal options are provided.
+ *
+ * Parameters:
+ * 0: the plugin name
+ * 1: the unsupported option key
+ * 2: legal values
+ */
+ static const AnalysisOptionsWarningCode UNSUPPORTED_OPTION_WITH_LEGAL_VALUES =
+ const AnalysisOptionsWarningCode('UNSUPPORTED_OPTION_WITH_LEGAL_VALUES',
+ "The option '{1}' is not supported by {0}, supported values are {2}");
+
+ /**
+ * An error code indicating that a plugin is being configured with an
+ * unsupported option where there is just one legal value.
+ *
+ * Parameters:
+ * 0: the plugin name
+ * 1: the unsupported option key
+ * 2: the legal value
+ */
+ static const AnalysisOptionsWarningCode UNSUPPORTED_OPTION_WITH_LEGAL_VALUE =
+ const AnalysisOptionsWarningCode('UNSUPPORTED_OPTION_WITH_LEGAL_VALUE',
+ "The option '{1}' is not supported by {0}, did you mean {2}?");
+
+ /**
+ * An error code indicating that an option entry is being configured with an
+ * unsupported value.
+ *
+ * Parameters:
+ * 0: the option name
+ * 1: the unsupported value
+ * 2: legal values
+ */
+ static const AnalysisOptionsWarningCode UNSUPPORTED_VALUE =
+ const AnalysisOptionsWarningCode('UNSUPPORTED_VALUE',
+ "The value '{1}' is not supported by {0}, legal values are {2}");
+
+ /**
+ * An error code indicating that an unrecognized error code is being used to
+ * specify an error filter.
+ *
+ * Parameters:
+ * 0: the unrecognized error code
+ */
+ static const AnalysisOptionsWarningCode UNRECOGNIZED_ERROR_CODE =
+ const AnalysisOptionsWarningCode(
+ 'UNRECOGNIZED_ERROR_CODE', "'{0}' is not a recognized error code");
+
+ /**
+ * Initialize a newly created warning code to have the given [name].
+ */
+ const AnalysisOptionsWarningCode(String name, String message,
+ [String correction])
+ : super(name, message, correction);
+
+ @override
+ ErrorSeverity get errorSeverity => ErrorSeverity.WARNING;
+
+ @override
+ ErrorType get type => ErrorType.STATIC_WARNING;
+}
+
+/**
+ * The error codes used for compile time errors caused by constant evaluation
+ * that would throw an exception when run in checked mode. The client of the
+ * analysis engine is responsible for determining how these errors should be
+ * presented to the user (for example, a command-line compiler might elect to
+ * treat these errors differently depending whether it is compiling it "checked"
+ * mode).
+ */
+class CheckedModeCompileTimeErrorCode extends ErrorCode {
+ // TODO(paulberry): improve the text of these error messages so that it's
+ // clear to the user that the error is coming from constant evaluation (and
+ // hence the constant needs to be a subtype of the annotated type) as opposed
+ // to static type analysis (which only requires that the two types be
+ // assignable). Also consider populating the "correction" field for these
+ // errors.
+
+ /**
+ * 12.11.2 Const: It is a compile-time error if evaluation of a constant
+ * object results in an uncaught exception being thrown.
+ */
+ static const CheckedModeCompileTimeErrorCode
+ CONST_CONSTRUCTOR_FIELD_TYPE_MISMATCH =
+ const CheckedModeCompileTimeErrorCode(
+ 'CONST_CONSTRUCTOR_FIELD_TYPE_MISMATCH',
+ "The object type '{0}' cannot be assigned to the field '{1}', which has type '{2}'");
+
+ /**
+ * 12.11.2 Const: It is a compile-time error if evaluation of a constant
+ * object results in an uncaught exception being thrown.
+ */
+ static const CheckedModeCompileTimeErrorCode
+ CONST_CONSTRUCTOR_PARAM_TYPE_MISMATCH =
+ const CheckedModeCompileTimeErrorCode(
+ 'CONST_CONSTRUCTOR_PARAM_TYPE_MISMATCH',
+ "The object type '{0}' cannot be assigned to a parameter of type '{1}'");
+
+ /**
+ * 7.6.1 Generative Constructors: In checked mode, it is a dynamic type error
+ * if o is not <b>null</b> and the interface of the class of <i>o</i> is not a
+ * subtype of the static type of the field <i>v</i>.
+ *
+ * 12.11.2 Const: It is a compile-time error if evaluation of a constant
+ * object results in an uncaught exception being thrown.
+ *
+ * Parameters:
+ * 0: the name of the type of the initializer expression
+ * 1: the name of the type of the field
+ */
+ static const CheckedModeCompileTimeErrorCode
+ CONST_FIELD_INITIALIZER_NOT_ASSIGNABLE =
+ const CheckedModeCompileTimeErrorCode(
+ 'CONST_FIELD_INITIALIZER_NOT_ASSIGNABLE',
+ "The initializer type '{0}' cannot be assigned to the field type '{1}'");
+
+ /**
+ * 12.6 Lists: A run-time list literal <<i>E</i>> [<i>e<sub>1</sub></i>
+ * ... <i>e<sub>n</sub></i>] is evaluated as follows:
+ * * The operator []= is invoked on <i>a</i> with first argument <i>i</i> and
+ * second argument <i>o<sub>i+1</sub></i><i>, 1 <= i <= n</i>
+ *
+ * 12.14.2 Binding Actuals to Formals: Let <i>T<sub>i</sub></i> be the static
+ * type of <i>a<sub>i</sub></i>, let <i>S<sub>i</sub></i> be the type of
+ * <i>p<sub>i</sub>, 1 <= i <= n+k</i> and let <i>S<sub>q</sub></i> be
+ * the type of the named parameter <i>q</i> of <i>f</i>. It is a static
+ * warning if <i>T<sub>j</sub></i> may not be assigned to <i>S<sub>j</sub>,
+ * 1 <= j <= m</i>.
+ */
+ static const CheckedModeCompileTimeErrorCode
+ LIST_ELEMENT_TYPE_NOT_ASSIGNABLE = const CheckedModeCompileTimeErrorCode(
+ 'LIST_ELEMENT_TYPE_NOT_ASSIGNABLE',
+ "The element type '{0}' cannot be assigned to the list type '{1}'");
+
+ /**
+ * 12.7 Map: A run-time map literal <<i>K</i>, <i>V</i>>
+ * [<i>k<sub>1</sub></i> : <i>e<sub>1</sub></i> ... <i>k<sub>n</sub></i> :
+ * <i>e<sub>n</sub></i>] is evaluated as follows:
+ * * The operator []= is invoked on <i>m</i> with first argument
+ * <i>k<sub>i</sub></i> and second argument <i>e<sub>i</sub></i><i>, 1 <=
+ * i <= n</i>
+ *
+ * 12.14.2 Binding Actuals to Formals: Let <i>T<sub>i</sub></i> be the static
+ * type of <i>a<sub>i</sub></i>, let <i>S<sub>i</sub></i> be the type of
+ * <i>p<sub>i</sub>, 1 <= i <= n+k</i> and let <i>S<sub>q</sub></i> be
+ * the type of the named parameter <i>q</i> of <i>f</i>. It is a static
+ * warning if <i>T<sub>j</sub></i> may not be assigned to <i>S<sub>j</sub>, 1
+ * <= j <= m</i>.
+ */
+ static const CheckedModeCompileTimeErrorCode MAP_KEY_TYPE_NOT_ASSIGNABLE =
+ const CheckedModeCompileTimeErrorCode('MAP_KEY_TYPE_NOT_ASSIGNABLE',
+ "The element type '{0}' cannot be assigned to the map key type '{1}'");
+
+ /**
+ * 12.7 Map: A run-time map literal <<i>K</i>, <i>V</i>>
+ * [<i>k<sub>1</sub></i> : <i>e<sub>1</sub></i> ... <i>k<sub>n</sub></i> :
+ * <i>e<sub>n</sub></i>] is evaluated as follows:
+ * * The operator []= is invoked on <i>m</i> with first argument
+ * <i>k<sub>i</sub></i> and second argument <i>e<sub>i</sub></i><i>, 1 <=
+ * i <= n</i>
+ *
+ * 12.14.2 Binding Actuals to Formals: Let <i>T<sub>i</sub></i> be the static
+ * type of <i>a<sub>i</sub></i>, let <i>S<sub>i</sub></i> be the type of
+ * <i>p<sub>i</sub>, 1 <= i <= n+k</i> and let <i>S<sub>q</sub></i> be
+ * the type of the named parameter <i>q</i> of <i>f</i>. It is a static
+ * warning if <i>T<sub>j</sub></i> may not be assigned to <i>S<sub>j</sub>, 1
+ * <= j <= m</i>.
+ */
+ static const CheckedModeCompileTimeErrorCode MAP_VALUE_TYPE_NOT_ASSIGNABLE =
+ const CheckedModeCompileTimeErrorCode('MAP_VALUE_TYPE_NOT_ASSIGNABLE',
+ "The element type '{0}' cannot be assigned to the map value type '{1}'");
+
+ /**
+ * 12.11.2 Const: It is a compile-time error if evaluation of a constant
+ * object results in an uncaught exception being thrown.
+ */
+ static const CheckedModeCompileTimeErrorCode VARIABLE_TYPE_MISMATCH =
+ const CheckedModeCompileTimeErrorCode('VARIABLE_TYPE_MISMATCH',
+ "The object type '{0}' cannot be assigned to a variable of type '{1}'");
+
+ /**
+ * Initialize a newly created error code to have the given [name]. The message
+ * associated with the error will be created from the given [message]
+ * template. The correction associated with the error will be created from the
+ * given [correction] template.
+ */
+ const CheckedModeCompileTimeErrorCode(String name, String message,
+ [String correction])
+ : super(name, message, correction);
+
+ @override
+ ErrorSeverity get errorSeverity =>
+ ErrorType.CHECKED_MODE_COMPILE_TIME_ERROR.severity;
+
+ @override
+ ErrorType get type => ErrorType.CHECKED_MODE_COMPILE_TIME_ERROR;
+}
+
+/**
+ * The error codes used for compile time errors. The convention for this class
+ * is for the name of the error code to indicate the problem that caused the
+ * error to be generated and for the error message to explain what is wrong and,
+ * when appropriate, how the problem can be corrected.
+ */
+class CompileTimeErrorCode extends ErrorCode {
+ /**
+ * Enum proposal: It is also a compile-time error to explicitly instantiate an
+ * enum via 'new' or 'const' or to access its private fields.
+ */
+ static const CompileTimeErrorCode ACCESS_PRIVATE_ENUM_FIELD =
+ const CompileTimeErrorCode('ACCESS_PRIVATE_ENUM_FIELD',
+ "The private fields of an enum cannot be accessed, even within the same library");
+
+ /**
+ * 14.2 Exports: It is a compile-time error if a name <i>N</i> is re-exported
+ * by a library <i>L</i> and <i>N</i> is introduced into the export namespace
+ * of <i>L</i> by more than one export, unless each all exports refer to same
+ * declaration for the name N.
+ *
+ * Parameters:
+ * 0: the name of the ambiguous element
+ * 1: the name of the first library that the type is found
+ * 2: the name of the second library that the type is found
+ */
+ static const CompileTimeErrorCode AMBIGUOUS_EXPORT =
+ const CompileTimeErrorCode('AMBIGUOUS_EXPORT',
+ "The name '{0}' is defined in the libraries '{1}' and '{2}'");
+
+ /**
+ * 15 Metadata: The constant expression given in an annotation is type checked
+ * and evaluated in the scope surrounding the declaration being annotated.
+ *
+ * 12.11.2 Const: It is a compile-time error if <i>T</i> is not a class
+ * accessible in the current scope, optionally followed by type arguments.
+ *
+ * 12.11.2 Const: If <i>e</i> is of the form <i>const T.id(a<sub>1</sub>,
+ * …, a<sub>n</sub>, x<sub>n+1</sub>: a<sub>n+1</sub>, …
+ * x<sub>n+k</sub>: a<sub>n+k</sub>)</i> it is a compile-time error if
+ * <i>T</i> is not a class accessible in the current scope, optionally
+ * followed by type arguments.
+ *
+ * Parameters:
+ * 0: the name of the non-type element
+ */
+ static const CompileTimeErrorCode ANNOTATION_WITH_NON_CLASS =
+ const CompileTimeErrorCode(
+ 'ANNOTATION_WITH_NON_CLASS', "The name '{0}' is not a class");
+
+ /**
+ * 12.33 Argument Definition Test: It is a compile time error if <i>v</i> does
+ * not denote a formal parameter.
+ *
+ * Parameters:
+ * 0: the name of the identifier in the argument definition test that is not a
+ * parameter
+ */
+ static const CompileTimeErrorCode ARGUMENT_DEFINITION_TEST_NON_PARAMETER =
+ const CompileTimeErrorCode(
+ 'ARGUMENT_DEFINITION_TEST_NON_PARAMETER', "'{0}' is not a parameter");
+
+ /**
+ * ?? Asynchronous For-in: It is a compile-time error if an asynchronous
+ * for-in statement appears inside a synchronous function.
+ */
+ static const CompileTimeErrorCode ASYNC_FOR_IN_WRONG_CONTEXT =
+ const CompileTimeErrorCode('ASYNC_FOR_IN_WRONG_CONTEXT',
+ "The asynchronous for-in can only be used in a function marked with async or async*");
+
+ /**
+ * ??: It is a compile-time error if the function immediately enclosing a is
+ * not declared asynchronous.
+ */
+ static const CompileTimeErrorCode AWAIT_IN_WRONG_CONTEXT =
+ const CompileTimeErrorCode('AWAIT_IN_WRONG_CONTEXT',
+ "The await expression can only be used in a function marked as async or async*");
+
+ /**
+ * 12.30 Identifier Reference: It is a compile-time error to use a built-in
+ * identifier other than dynamic as a type annotation.
+ */
+ static const CompileTimeErrorCode BUILT_IN_IDENTIFIER_AS_TYPE =
+ const CompileTimeErrorCode('BUILT_IN_IDENTIFIER_AS_TYPE',
+ "The built-in identifier '{0}' cannot be used as a type");
+
+ /**
+ * 12.30 Identifier Reference: It is a compile-time error if a built-in
+ * identifier is used as the declared name of a class, type parameter or type
+ * alias.
+ */
+ static const CompileTimeErrorCode BUILT_IN_IDENTIFIER_AS_TYPE_NAME =
+ const CompileTimeErrorCode('BUILT_IN_IDENTIFIER_AS_TYPE_NAME',
+ "The built-in identifier '{0}' cannot be used as a type name");
+
+ /**
+ * 12.30 Identifier Reference: It is a compile-time error if a built-in
+ * identifier is used as the declared name of a class, type parameter or type
+ * alias.
+ */
+ static const CompileTimeErrorCode BUILT_IN_IDENTIFIER_AS_TYPEDEF_NAME =
+ const CompileTimeErrorCode('BUILT_IN_IDENTIFIER_AS_TYPEDEF_NAME',
+ "The built-in identifier '{0}' cannot be used as a type alias name");
+
+ /**
+ * 12.30 Identifier Reference: It is a compile-time error if a built-in
+ * identifier is used as the declared name of a class, type parameter or type
+ * alias.
+ */
+ static const CompileTimeErrorCode BUILT_IN_IDENTIFIER_AS_TYPE_PARAMETER_NAME =
+ const CompileTimeErrorCode('BUILT_IN_IDENTIFIER_AS_TYPE_PARAMETER_NAME',
+ "The built-in identifier '{0}' cannot be used as a type parameter name");
+
+ /**
+ * 13.9 Switch: It is a compile-time error if the class <i>C</i> implements
+ * the operator <i>==</i>.
+ */
+ static const CompileTimeErrorCode CASE_EXPRESSION_TYPE_IMPLEMENTS_EQUALS =
+ const CompileTimeErrorCode('CASE_EXPRESSION_TYPE_IMPLEMENTS_EQUALS',
+ "The switch case expression type '{0}' cannot override the == operator");
+
+ /**
+ * 12.1 Constants: It is a compile-time error if evaluation of a compile-time
+ * constant would raise
+ * an exception.
+ */
+ static const CompileTimeErrorCode COMPILE_TIME_CONSTANT_RAISES_EXCEPTION =
+ const CompileTimeErrorCode('COMPILE_TIME_CONSTANT_RAISES_EXCEPTION', "");
+
+ /**
+ * 7.2 Getters: It is a compile-time error if a class has both a getter and a
+ * method with the same name. This restriction holds regardless of whether the
+ * getter is defined explicitly or implicitly, or whether the getter or the
+ * method are inherited or not.
+ */
+ static const CompileTimeErrorCode CONFLICTING_GETTER_AND_METHOD =
+ const CompileTimeErrorCode('CONFLICTING_GETTER_AND_METHOD',
+ "Class '{0}' cannot have both getter '{1}.{2}' and method with the same name");
+
+ /**
+ * 7.2 Getters: It is a compile-time error if a class has both a getter and a
+ * method with the same name. This restriction holds regardless of whether the
+ * getter is defined explicitly or implicitly, or whether the getter or the
+ * method are inherited or not.
+ */
+ static const CompileTimeErrorCode CONFLICTING_METHOD_AND_GETTER =
+ const CompileTimeErrorCode('CONFLICTING_METHOD_AND_GETTER',
+ "Class '{0}' cannot have both method '{1}.{2}' and getter with the same name");
+
+ /**
+ * 7.6 Constructors: A constructor name always begins with the name of its
+ * immediately enclosing class, and may optionally be followed by a dot and an
+ * identifier <i>id</i>. It is a compile-time error if <i>id</i> is the name
+ * of a member declared in the immediately enclosing class.
+ */
+ static const CompileTimeErrorCode CONFLICTING_CONSTRUCTOR_NAME_AND_FIELD =
+ const CompileTimeErrorCode('CONFLICTING_CONSTRUCTOR_NAME_AND_FIELD',
+ "'{0}' cannot be used to name a constructor and a field in this class");
+
+ /**
+ * 7.6 Constructors: A constructor name always begins with the name of its
+ * immediately enclosing class, and may optionally be followed by a dot and an
+ * identifier <i>id</i>. It is a compile-time error if <i>id</i> is the name
+ * of a member declared in the immediately enclosing class.
+ */
+ static const CompileTimeErrorCode CONFLICTING_CONSTRUCTOR_NAME_AND_METHOD =
+ const CompileTimeErrorCode('CONFLICTING_CONSTRUCTOR_NAME_AND_METHOD',
+ "'{0}' cannot be used to name a constructor and a method in this class");
+
+ /**
+ * 7. Classes: It is a compile time error if a generic class declares a type
+ * variable with the same name as the class or any of its members or
+ * constructors.
+ */
+ static const CompileTimeErrorCode CONFLICTING_TYPE_VARIABLE_AND_CLASS =
+ const CompileTimeErrorCode('CONFLICTING_TYPE_VARIABLE_AND_CLASS',
+ "'{0}' cannot be used to name a type variable in a class with the same name");
+
+ /**
+ * 7. Classes: It is a compile time error if a generic class declares a type
+ * variable with the same name as the class or any of its members or
+ * constructors.
+ */
+ static const CompileTimeErrorCode CONFLICTING_TYPE_VARIABLE_AND_MEMBER =
+ const CompileTimeErrorCode('CONFLICTING_TYPE_VARIABLE_AND_MEMBER',
+ "'{0}' cannot be used to name a type variable and member in this class");
+
+ /**
+ * 12.11.2 Const: It is a compile-time error if evaluation of a constant
+ * object results in an uncaught exception being thrown.
+ */
+ static const CompileTimeErrorCode CONST_CONSTRUCTOR_THROWS_EXCEPTION =
+ const CompileTimeErrorCode('CONST_CONSTRUCTOR_THROWS_EXCEPTION',
+ "'const' constructors cannot throw exceptions");
+
+ /**
+ * 10.6.3 Constant Constructors: It is a compile-time error if a constant
+ * constructor is declared by a class C if any instance variable declared in C
+ * is initialized with an expression that is not a constant expression.
+ */
+ static const CompileTimeErrorCode
+ CONST_CONSTRUCTOR_WITH_FIELD_INITIALIZED_BY_NON_CONST =
+ const CompileTimeErrorCode(
+ 'CONST_CONSTRUCTOR_WITH_FIELD_INITIALIZED_BY_NON_CONST',
+ "Can't define the 'const' constructor because the field '{0}' is initialized with a non-constant value");
+
+ /**
+ * 7.6.3 Constant Constructors: The superinitializer that appears, explicitly
+ * or implicitly, in the initializer list of a constant constructor must
+ * specify a constant constructor of the superclass of the immediately
+ * enclosing class or a compile-time error occurs.
+ *
+ * 9 Mixins: For each generative constructor named ... an implicitly declared
+ * constructor named ... is declared.
+ */
+ static const CompileTimeErrorCode CONST_CONSTRUCTOR_WITH_MIXIN =
+ const CompileTimeErrorCode('CONST_CONSTRUCTOR_WITH_MIXIN',
+ "Constant constructor cannot be declared for a class with a mixin");
+
+ /**
+ * 7.6.3 Constant Constructors: The superinitializer that appears, explicitly
+ * or implicitly, in the initializer list of a constant constructor must
+ * specify a constant constructor of the superclass of the immediately
+ * enclosing class or a compile-time error occurs.
+ */
+ static const CompileTimeErrorCode CONST_CONSTRUCTOR_WITH_NON_CONST_SUPER =
+ const CompileTimeErrorCode('CONST_CONSTRUCTOR_WITH_NON_CONST_SUPER',
+ "Constant constructor cannot call non-constant super constructor of '{0}'");
+
+ /**
+ * 7.6.3 Constant Constructors: It is a compile-time error if a constant
+ * constructor is declared by a class that has a non-final instance variable.
+ *
+ * The above refers to both locally declared and inherited instance variables.
+ */
+ static const CompileTimeErrorCode CONST_CONSTRUCTOR_WITH_NON_FINAL_FIELD =
+ const CompileTimeErrorCode('CONST_CONSTRUCTOR_WITH_NON_FINAL_FIELD',
+ "Cannot define the 'const' constructor for a class with non-final fields");
+
+ /**
+ * 12.12.2 Const: It is a compile-time error if <i>T</i> is a deferred type.
+ */
+ static const CompileTimeErrorCode CONST_DEFERRED_CLASS =
+ const CompileTimeErrorCode('CONST_DEFERRED_CLASS',
+ "Deferred classes cannot be created with 'const'");
+
+ /**
+ * 6.2 Formal Parameters: It is a compile-time error if a formal parameter is
+ * declared as a constant variable.
+ */
+ static const CompileTimeErrorCode CONST_FORMAL_PARAMETER =
+ const CompileTimeErrorCode(
+ 'CONST_FORMAL_PARAMETER', "Parameters cannot be 'const'");
+
+ /**
+ * 5 Variables: A constant variable must be initialized to a compile-time
+ * constant or a compile-time error occurs.
+ */
+ static const CompileTimeErrorCode CONST_INITIALIZED_WITH_NON_CONSTANT_VALUE =
+ const CompileTimeErrorCode('CONST_INITIALIZED_WITH_NON_CONSTANT_VALUE',
+ "'const' variables must be constant value");
+
+ /**
+ * 5 Variables: A constant variable must be initialized to a compile-time
+ * constant or a compile-time error occurs.
+ *
+ * 12.1 Constants: A qualified reference to a static constant variable that is
+ * not qualified by a deferred prefix.
+ */
+ static const CompileTimeErrorCode
+ CONST_INITIALIZED_WITH_NON_CONSTANT_VALUE_FROM_DEFERRED_LIBRARY =
+ const CompileTimeErrorCode(
+ 'CONST_INITIALIZED_WITH_NON_CONSTANT_VALUE_FROM_DEFERRED_LIBRARY',
+ "Constant values from a deferred library cannot be used to initialized a 'const' variable");
+
+ /**
+ * 7.5 Instance Variables: It is a compile-time error if an instance variable
+ * is declared to be constant.
+ */
+ static const CompileTimeErrorCode CONST_INSTANCE_FIELD =
+ const CompileTimeErrorCode('CONST_INSTANCE_FIELD',
+ "Only static fields can be declared as 'const'");
+
+ /**
+ * 12.8 Maps: It is a compile-time error if the key of an entry in a constant
+ * map literal is an instance of a class that implements the operator
+ * <i>==</i> unless the key is a string or integer.
+ */
+ static const CompileTimeErrorCode
+ CONST_MAP_KEY_EXPRESSION_TYPE_IMPLEMENTS_EQUALS =
+ const CompileTimeErrorCode(
+ 'CONST_MAP_KEY_EXPRESSION_TYPE_IMPLEMENTS_EQUALS',
+ "The constant map entry key expression type '{0}' cannot override the == operator");
+
+ /**
+ * 5 Variables: A constant variable must be initialized to a compile-time
+ * constant (12.1) or a compile-time error occurs.
+ *
+ * Parameters:
+ * 0: the name of the uninitialized final variable
+ */
+ static const CompileTimeErrorCode CONST_NOT_INITIALIZED =
+ const CompileTimeErrorCode('CONST_NOT_INITIALIZED',
+ "The const variable '{0}' must be initialized");
+
+ /**
+ * 12.11.2 Const: An expression of one of the forms !e, e1 && e2 or e1 || e2,
+ * where e, e1 and e2 are constant expressions that evaluate to a boolean
+ * value.
+ */
+ static const CompileTimeErrorCode CONST_EVAL_TYPE_BOOL =
+ const CompileTimeErrorCode('CONST_EVAL_TYPE_BOOL',
+ "In constant expressions, operand(s) of this operator must be of type 'bool'");
+
+ /**
+ * 12.11.2 Const: An expression of one of the forms e1 == e2 or e1 != e2 where
+ * e1 and e2 are constant expressions that evaluate to a numeric, string or
+ * boolean value or to null.
+ */
+ static const CompileTimeErrorCode CONST_EVAL_TYPE_BOOL_NUM_STRING =
+ const CompileTimeErrorCode('CONST_EVAL_TYPE_BOOL_NUM_STRING',
+ "In constant expressions, operands of this operator must be of type 'bool', 'num', 'String' or 'null'");
+
+ /**
+ * 12.11.2 Const: An expression of one of the forms ~e, e1 ^ e2, e1 & e2,
+ * e1 | e2, e1 >> e2 or e1 << e2, where e, e1 and e2 are constant expressions
+ * that evaluate to an integer value or to null.
+ */
+ static const CompileTimeErrorCode CONST_EVAL_TYPE_INT =
+ const CompileTimeErrorCode('CONST_EVAL_TYPE_INT',
+ "In constant expressions, operand(s) of this operator must be of type 'int'");
+
+ /**
+ * 12.11.2 Const: An expression of one of the forms e, e1 + e2, e1 - e2, e1 *
+ * e2, e1 / e2, e1 ~/ e2, e1 > e2, e1 < e2, e1 >= e2, e1 <= e2 or e1 % e2,
+ * where e, e1 and e2 are constant expressions that evaluate to a numeric
+ * value or to null.
+ */
+ static const CompileTimeErrorCode CONST_EVAL_TYPE_NUM =
+ const CompileTimeErrorCode('CONST_EVAL_TYPE_NUM',
+ "In constant expressions, operand(s) of this operator must be of type 'num'");
+
+ /**
+ * 12.11.2 Const: It is a compile-time error if evaluation of a constant
+ * object results in an uncaught exception being thrown.
+ */
+ static const CompileTimeErrorCode CONST_EVAL_THROWS_EXCEPTION =
+ const CompileTimeErrorCode('CONST_EVAL_THROWS_EXCEPTION',
+ "Evaluation of this constant expression causes exception");
+
+ /**
+ * 12.11.2 Const: It is a compile-time error if evaluation of a constant
+ * object results in an uncaught exception being thrown.
+ */
+ static const CompileTimeErrorCode CONST_EVAL_THROWS_IDBZE =
+ const CompileTimeErrorCode('CONST_EVAL_THROWS_IDBZE',
+ "Evaluation of this constant expression throws IntegerDivisionByZeroException");
+
+ /**
+ * 12.11.2 Const: If <i>T</i> is a parameterized type <i>S<U<sub>1</sub>,
+ * …, U<sub>m</sub>></i>, let <i>R = S</i>; It is a compile time
+ * error if <i>S</i> is not a generic type with <i>m</i> type parameters.
+ *
+ * Parameters:
+ * 0: the name of the type being referenced (<i>S</i>)
+ * 1: the number of type parameters that were declared
+ * 2: the number of type arguments provided
+ *
+ * See [StaticWarningCode.NEW_WITH_INVALID_TYPE_PARAMETERS], and
+ * [StaticTypeWarningCode.WRONG_NUMBER_OF_TYPE_ARGUMENTS].
+ */
+ static const CompileTimeErrorCode CONST_WITH_INVALID_TYPE_PARAMETERS =
+ const CompileTimeErrorCode('CONST_WITH_INVALID_TYPE_PARAMETERS',
+ "The type '{0}' is declared with {1} type parameters, but {2} type arguments were given");
+
+ /**
+ * 12.11.2 Const: If <i>e</i> is of the form <i>const T(a<sub>1</sub>,
+ * …, a<sub>n</sub>, x<sub>n+1</sub>: a<sub>n+1</sub>, …,
+ * x<sub>n+k</sub>: a<sub>n+k</sub>)</i> it is a compile-time error if the
+ * type <i>T</i> does not declare a constant constructor with the same name as
+ * the declaration of <i>T</i>.
+ */
+ static const CompileTimeErrorCode CONST_WITH_NON_CONST =
+ const CompileTimeErrorCode('CONST_WITH_NON_CONST',
+ "The constructor being called is not a 'const' constructor");
+
+ /**
+ * 12.11.2 Const: In all of the above cases, it is a compile-time error if
+ * <i>a<sub>i</sub>, 1 <= i <= n + k</i>, is not a compile-time constant
+ * expression.
+ */
+ static const CompileTimeErrorCode CONST_WITH_NON_CONSTANT_ARGUMENT =
+ const CompileTimeErrorCode('CONST_WITH_NON_CONSTANT_ARGUMENT',
+ "Arguments of a constant creation must be constant expressions");
+
+ /**
+ * 12.11.2 Const: It is a compile-time error if <i>T</i> is not a class
+ * accessible in the current scope, optionally followed by type arguments.
+ *
+ * 12.11.2 Const: If <i>e</i> is of the form <i>const T.id(a<sub>1</sub>,
+ * …, a<sub>n</sub>, x<sub>n+1</sub>: a<sub>n+1</sub>, …
+ * x<sub>n+k</sub>: a<sub>n+k</sub>)</i> it is a compile-time error if
+ * <i>T</i> is not a class accessible in the current scope, optionally
+ * followed by type arguments.
+ *
+ * Parameters:
+ * 0: the name of the non-type element
+ */
+ static const CompileTimeErrorCode CONST_WITH_NON_TYPE =
+ const CompileTimeErrorCode(
+ 'CONST_WITH_NON_TYPE', "The name '{0}' is not a class");
+
+ /**
+ * 12.11.2 Const: It is a compile-time error if <i>T</i> includes any type
+ * parameters.
+ */
+ static const CompileTimeErrorCode CONST_WITH_TYPE_PARAMETERS =
+ const CompileTimeErrorCode('CONST_WITH_TYPE_PARAMETERS',
+ "The constant creation cannot use a type parameter");
+
+ /**
+ * 12.11.2 Const: It is a compile-time error if <i>T.id</i> is not the name of
+ * a constant constructor declared by the type <i>T</i>.
+ *
+ * Parameters:
+ * 0: the name of the type
+ * 1: the name of the requested constant constructor
+ */
+ static const CompileTimeErrorCode CONST_WITH_UNDEFINED_CONSTRUCTOR =
+ const CompileTimeErrorCode('CONST_WITH_UNDEFINED_CONSTRUCTOR',
+ "The class '{0}' does not have a constant constructor '{1}'");
+
+ /**
+ * 12.11.2 Const: It is a compile-time error if <i>T.id</i> is not the name of
+ * a constant constructor declared by the type <i>T</i>.
+ *
+ * Parameters:
+ * 0: the name of the type
+ */
+ static const CompileTimeErrorCode CONST_WITH_UNDEFINED_CONSTRUCTOR_DEFAULT =
+ const CompileTimeErrorCode('CONST_WITH_UNDEFINED_CONSTRUCTOR_DEFAULT',
+ "The class '{0}' does not have a default constant constructor");
+
+ /**
+ * 15.3.1 Typedef: It is a compile-time error if any default values are
+ * specified in the signature of a function type alias.
+ */
+ static const CompileTimeErrorCode DEFAULT_VALUE_IN_FUNCTION_TYPE_ALIAS =
+ const CompileTimeErrorCode('DEFAULT_VALUE_IN_FUNCTION_TYPE_ALIAS',
+ "Default values aren't allowed in typedefs");
+
+ /**
+ * 6.2.1 Required Formals: By means of a function signature that names the
+ * parameter and describes its type as a function type. It is a compile-time
+ * error if any default values are specified in the signature of such a
+ * function type.
+ */
+ static const CompileTimeErrorCode DEFAULT_VALUE_IN_FUNCTION_TYPED_PARAMETER =
+ const CompileTimeErrorCode('DEFAULT_VALUE_IN_FUNCTION_TYPED_PARAMETER',
+ "Default values aren't allowed in function type parameters");
+
+ /**
+ * 7.6.2 Factories: It is a compile-time error if <i>k</i> explicitly
+ * specifies a default value for an optional parameter.
+ */
+ static const CompileTimeErrorCode
+ DEFAULT_VALUE_IN_REDIRECTING_FACTORY_CONSTRUCTOR =
+ const CompileTimeErrorCode(
+ 'DEFAULT_VALUE_IN_REDIRECTING_FACTORY_CONSTRUCTOR',
+ "Default values aren't allowed in factory constructors that redirect to another constructor");
+
+ /**
+ * 3.1 Scoping: It is a compile-time error if there is more than one entity
+ * with the same name declared in the same scope.
+ */
+ static const CompileTimeErrorCode DUPLICATE_CONSTRUCTOR_DEFAULT =
+ const CompileTimeErrorCode('DUPLICATE_CONSTRUCTOR_DEFAULT',
+ "The default constructor is already defined");
+
+ /**
+ * 3.1 Scoping: It is a compile-time error if there is more than one entity
+ * with the same name declared in the same scope.
+ *
+ * Parameters:
+ * 0: the name of the duplicate entity
+ */
+ static const CompileTimeErrorCode DUPLICATE_CONSTRUCTOR_NAME =
+ const CompileTimeErrorCode('DUPLICATE_CONSTRUCTOR_NAME',
+ "The constructor with name '{0}' is already defined");
+
+ /**
+ * 3.1 Scoping: It is a compile-time error if there is more than one entity
+ * with the same name declared in the same scope.
+ *
+ * 7 Classes: It is a compile-time error if a class declares two members of
+ * the same name.
+ *
+ * 7 Classes: It is a compile-time error if a class has an instance member and
+ * a static member with the same name.
+ *
+ * Parameters:
+ * 0: the name of the duplicate entity
+ */
+ static const CompileTimeErrorCode DUPLICATE_DEFINITION =
+ const CompileTimeErrorCode(
+ 'DUPLICATE_DEFINITION', "The name '{0}' is already defined");
+
+ /**
+ * 7. Classes: It is a compile-time error if a class has an instance member
+ * and a static member with the same name.
+ *
+ * This covers the additional duplicate definition cases where inheritance has
+ * to be considered.
+ *
+ * Parameters:
+ * 0: the name of the class that has conflicting instance/static members
+ * 1: the name of the conflicting members
+ *
+ * See [DUPLICATE_DEFINITION].
+ */
+ static const CompileTimeErrorCode DUPLICATE_DEFINITION_INHERITANCE =
+ const CompileTimeErrorCode('DUPLICATE_DEFINITION_INHERITANCE',
+ "The name '{0}' is already defined in '{1}'");
+
+ /**
+ * 12.14.2 Binding Actuals to Formals: It is a compile-time error if
+ * <i>q<sub>i</sub> = q<sub>j</sub></i> for any <i>i != j</i> [where
+ * <i>q<sub>i</sub></i> is the label for a named argument].
+ */
+ static const CompileTimeErrorCode DUPLICATE_NAMED_ARGUMENT =
+ const CompileTimeErrorCode('DUPLICATE_NAMED_ARGUMENT',
+ "The argument for the named parameter '{0}' was already specified");
+
+ /**
+ * SDK implementation libraries can be exported only by other SDK libraries.
+ *
+ * Parameters:
+ * 0: the uri pointing to a library
+ */
+ static const CompileTimeErrorCode EXPORT_INTERNAL_LIBRARY =
+ const CompileTimeErrorCode('EXPORT_INTERNAL_LIBRARY',
+ "The library '{0}' is internal and cannot be exported");
+
+ /**
+ * 14.2 Exports: It is a compile-time error if the compilation unit found at
+ * the specified URI is not a library declaration.
+ *
+ * Parameters:
+ * 0: the uri pointing to a non-library declaration
+ */
+ static const CompileTimeErrorCode EXPORT_OF_NON_LIBRARY =
+ const CompileTimeErrorCode('EXPORT_OF_NON_LIBRARY',
+ "The exported library '{0}' must not have a part-of directive");
+
+ /**
+ * Enum proposal: It is a compile-time error to subclass, mix-in or implement
+ * an enum.
+ */
+ static const CompileTimeErrorCode EXTENDS_ENUM = const CompileTimeErrorCode(
+ 'EXTENDS_ENUM', "Classes cannot extend an enum");
+
+ /**
+ * 7.9 Superclasses: It is a compile-time error if the extends clause of a
+ * class <i>C</i> includes a type expression that does not denote a class
+ * available in the lexical scope of <i>C</i>.
+ *
+ * Parameters:
+ * 0: the name of the superclass that was not found
+ */
+ static const CompileTimeErrorCode EXTENDS_NON_CLASS =
+ const CompileTimeErrorCode(
+ 'EXTENDS_NON_CLASS', "Classes can only extend other classes");
+
+ /**
+ * 12.2 Null: It is a compile-time error for a class to attempt to extend or
+ * implement Null.
+ *
+ * 12.3 Numbers: It is a compile-time error for a class to attempt to extend
+ * or implement int.
+ *
+ * 12.3 Numbers: It is a compile-time error for a class to attempt to extend
+ * or implement double.
+ *
+ * 12.3 Numbers: It is a compile-time error for any type other than the types
+ * int and double to
+ * attempt to extend or implement num.
+ *
+ * 12.4 Booleans: It is a compile-time error for a class to attempt to extend
+ * or implement bool.
+ *
+ * 12.5 Strings: It is a compile-time error for a class to attempt to extend
+ * or implement String.
+ *
+ * Parameters:
+ * 0: the name of the type that cannot be extended
+ *
+ * See [IMPLEMENTS_DISALLOWED_CLASS].
+ */
+ static const CompileTimeErrorCode EXTENDS_DISALLOWED_CLASS =
+ const CompileTimeErrorCode(
+ 'EXTENDS_DISALLOWED_CLASS', "Classes cannot extend '{0}'");
+
+ /**
+ * 7.9 Superclasses: It is a compile-time error if the extends clause of a
+ * class <i>C</i> includes a deferred type expression.
+ *
+ * Parameters:
+ * 0: the name of the type that cannot be extended
+ *
+ * See [IMPLEMENTS_DEFERRED_CLASS], and [MIXIN_DEFERRED_CLASS].
+ */
+ static const CompileTimeErrorCode EXTENDS_DEFERRED_CLASS =
+ const CompileTimeErrorCode('EXTENDS_DEFERRED_CLASS',
+ "This class cannot extend the deferred class '{0}'");
+
+ /**
+ * DEP 37 extends the syntax for assert() to allow a second "message"
+ * argument. We issue this error if the user tries to supply a "message"
+ * argument but the DEP is not enabled.
+ */
+ static const CompileTimeErrorCode EXTRA_ARGUMENT_TO_ASSERT =
+ const CompileTimeErrorCode('EXTRA_ARGUMENT_TO_ASSERT',
+ "Assertions only accept a single argument");
+
+ /**
+ * 12.14.2 Binding Actuals to Formals: It is a static warning if <i>m <
+ * h</i> or if <i>m > n</i>.
+ *
+ * 12.11.2 Const: It is a compile-time error if evaluation of a constant
+ * object results in an uncaught exception being thrown.
+ *
+ * Parameters:
+ * 0: the maximum number of positional arguments
+ * 1: the actual number of positional arguments given
+ */
+ static const CompileTimeErrorCode EXTRA_POSITIONAL_ARGUMENTS =
+ const CompileTimeErrorCode('EXTRA_POSITIONAL_ARGUMENTS',
+ "{0} positional arguments expected, but {1} found");
+
+ /**
+ * 7.6.1 Generative Constructors: Let <i>k</i> be a generative constructor. It
+ * is a compile time error if more than one initializer corresponding to a
+ * given instance variable appears in <i>k</i>'s list.
+ */
+ static const CompileTimeErrorCode FIELD_INITIALIZED_BY_MULTIPLE_INITIALIZERS =
+ const CompileTimeErrorCode('FIELD_INITIALIZED_BY_MULTIPLE_INITIALIZERS',
+ "The field '{0}' cannot be initialized twice in the same constructor");
+
+ /**
+ * 7.6.1 Generative Constructors: Let <i>k</i> be a generative constructor. It
+ * is a compile time error if <i>k</i>'s initializer list contains an
+ * initializer for a variable that is initialized by means of an initializing
+ * formal of <i>k</i>.
+ */
+ static const CompileTimeErrorCode
+ FIELD_INITIALIZED_IN_PARAMETER_AND_INITIALIZER =
+ const CompileTimeErrorCode(
+ 'FIELD_INITIALIZED_IN_PARAMETER_AND_INITIALIZER',
+ "Fields cannot be initialized in both the parameter list and the initializers");
+
+ /**
+ * 5 Variables: It is a compile-time error if a final instance variable that
+ * has is initialized by means of an initializing formal of a constructor is
+ * also initialized elsewhere in the same constructor.
+ *
+ * Parameters:
+ * 0: the name of the field in question
+ */
+ static const CompileTimeErrorCode FINAL_INITIALIZED_MULTIPLE_TIMES =
+ const CompileTimeErrorCode('FINAL_INITIALIZED_MULTIPLE_TIMES',
+ "'{0}' is a final field and so can only be set once");
+
+ /**
+ * 7.6.1 Generative Constructors: It is a compile-time error if an
+ * initializing formal is used by a function other than a non-redirecting
+ * generative constructor.
+ */
+ static const CompileTimeErrorCode FIELD_INITIALIZER_FACTORY_CONSTRUCTOR =
+ const CompileTimeErrorCode('FIELD_INITIALIZER_FACTORY_CONSTRUCTOR',
+ "Initializing formal fields cannot be used in factory constructors");
+
+ /**
+ * 7.6.1 Generative Constructors: It is a compile-time error if an
+ * initializing formal is used by a function other than a non-redirecting
+ * generative constructor.
+ */
+ static const CompileTimeErrorCode FIELD_INITIALIZER_OUTSIDE_CONSTRUCTOR =
+ const CompileTimeErrorCode('FIELD_INITIALIZER_OUTSIDE_CONSTRUCTOR',
+ "Initializing formal fields can only be used in constructors");
+
+ /**
+ * 7.6.1 Generative Constructors: A generative constructor may be redirecting,
+ * in which case its only action is to invoke another generative constructor.
+ *
+ * 7.6.1 Generative Constructors: It is a compile-time error if an
+ * initializing formal is used by a function other than a non-redirecting
+ * generative constructor.
+ */
+ static const CompileTimeErrorCode FIELD_INITIALIZER_REDIRECTING_CONSTRUCTOR =
+ const CompileTimeErrorCode('FIELD_INITIALIZER_REDIRECTING_CONSTRUCTOR',
+ "The redirecting constructor cannot have a field initializer");
+
+ /**
+ * 7.2 Getters: It is a compile-time error if a class has both a getter and a
+ * method with the same name.
+ *
+ * Parameters:
+ * 0: the conflicting name of the getter and method
+ */
+ static const CompileTimeErrorCode GETTER_AND_METHOD_WITH_SAME_NAME =
+ const CompileTimeErrorCode('GETTER_AND_METHOD_WITH_SAME_NAME',
+ "'{0}' cannot be used to name a getter, there is already a method with the same name");
+
+ /**
+ * 7.10 Superinterfaces: It is a compile-time error if the implements clause
+ * of a class <i>C</i> specifies a malformed type or deferred type as a
+ * superinterface.
+ *
+ * Parameters:
+ * 0: the name of the type that cannot be extended
+ *
+ * See [EXTENDS_DEFERRED_CLASS], and [MIXIN_DEFERRED_CLASS].
+ */
+ static const CompileTimeErrorCode IMPLEMENTS_DEFERRED_CLASS =
+ const CompileTimeErrorCode('IMPLEMENTS_DEFERRED_CLASS',
+ "This class cannot implement the deferred class '{0}'");
+
+ /**
+ * 12.2 Null: It is a compile-time error for a class to attempt to extend or
+ * implement Null.
+ *
+ * 12.3 Numbers: It is a compile-time error for a class to attempt to extend
+ * or implement int.
+ *
+ * 12.3 Numbers: It is a compile-time error for a class to attempt to extend
+ * or implement double.
+ *
+ * 12.3 Numbers: It is a compile-time error for any type other than the types
+ * int and double to
+ * attempt to extend or implement num.
+ *
+ * 12.4 Booleans: It is a compile-time error for a class to attempt to extend
+ * or implement bool.
+ *
+ * 12.5 Strings: It is a compile-time error for a class to attempt to extend
+ * or implement String.
+ *
+ * Parameters:
+ * 0: the name of the type that cannot be implemented
+ *
+ * See [EXTENDS_DISALLOWED_CLASS].
+ */
+ static const CompileTimeErrorCode IMPLEMENTS_DISALLOWED_CLASS =
+ const CompileTimeErrorCode(
+ 'IMPLEMENTS_DISALLOWED_CLASS', "Classes cannot implement '{0}'");
+
+ /**
+ * 7.10 Superinterfaces: It is a compile-time error if the implements clause
+ * of a class includes type dynamic.
+ */
+ static const CompileTimeErrorCode IMPLEMENTS_DYNAMIC =
+ const CompileTimeErrorCode(
+ 'IMPLEMENTS_DYNAMIC', "Classes cannot implement 'dynamic'");
+
+ /**
+ * Enum proposal: It is a compile-time error to subclass, mix-in or implement
+ * an enum.
+ */
+ static const CompileTimeErrorCode IMPLEMENTS_ENUM =
+ const CompileTimeErrorCode(
+ 'IMPLEMENTS_ENUM', "Classes cannot implement an enum");
+
+ /**
+ * 7.10 Superinterfaces: It is a compile-time error if the implements clause
+ * of a class <i>C</i> includes a type expression that does not denote a class
+ * available in the lexical scope of <i>C</i>.
+ *
+ * Parameters:
+ * 0: the name of the interface that was not found
+ */
+ static const CompileTimeErrorCode IMPLEMENTS_NON_CLASS =
+ const CompileTimeErrorCode(
+ 'IMPLEMENTS_NON_CLASS', "Classes can only implement other classes");
+
+ /**
+ * 7.10 Superinterfaces: It is a compile-time error if a type <i>T</i> appears
+ * more than once in the implements clause of a class.
+ *
+ * Parameters:
+ * 0: the name of the class that is implemented more than once
+ */
+ static const CompileTimeErrorCode IMPLEMENTS_REPEATED =
+ const CompileTimeErrorCode(
+ 'IMPLEMENTS_REPEATED', "'{0}' can only be implemented once");
+
+ /**
+ * 7.10 Superinterfaces: It is a compile-time error if the superclass of a
+ * class <i>C</i> appears in the implements clause of <i>C</i>.
+ *
+ * Parameters:
+ * 0: the name of the class that appears in both "extends" and "implements"
+ * clauses
+ */
+ static const CompileTimeErrorCode IMPLEMENTS_SUPER_CLASS =
+ const CompileTimeErrorCode('IMPLEMENTS_SUPER_CLASS',
+ "'{0}' cannot be used in both 'extends' and 'implements' clauses");
+
+ /**
+ * 7.6.1 Generative Constructors: Note that <b>this</b> is not in scope on the
+ * right hand side of an initializer.
+ *
+ * 12.10 This: It is a compile-time error if this appears in a top-level
+ * function or variable initializer, in a factory constructor, or in a static
+ * method or variable initializer, or in the initializer of an instance
+ * variable.
+ *
+ * Parameters:
+ * 0: the name of the type in question
+ */
+ static const CompileTimeErrorCode IMPLICIT_THIS_REFERENCE_IN_INITIALIZER =
+ const CompileTimeErrorCode('IMPLICIT_THIS_REFERENCE_IN_INITIALIZER',
+ "Only static members can be accessed in initializers");
+
+ /**
+ * SDK implementation libraries can be imported only by other SDK libraries.
+ *
+ * Parameters:
+ * 0: the uri pointing to a library
+ */
+ static const CompileTimeErrorCode IMPORT_INTERNAL_LIBRARY =
+ const CompileTimeErrorCode('IMPORT_INTERNAL_LIBRARY',
+ "The library '{0}' is internal and cannot be imported");
+
+ /**
+ * 14.1 Imports: It is a compile-time error if the specified URI of an
+ * immediate import does not refer to a library declaration.
+ *
+ * Parameters:
+ * 0: the uri pointing to a non-library declaration
+ *
+ * See [StaticWarningCode.IMPORT_OF_NON_LIBRARY].
+ */
+ static const CompileTimeErrorCode IMPORT_OF_NON_LIBRARY =
+ const CompileTimeErrorCode('IMPORT_OF_NON_LIBRARY',
+ "The imported library '{0}' must not have a part-of directive");
+
+ /**
+ * 13.9 Switch: It is a compile-time error if values of the expressions
+ * <i>e<sub>k</sub></i> are not instances of the same class <i>C</i>, for all
+ * <i>1 <= k <= n</i>.
+ *
+ * Parameters:
+ * 0: the expression source code that is the unexpected type
+ * 1: the name of the expected type
+ */
+ static const CompileTimeErrorCode INCONSISTENT_CASE_EXPRESSION_TYPES =
+ const CompileTimeErrorCode('INCONSISTENT_CASE_EXPRESSION_TYPES',
+ "Case expressions must have the same types, '{0}' is not a '{1}'");
+
+ /**
+ * 7.6.1 Generative Constructors: Let <i>k</i> be a generative constructor. It
+ * is a compile-time error if <i>k</i>'s initializer list contains an
+ * initializer for a variable that is not an instance variable declared in the
+ * immediately surrounding class.
+ *
+ * Parameters:
+ * 0: the name of the initializing formal that is not an instance variable in
+ * the immediately enclosing class
+ *
+ * See [INITIALIZING_FORMAL_FOR_NON_EXISTENT_FIELD].
+ */
+ static const CompileTimeErrorCode INITIALIZER_FOR_NON_EXISTENT_FIELD =
+ const CompileTimeErrorCode('INITIALIZER_FOR_NON_EXISTENT_FIELD',
+ "'{0}' is not a variable in the enclosing class");
+
+ /**
+ * 7.6.1 Generative Constructors: Let <i>k</i> be a generative constructor. It
+ * is a compile-time error if <i>k</i>'s initializer list contains an
+ * initializer for a variable that is not an instance variable declared in the
+ * immediately surrounding class.
+ *
+ * Parameters:
+ * 0: the name of the initializing formal that is a static variable in the
+ * immediately enclosing class
+ *
+ * See [INITIALIZING_FORMAL_FOR_STATIC_FIELD].
+ */
+ static const CompileTimeErrorCode INITIALIZER_FOR_STATIC_FIELD =
+ const CompileTimeErrorCode('INITIALIZER_FOR_STATIC_FIELD',
+ "'{0}' is a static variable in the enclosing class, variables initialized in a constructor cannot be static");
+
+ /**
+ * 7.6.1 Generative Constructors: An initializing formal has the form
+ * <i>this.id</i>. It is a compile-time error if <i>id</i> is not the name of
+ * an instance variable of the immediately enclosing class.
+ *
+ * Parameters:
+ * 0: the name of the initializing formal that is not an instance variable in
+ * the immediately enclosing class
+ *
+ * See [INITIALIZING_FORMAL_FOR_STATIC_FIELD], and
+ * [INITIALIZER_FOR_NON_EXISTENT_FIELD].
+ */
+ static const CompileTimeErrorCode INITIALIZING_FORMAL_FOR_NON_EXISTENT_FIELD =
+ const CompileTimeErrorCode('INITIALIZING_FORMAL_FOR_NON_EXISTENT_FIELD',
+ "'{0}' is not a variable in the enclosing class");
+
+ /**
+ * 7.6.1 Generative Constructors: An initializing formal has the form
+ * <i>this.id</i>. It is a compile-time error if <i>id</i> is not the name of
+ * an instance variable of the immediately enclosing class.
+ *
+ * Parameters:
+ * 0: the name of the initializing formal that is a static variable in the
+ * immediately enclosing class
+ *
+ * See [INITIALIZER_FOR_STATIC_FIELD].
+ */
+ static const CompileTimeErrorCode INITIALIZING_FORMAL_FOR_STATIC_FIELD =
+ const CompileTimeErrorCode('INITIALIZING_FORMAL_FOR_STATIC_FIELD',
+ "'{0}' is a static field in the enclosing class, fields initialized in a constructor cannot be static");
+
+ /**
+ * 12.30 Identifier Reference: Otherwise, e is equivalent to the property
+ * extraction <b>this</b>.<i>id</i>.
+ */
+ static const CompileTimeErrorCode INSTANCE_MEMBER_ACCESS_FROM_FACTORY =
+ const CompileTimeErrorCode('INSTANCE_MEMBER_ACCESS_FROM_FACTORY',
+ "Instance members cannot be accessed from a factory constructor");
+
+ /**
+ * 12.30 Identifier Reference: Otherwise, e is equivalent to the property
+ * extraction <b>this</b>.<i>id</i>.
+ */
+ static const CompileTimeErrorCode INSTANCE_MEMBER_ACCESS_FROM_STATIC =
+ const CompileTimeErrorCode('INSTANCE_MEMBER_ACCESS_FROM_STATIC',
+ "Instance members cannot be accessed from a static method");
+
+ /**
+ * Enum proposal: It is also a compile-time error to explicitly instantiate an
+ * enum via 'new' or 'const' or to access its private fields.
+ */
+ static const CompileTimeErrorCode INSTANTIATE_ENUM =
+ const CompileTimeErrorCode(
+ 'INSTANTIATE_ENUM', "Enums cannot be instantiated");
+
+ /**
+ * 11 Metadata: Metadata consists of a series of annotations, each of which
+ * begin with the character @, followed by a constant expression that must be
+ * either a reference to a compile-time constant variable, or a call to a
+ * constant constructor.
+ */
+ static const CompileTimeErrorCode INVALID_ANNOTATION = const CompileTimeErrorCode(
+ 'INVALID_ANNOTATION',
+ "Annotation can be only constant variable or constant constructor invocation");
+
+ /**
+ * 11 Metadata: Metadata consists of a series of annotations, each of which
+ * begin with the character @, followed by a constant expression that must be
+ * either a reference to a compile-time constant variable, or a call to a
+ * constant constructor.
+ *
+ * 12.1 Constants: A qualified reference to a static constant variable that is
+ * not qualified by a deferred prefix.
+ */
+ static const CompileTimeErrorCode INVALID_ANNOTATION_FROM_DEFERRED_LIBRARY =
+ const CompileTimeErrorCode('INVALID_ANNOTATION_FROM_DEFERRED_LIBRARY',
+ "Constant values from a deferred library cannot be used as annotations");
+
+ /**
+ * 15.31 Identifier Reference: It is a compile-time error if any of the
+ * identifiers async, await or yield is used as an identifier in a function
+ * body marked with either async, async* or sync*.
+ */
+ static const CompileTimeErrorCode INVALID_IDENTIFIER_IN_ASYNC =
+ const CompileTimeErrorCode('INVALID_IDENTIFIER_IN_ASYNC',
+ "The identifier '{0}' cannot be used in a function marked with async, async* or sync*");
+
+ /**
+ * 9. Functions: It is a compile-time error if an async, async* or sync*
+ * modifier is attached to the body of a setter or constructor.
+ */
+ static const CompileTimeErrorCode INVALID_MODIFIER_ON_CONSTRUCTOR =
+ const CompileTimeErrorCode('INVALID_MODIFIER_ON_CONSTRUCTOR',
+ "The modifier '{0}' cannot be applied to the body of a constructor");
+
+ /**
+ * 9. Functions: It is a compile-time error if an async, async* or sync*
+ * modifier is attached to the body of a setter or constructor.
+ */
+ static const CompileTimeErrorCode INVALID_MODIFIER_ON_SETTER =
+ const CompileTimeErrorCode('INVALID_MODIFIER_ON_SETTER',
+ "The modifier '{0}' cannot be applied to the body of a setter");
+
+ /**
+ * TODO(brianwilkerson) Remove this when we have decided on how to report
+ * errors in compile-time constants. Until then, this acts as a placeholder
+ * for more informative errors.
+ *
+ * See TODOs in ConstantVisitor
+ */
+ static const CompileTimeErrorCode INVALID_CONSTANT =
+ const CompileTimeErrorCode('INVALID_CONSTANT', "Invalid constant value");
+
+ /**
+ * 7.6 Constructors: It is a compile-time error if the name of a constructor
+ * is not a constructor name.
+ */
+ static const CompileTimeErrorCode INVALID_CONSTRUCTOR_NAME =
+ const CompileTimeErrorCode(
+ 'INVALID_CONSTRUCTOR_NAME', "Invalid constructor name");
+
+ /**
+ * 7.6.2 Factories: It is a compile-time error if <i>M</i> is not the name of
+ * the immediately enclosing class.
+ */
+ static const CompileTimeErrorCode INVALID_FACTORY_NAME_NOT_A_CLASS =
+ const CompileTimeErrorCode('INVALID_FACTORY_NAME_NOT_A_CLASS',
+ "The name of the immediately enclosing class expected");
+
+ /**
+ * 12.10 This: It is a compile-time error if this appears in a top-level
+ * function or variable initializer, in a factory constructor, or in a static
+ * method or variable initializer, or in the initializer of an instance
+ * variable.
+ */
+ static const CompileTimeErrorCode INVALID_REFERENCE_TO_THIS =
+ const CompileTimeErrorCode('INVALID_REFERENCE_TO_THIS',
+ "Invalid reference to 'this' expression");
+
+ /**
+ * 12.6 Lists: It is a compile time error if the type argument of a constant
+ * list literal includes a type parameter.
+ *
+ * Parameters:
+ * 0: the name of the type parameter
+ */
+ static const CompileTimeErrorCode INVALID_TYPE_ARGUMENT_IN_CONST_LIST =
+ const CompileTimeErrorCode('INVALID_TYPE_ARGUMENT_IN_CONST_LIST',
+ "Constant list literals cannot include a type parameter as a type argument, such as '{0}'");
+
+ /**
+ * 12.7 Maps: It is a compile time error if the type arguments of a constant
+ * map literal include a type parameter.
+ *
+ * Parameters:
+ * 0: the name of the type parameter
+ */
+ static const CompileTimeErrorCode INVALID_TYPE_ARGUMENT_IN_CONST_MAP =
+ const CompileTimeErrorCode('INVALID_TYPE_ARGUMENT_IN_CONST_MAP',
+ "Constant map literals cannot include a type parameter as a type argument, such as '{0}'");
+
+ /**
+ * 14.2 Exports: It is a compile-time error if the compilation unit found at
+ * the specified URI is not a library declaration.
+ *
+ * 14.1 Imports: It is a compile-time error if the compilation unit found at
+ * the specified URI is not a library declaration.
+ *
+ * 14.3 Parts: It is a compile time error if the contents of the URI are not a
+ * valid part declaration.
+ *
+ * Parameters:
+ * 0: the URI that is invalid
+ *
+ * See [URI_DOES_NOT_EXIST].
+ */
+ static const CompileTimeErrorCode INVALID_URI =
+ const CompileTimeErrorCode('INVALID_URI', "Invalid URI syntax: '{0}'");
+
+ /**
+ * 13.13 Break: It is a compile-time error if no such statement
+ * <i>s<sub>E</sub></i> exists within the innermost function in which
+ * <i>s<sub>b</sub></i> occurs.
+ *
+ * 13.14 Continue: It is a compile-time error if no such statement or case
+ * clause <i>s<sub>E</sub></i> exists within the innermost function in which
+ * <i>s<sub>c</sub></i> occurs.
+ *
+ * Parameters:
+ * 0: the name of the unresolvable label
+ */
+ static const CompileTimeErrorCode LABEL_IN_OUTER_SCOPE =
+ const CompileTimeErrorCode('LABEL_IN_OUTER_SCOPE',
+ "Cannot reference label '{0}' declared in an outer method");
+
+ /**
+ * 13.13 Break: It is a compile-time error if no such statement
+ * <i>s<sub>E</sub></i> exists within the innermost function in which
+ * <i>s<sub>b</sub></i> occurs.
+ *
+ * 13.14 Continue: It is a compile-time error if no such statement or case
+ * clause <i>s<sub>E</sub></i> exists within the innermost function in which
+ * <i>s<sub>c</sub></i> occurs.
+ *
+ * Parameters:
+ * 0: the name of the unresolvable label
+ */
+ static const CompileTimeErrorCode LABEL_UNDEFINED =
+ const CompileTimeErrorCode(
+ 'LABEL_UNDEFINED', "Cannot reference undefined label '{0}'");
+
+ /**
+ * 7 Classes: It is a compile time error if a class <i>C</i> declares a member
+ * with the same name as <i>C</i>.
+ */
+ static const CompileTimeErrorCode MEMBER_WITH_CLASS_NAME =
+ const CompileTimeErrorCode('MEMBER_WITH_CLASS_NAME',
+ "Class members cannot have the same name as the enclosing class");
+
+ /**
+ * 7.2 Getters: It is a compile-time error if a class has both a getter and a
+ * method with the same name.
+ *
+ * Parameters:
+ * 0: the conflicting name of the getter and method
+ */
+ static const CompileTimeErrorCode METHOD_AND_GETTER_WITH_SAME_NAME =
+ const CompileTimeErrorCode('METHOD_AND_GETTER_WITH_SAME_NAME',
+ "'{0}' cannot be used to name a method, there is already a getter with the same name");
+
+ /**
+ * 12.1 Constants: A constant expression is ... a constant list literal.
+ */
+ static const CompileTimeErrorCode MISSING_CONST_IN_LIST_LITERAL =
+ const CompileTimeErrorCode('MISSING_CONST_IN_LIST_LITERAL',
+ "List literals must be prefixed with 'const' when used as a constant expression");
+
+ /**
+ * 12.1 Constants: A constant expression is ... a constant map literal.
+ */
+ static const CompileTimeErrorCode MISSING_CONST_IN_MAP_LITERAL =
+ const CompileTimeErrorCode('MISSING_CONST_IN_MAP_LITERAL',
+ "Map literals must be prefixed with 'const' when used as a constant expression");
+
+ /**
+ * 9 Mixins: It is a compile-time error if a declared or derived mixin
+ * explicitly declares a constructor.
+ *
+ * Parameters:
+ * 0: the name of the mixin that is invalid
+ */
+ static const CompileTimeErrorCode MIXIN_DECLARES_CONSTRUCTOR =
+ const CompileTimeErrorCode('MIXIN_DECLARES_CONSTRUCTOR',
+ "The class '{0}' cannot be used as a mixin because it declares a constructor");
+
+ /**
+ * 9.1 Mixin Application: It is a compile-time error if the with clause of a
+ * mixin application <i>C</i> includes a deferred type expression.
+ *
+ * Parameters:
+ * 0: the name of the type that cannot be extended
+ *
+ * See [EXTENDS_DEFERRED_CLASS], and [IMPLEMENTS_DEFERRED_CLASS].
+ */
+ static const CompileTimeErrorCode MIXIN_DEFERRED_CLASS =
+ const CompileTimeErrorCode('MIXIN_DEFERRED_CLASS',
+ "This class cannot mixin the deferred class '{0}'");
+
+ /**
+ * Not yet in the spec, but consistent with VM behavior. It is a
+ * compile-time error if all of the constructors of a mixin's base class have
+ * at least one optional parameter (since only constructors that lack
+ * optional parameters can be forwarded to the mixin). See
+ * https://code.google.com/p/dart/issues/detail?id=15101#c4
+ */
+ static const CompileTimeErrorCode MIXIN_HAS_NO_CONSTRUCTORS =
+ const CompileTimeErrorCode(
+ 'MIXIN_HAS_NO_CONSTRUCTORS',
+ "This mixin application is invalid because all of the constructors "
+ "in the base class '{0}' have optional parameters.");
+
+ /**
+ * 9 Mixins: It is a compile-time error if a mixin is derived from a class
+ * whose superclass is not Object.
+ *
+ * Parameters:
+ * 0: the name of the mixin that is invalid
+ */
+ static const CompileTimeErrorCode MIXIN_INHERITS_FROM_NOT_OBJECT =
+ const CompileTimeErrorCode('MIXIN_INHERITS_FROM_NOT_OBJECT',
+ "The class '{0}' cannot be used as a mixin because it extends a class other than Object");
+
+ /**
+ * 12.2 Null: It is a compile-time error for a class to attempt to extend or
+ * implement Null.
+ *
+ * 12.3 Numbers: It is a compile-time error for a class to attempt to extend
+ * or implement int.
+ *
+ * 12.3 Numbers: It is a compile-time error for a class to attempt to extend
+ * or implement double.
+ *
+ * 12.3 Numbers: It is a compile-time error for any type other than the types
+ * int and double to attempt to extend or implement num.
+ *
+ * 12.4 Booleans: It is a compile-time error for a class to attempt to extend
+ * or implement bool.
+ *
+ * 12.5 Strings: It is a compile-time error for a class to attempt to extend
+ * or implement String.
+ *
+ * Parameters:
+ * 0: the name of the type that cannot be extended
+ *
+ * See [IMPLEMENTS_DISALLOWED_CLASS].
+ */
+ static const CompileTimeErrorCode MIXIN_OF_DISALLOWED_CLASS =
+ const CompileTimeErrorCode(
+ 'MIXIN_OF_DISALLOWED_CLASS', "Classes cannot mixin '{0}'");
+
+ /**
+ * Enum proposal: It is a compile-time error to subclass, mix-in or implement
+ * an enum.
+ */
+ static const CompileTimeErrorCode MIXIN_OF_ENUM = const CompileTimeErrorCode(
+ 'MIXIN_OF_ENUM', "Classes cannot mixin an enum");
+
+ /**
+ * 9.1 Mixin Application: It is a compile-time error if <i>M</i> does not
+ * denote a class or mixin available in the immediately enclosing scope.
+ */
+ static const CompileTimeErrorCode MIXIN_OF_NON_CLASS =
+ const CompileTimeErrorCode(
+ 'MIXIN_OF_NON_CLASS', "Classes can only mixin other classes");
+
+ /**
+ * 9 Mixins: It is a compile-time error if a declared or derived mixin refers
+ * to super.
+ */
+ static const CompileTimeErrorCode MIXIN_REFERENCES_SUPER =
+ const CompileTimeErrorCode('MIXIN_REFERENCES_SUPER',
+ "The class '{0}' cannot be used as a mixin because it references 'super'");
+
+ /**
+ * 9.1 Mixin Application: It is a compile-time error if <i>S</i> does not
+ * denote a class available in the immediately enclosing scope.
+ */
+ static const CompileTimeErrorCode MIXIN_WITH_NON_CLASS_SUPERCLASS =
+ const CompileTimeErrorCode('MIXIN_WITH_NON_CLASS_SUPERCLASS',
+ "Mixin can only be applied to class");
+
+ /**
+ * 7.6.1 Generative Constructors: A generative constructor may be redirecting,
+ * in which case its only action is to invoke another generative constructor.
+ */
+ static const CompileTimeErrorCode
+ MULTIPLE_REDIRECTING_CONSTRUCTOR_INVOCATIONS = const CompileTimeErrorCode(
+ 'MULTIPLE_REDIRECTING_CONSTRUCTOR_INVOCATIONS',
+ "Constructor may have at most one 'this' redirection");
+
+ /**
+ * 7.6.1 Generative Constructors: Let <i>k</i> be a generative constructor.
+ * Then <i>k</i> may include at most one superinitializer in its initializer
+ * list or a compile time error occurs.
+ */
+ static const CompileTimeErrorCode MULTIPLE_SUPER_INITIALIZERS =
+ const CompileTimeErrorCode('MULTIPLE_SUPER_INITIALIZERS',
+ "Constructor may have at most one 'super' initializer");
+
+ /**
+ * 11 Metadata: Metadata consists of a series of annotations, each of which
+ * begin with the character @, followed by a constant expression that must be
+ * either a reference to a compile-time constant variable, or a call to a
+ * constant constructor.
+ */
+ static const CompileTimeErrorCode NO_ANNOTATION_CONSTRUCTOR_ARGUMENTS =
+ const CompileTimeErrorCode('NO_ANNOTATION_CONSTRUCTOR_ARGUMENTS',
+ "Annotation creation must have arguments");
+
+ /**
+ * 7.6.1 Generative Constructors: If no superinitializer is provided, an
+ * implicit superinitializer of the form <b>super</b>() is added at the end of
+ * <i>k</i>'s initializer list, unless the enclosing class is class
+ * <i>Object</i>.
+ *
+ * 7.6.1 Generative constructors. It is a compile-time error if class <i>S</i>
+ * does not declare a generative constructor named <i>S</i> (respectively
+ * <i>S.id</i>)
+ */
+ static const CompileTimeErrorCode NO_DEFAULT_SUPER_CONSTRUCTOR_EXPLICIT =
+ const CompileTimeErrorCode('NO_DEFAULT_SUPER_CONSTRUCTOR_EXPLICIT',
+ "The class '{0}' does not have a default constructor");
+
+ /**
+ * 7.6 Constructors: Iff no constructor is specified for a class <i>C</i>, it
+ * implicitly has a default constructor C() : <b>super<b>() {}, unless
+ * <i>C</i> is class <i>Object</i>.
+ *
+ * 7.6.1 Generative constructors. It is a compile-time error if class <i>S</i>
+ * does not declare a generative constructor named <i>S</i> (respectively
+ * <i>S.id</i>)
+ */
+ static const CompileTimeErrorCode NO_DEFAULT_SUPER_CONSTRUCTOR_IMPLICIT =
+ const CompileTimeErrorCode('NO_DEFAULT_SUPER_CONSTRUCTOR_IMPLICIT',
+ "The class '{0}' does not have a default constructor");
+
+ /**
+ * 13.2 Expression Statements: It is a compile-time error if a non-constant
+ * map literal that has no explicit type arguments appears in a place where a
+ * statement is expected.
+ */
+ static const CompileTimeErrorCode NON_CONST_MAP_AS_EXPRESSION_STATEMENT =
+ const CompileTimeErrorCode('NON_CONST_MAP_AS_EXPRESSION_STATEMENT',
+ "A non-constant map literal without type arguments cannot be used as an expression statement");
+
+ /**
+ * 13.9 Switch: Given a switch statement of the form <i>switch (e) {
+ * label<sub>11</sub> … label<sub>1j1</sub> case e<sub>1</sub>:
+ * s<sub>1</sub> … label<sub>n1</sub> … label<sub>njn</sub> case
+ * e<sub>n</sub>: s<sub>n</sub> default: s<sub>n+1</sub>}</i> or the form
+ * <i>switch (e) { label<sub>11</sub> … label<sub>1j1</sub> case
+ * e<sub>1</sub>: s<sub>1</sub> … label<sub>n1</sub> …
+ * label<sub>njn</sub> case e<sub>n</sub>: s<sub>n</sub>}</i>, it is a
+ * compile-time error if the expressions <i>e<sub>k</sub></i> are not
+ * compile-time constants, for all <i>1 <= k <= n</i>.
+ */
+ static const CompileTimeErrorCode NON_CONSTANT_CASE_EXPRESSION =
+ const CompileTimeErrorCode(
+ 'NON_CONSTANT_CASE_EXPRESSION', "Case expressions must be constant");
+
+ /**
+ * 13.9 Switch: Given a switch statement of the form <i>switch (e) {
+ * label<sub>11</sub> … label<sub>1j1</sub> case e<sub>1</sub>:
+ * s<sub>1</sub> … label<sub>n1</sub> … label<sub>njn</sub> case
+ * e<sub>n</sub>: s<sub>n</sub> default: s<sub>n+1</sub>}</i> or the form
+ * <i>switch (e) { label<sub>11</sub> … label<sub>1j1</sub> case
+ * e<sub>1</sub>: s<sub>1</sub> … label<sub>n1</sub> …
+ * label<sub>njn</sub> case e<sub>n</sub>: s<sub>n</sub>}</i>, it is a
+ * compile-time error if the expressions <i>e<sub>k</sub></i> are not
+ * compile-time constants, for all <i>1 <= k <= n</i>.
+ *
+ * 12.1 Constants: A qualified reference to a static constant variable that is
+ * not qualified by a deferred prefix.
+ */
+ static const CompileTimeErrorCode
+ NON_CONSTANT_CASE_EXPRESSION_FROM_DEFERRED_LIBRARY =
+ const CompileTimeErrorCode(
+ 'NON_CONSTANT_CASE_EXPRESSION_FROM_DEFERRED_LIBRARY',
+ "Constant values from a deferred library cannot be used as a case expression");
+
+ /**
+ * 6.2.2 Optional Formals: It is a compile-time error if the default value of
+ * an optional parameter is not a compile-time constant.
+ */
+ static const CompileTimeErrorCode NON_CONSTANT_DEFAULT_VALUE =
+ const CompileTimeErrorCode('NON_CONSTANT_DEFAULT_VALUE',
+ "Default values of an optional parameter must be constant");
+
+ /**
+ * 6.2.2 Optional Formals: It is a compile-time error if the default value of
+ * an optional parameter is not a compile-time constant.
+ *
+ * 12.1 Constants: A qualified reference to a static constant variable that is
+ * not qualified by a deferred prefix.
+ */
+ static const CompileTimeErrorCode
+ NON_CONSTANT_DEFAULT_VALUE_FROM_DEFERRED_LIBRARY =
+ const CompileTimeErrorCode(
+ 'NON_CONSTANT_DEFAULT_VALUE_FROM_DEFERRED_LIBRARY',
+ "Constant values from a deferred library cannot be used as a default parameter value");
+
+ /**
+ * 12.6 Lists: It is a compile time error if an element of a constant list
+ * literal is not a compile-time constant.
+ */
+ static const CompileTimeErrorCode NON_CONSTANT_LIST_ELEMENT =
+ const CompileTimeErrorCode('NON_CONSTANT_LIST_ELEMENT',
+ "'const' lists must have all constant values");
+
+ /**
+ * 12.6 Lists: It is a compile time error if an element of a constant list
+ * literal is not a compile-time constant.
+ *
+ * 12.1 Constants: A qualified reference to a static constant variable that is
+ * not qualified by a deferred prefix.
+ */
+ static const CompileTimeErrorCode
+ NON_CONSTANT_LIST_ELEMENT_FROM_DEFERRED_LIBRARY =
+ const CompileTimeErrorCode(
+ 'NON_CONSTANT_LIST_ELEMENT_FROM_DEFERRED_LIBRARY',
+ "Constant values from a deferred library cannot be used as values in a 'const' list");
+
+ /**
+ * 12.7 Maps: It is a compile time error if either a key or a value of an
+ * entry in a constant map literal is not a compile-time constant.
+ */
+ static const CompileTimeErrorCode NON_CONSTANT_MAP_KEY =
+ const CompileTimeErrorCode(
+ 'NON_CONSTANT_MAP_KEY', "The keys in a map must be constant");
+
+ /**
+ * 12.7 Maps: It is a compile time error if either a key or a value of an
+ * entry in a constant map literal is not a compile-time constant.
+ *
+ * 12.1 Constants: A qualified reference to a static constant variable that is
+ * not qualified by a deferred prefix.
+ */
+ static const CompileTimeErrorCode NON_CONSTANT_MAP_KEY_FROM_DEFERRED_LIBRARY =
+ const CompileTimeErrorCode('NON_CONSTANT_MAP_KEY_FROM_DEFERRED_LIBRARY',
+ "Constant values from a deferred library cannot be used as keys in a map");
+
+ /**
+ * 12.7 Maps: It is a compile time error if either a key or a value of an
+ * entry in a constant map literal is not a compile-time constant.
+ */
+ static const CompileTimeErrorCode NON_CONSTANT_MAP_VALUE =
+ const CompileTimeErrorCode('NON_CONSTANT_MAP_VALUE',
+ "The values in a 'const' map must be constant");
+
+ /**
+ * 12.7 Maps: It is a compile time error if either a key or a value of an
+ * entry in a constant map literal is not a compile-time constant.
+ *
+ * 12.1 Constants: A qualified reference to a static constant variable that is
+ * not qualified by a deferred prefix.
+ */
+ static const CompileTimeErrorCode
+ NON_CONSTANT_MAP_VALUE_FROM_DEFERRED_LIBRARY = const CompileTimeErrorCode(
+ 'NON_CONSTANT_MAP_VALUE_FROM_DEFERRED_LIBRARY',
+ "Constant values from a deferred library cannot be used as values in a 'const' map");
+
+ /**
+ * 11 Metadata: Metadata consists of a series of annotations, each of which
+ * begin with the character @, followed by a constant expression that must be
+ * either a reference to a compile-time constant variable, or a call to a
+ * constant constructor.
+ *
+ * "From deferred library" case is covered by
+ * [CompileTimeErrorCode.INVALID_ANNOTATION_FROM_DEFERRED_LIBRARY].
+ */
+ static const CompileTimeErrorCode NON_CONSTANT_ANNOTATION_CONSTRUCTOR =
+ const CompileTimeErrorCode('NON_CONSTANT_ANNOTATION_CONSTRUCTOR',
+ "Annotation creation can use only 'const' constructor");
+
+ /**
+ * 7.6.3 Constant Constructors: Any expression that appears within the
+ * initializer list of a constant constructor must be a potentially constant
+ * expression, or a compile-time error occurs.
+ */
+ static const CompileTimeErrorCode NON_CONSTANT_VALUE_IN_INITIALIZER =
+ const CompileTimeErrorCode('NON_CONSTANT_VALUE_IN_INITIALIZER',
+ "Initializer expressions in constant constructors must be constants");
+
+ /**
+ * 7.6.3 Constant Constructors: Any expression that appears within the
+ * initializer list of a constant constructor must be a potentially constant
+ * expression, or a compile-time error occurs.
+ *
+ * 12.1 Constants: A qualified reference to a static constant variable that is
+ * not qualified by a deferred prefix.
+ */
+ static const CompileTimeErrorCode
+ NON_CONSTANT_VALUE_IN_INITIALIZER_FROM_DEFERRED_LIBRARY =
+ const CompileTimeErrorCode(
+ 'NON_CONSTANT_VALUE_IN_INITIALIZER_FROM_DEFERRED_LIBRARY',
+ "Constant values from a deferred library cannot be used as constant initializers");
+
+ /**
+ * 12.14.2 Binding Actuals to Formals: It is a static warning if <i>m < h</i>
+ * or if <i>m > n</i>.
+ *
+ * 12.11.2 Const: It is a compile-time error if evaluation of a constant
+ * object results in an uncaught exception being thrown.
+ *
+ * Parameters:
+ * 0: the expected number of required arguments
+ * 1: the actual number of positional arguments given
+ */
+ static const CompileTimeErrorCode NOT_ENOUGH_REQUIRED_ARGUMENTS =
+ const CompileTimeErrorCode('NOT_ENOUGH_REQUIRED_ARGUMENTS',
+ "{0} required argument(s) expected, but {1} found");
+
+ /**
+ * 7.6.1 Generative Constructors: Let <i>C</i> be the class in which the
+ * superinitializer appears and let <i>S</i> be the superclass of <i>C</i>.
+ * Let <i>k</i> be a generative constructor. It is a compile-time error if
+ * class <i>S</i> does not declare a generative constructor named <i>S</i>
+ * (respectively <i>S.id</i>)
+ */
+ static const CompileTimeErrorCode NON_GENERATIVE_CONSTRUCTOR =
+ const CompileTimeErrorCode('NON_GENERATIVE_CONSTRUCTOR',
+ "The generative constructor '{0}' expected, but factory found");
+
+ /**
+ * 7.9 Superclasses: It is a compile-time error to specify an extends clause
+ * for class Object.
+ */
+ static const CompileTimeErrorCode OBJECT_CANNOT_EXTEND_ANOTHER_CLASS =
+ const CompileTimeErrorCode('OBJECT_CANNOT_EXTEND_ANOTHER_CLASS', "");
+
+ /**
+ * 7.1.1 Operators: It is a compile-time error to declare an optional
+ * parameter in an operator.
+ */
+ static const CompileTimeErrorCode OPTIONAL_PARAMETER_IN_OPERATOR =
+ const CompileTimeErrorCode('OPTIONAL_PARAMETER_IN_OPERATOR',
+ "Optional parameters are not allowed when defining an operator");
+
+ /**
+ * 14.3 Parts: It is a compile time error if the contents of the URI are not a
+ * valid part declaration.
+ *
+ * Parameters:
+ * 0: the uri pointing to a non-library declaration
+ */
+ static const CompileTimeErrorCode PART_OF_NON_PART =
+ const CompileTimeErrorCode('PART_OF_NON_PART',
+ "The included part '{0}' must have a part-of directive");
+
+ /**
+ * 14.1 Imports: It is a compile-time error if the current library declares a
+ * top-level member named <i>p</i>.
+ */
+ static const CompileTimeErrorCode PREFIX_COLLIDES_WITH_TOP_LEVEL_MEMBER =
+ const CompileTimeErrorCode('PREFIX_COLLIDES_WITH_TOP_LEVEL_MEMBER',
+ "The name '{0}' is already used as an import prefix and cannot be used to name a top-level element");
+
+ /**
+ * 16.32 Identifier Reference: If d is a prefix p, a compile-time error
+ * occurs unless the token immediately following d is '.'.
+ */
+ static const CompileTimeErrorCode PREFIX_IDENTIFIER_NOT_FOLLOWED_BY_DOT =
+ const CompileTimeErrorCode('PREFIX_IDENTIFIER_NOT_FOLLOWED_BY_DOT',
+ "The name '{0}' refers to an import prefix, so it must be followed by '.'");
+
+ /**
+ * 6.2.2 Optional Formals: It is a compile-time error if the name of a named
+ * optional parameter begins with an '_' character.
+ */
+ static const CompileTimeErrorCode PRIVATE_OPTIONAL_PARAMETER =
+ const CompileTimeErrorCode('PRIVATE_OPTIONAL_PARAMETER',
+ "Named optional parameters cannot start with an underscore");
+
+ /**
+ * 12.1 Constants: It is a compile-time error if the value of a compile-time
+ * constant expression depends on itself.
+ */
+ static const CompileTimeErrorCode RECURSIVE_COMPILE_TIME_CONSTANT =
+ const CompileTimeErrorCode('RECURSIVE_COMPILE_TIME_CONSTANT',
+ "Compile-time constant expression depends on itself");
+
+ /**
+ * 7.6.1 Generative Constructors: A generative constructor may be redirecting,
+ * in which case its only action is to invoke another generative constructor.
+ *
+ * TODO(scheglov) review this later, there are no explicit "it is a
+ * compile-time error" in specification. But it was added to the co19 and
+ * there is same error for factories.
+ *
+ * https://code.google.com/p/dart/issues/detail?id=954
+ */
+ static const CompileTimeErrorCode RECURSIVE_CONSTRUCTOR_REDIRECT =
+ const CompileTimeErrorCode('RECURSIVE_CONSTRUCTOR_REDIRECT',
+ "Cycle in redirecting generative constructors");
+
+ /**
+ * 7.6.2 Factories: It is a compile-time error if a redirecting factory
+ * constructor redirects to itself, either directly or indirectly via a
+ * sequence of redirections.
+ */
+ static const CompileTimeErrorCode RECURSIVE_FACTORY_REDIRECT =
+ const CompileTimeErrorCode('RECURSIVE_FACTORY_REDIRECT',
+ "Cycle in redirecting factory constructors");
+
+ /**
+ * 7.10 Superinterfaces: It is a compile-time error if the interface of a
+ * class <i>C</i> is a superinterface of itself.
+ *
+ * 8.1 Superinterfaces: It is a compile-time error if an interface is a
+ * superinterface of itself.
+ *
+ * 7.9 Superclasses: It is a compile-time error if a class <i>C</i> is a
+ * superclass of itself.
+ *
+ * Parameters:
+ * 0: the name of the class that implements itself recursively
+ * 1: a string representation of the implements loop
+ */
+ static const CompileTimeErrorCode RECURSIVE_INTERFACE_INHERITANCE =
+ const CompileTimeErrorCode('RECURSIVE_INTERFACE_INHERITANCE',
+ "'{0}' cannot be a superinterface of itself: {1}");
+
+ /**
+ * 7.10 Superinterfaces: It is a compile-time error if the interface of a
+ * class <i>C</i> is a superinterface of itself.
+ *
+ * 8.1 Superinterfaces: It is a compile-time error if an interface is a
+ * superinterface of itself.
+ *
+ * 7.9 Superclasses: It is a compile-time error if a class <i>C</i> is a
+ * superclass of itself.
+ *
+ * Parameters:
+ * 0: the name of the class that implements itself recursively
+ */
+ static const CompileTimeErrorCode
+ RECURSIVE_INTERFACE_INHERITANCE_BASE_CASE_EXTENDS =
+ const CompileTimeErrorCode(
+ 'RECURSIVE_INTERFACE_INHERITANCE_BASE_CASE_EXTENDS',
+ "'{0}' cannot extend itself");
+
+ /**
+ * 7.10 Superinterfaces: It is a compile-time error if the interface of a
+ * class <i>C</i> is a superinterface of itself.
+ *
+ * 8.1 Superinterfaces: It is a compile-time error if an interface is a
+ * superinterface of itself.
+ *
+ * 7.9 Superclasses: It is a compile-time error if a class <i>C</i> is a
+ * superclass of itself.
+ *
+ * Parameters:
+ * 0: the name of the class that implements itself recursively
+ */
+ static const CompileTimeErrorCode
+ RECURSIVE_INTERFACE_INHERITANCE_BASE_CASE_IMPLEMENTS =
+ const CompileTimeErrorCode(
+ 'RECURSIVE_INTERFACE_INHERITANCE_BASE_CASE_IMPLEMENTS',
+ "'{0}' cannot implement itself");
+
+ /**
+ * 7.10 Superinterfaces: It is a compile-time error if the interface of a
+ * class <i>C</i> is a superinterface of itself.
+ *
+ * 8.1 Superinterfaces: It is a compile-time error if an interface is a
+ * superinterface of itself.
+ *
+ * 7.9 Superclasses: It is a compile-time error if a class <i>C</i> is a
+ * superclass of itself.
+ *
+ * Parameters:
+ * 0: the name of the class that implements itself recursively
+ */
+ static const CompileTimeErrorCode
+ RECURSIVE_INTERFACE_INHERITANCE_BASE_CASE_WITH =
+ const CompileTimeErrorCode(
+ 'RECURSIVE_INTERFACE_INHERITANCE_BASE_CASE_WITH',
+ "'{0}' cannot use itself as a mixin");
+
+ /**
+ * 7.6.2 Factories: It is a compile-time error if <i>k</i> is prefixed with
+ * the const modifier but <i>k'</i> is not a constant constructor.
+ */
+ static const CompileTimeErrorCode REDIRECT_TO_MISSING_CONSTRUCTOR =
+ const CompileTimeErrorCode('REDIRECT_TO_MISSING_CONSTRUCTOR',
+ "The constructor '{0}' could not be found in '{1}'");
+
+ /**
+ * 7.6.2 Factories: It is a compile-time error if <i>k</i> is prefixed with
+ * the const modifier but <i>k'</i> is not a constant constructor.
+ */
+ static const CompileTimeErrorCode REDIRECT_TO_NON_CLASS =
+ const CompileTimeErrorCode('REDIRECT_TO_NON_CLASS',
+ "The name '{0}' is not a type and cannot be used in a redirected constructor");
+
+ /**
+ * 7.6.2 Factories: It is a compile-time error if <i>k</i> is prefixed with
+ * the const modifier but <i>k'</i> is not a constant constructor.
+ */
+ static const CompileTimeErrorCode REDIRECT_TO_NON_CONST_CONSTRUCTOR =
+ const CompileTimeErrorCode('REDIRECT_TO_NON_CONST_CONSTRUCTOR',
+ "Constant factory constructor cannot delegate to a non-constant constructor");
+
+ /**
+ * 7.6.1 Generative constructors: A generative constructor may be
+ * <i>redirecting</i>, in which case its only action is to invoke another
+ * generative constructor.
+ */
+ static const CompileTimeErrorCode REDIRECT_GENERATIVE_TO_MISSING_CONSTRUCTOR =
+ const CompileTimeErrorCode('REDIRECT_GENERATIVE_TO_MISSING_CONSTRUCTOR',
+ "The constructor '{0}' could not be found in '{1}'");
+
+ /**
+ * 7.6.1 Generative constructors: A generative constructor may be
+ * <i>redirecting</i>, in which case its only action is to invoke another
+ * generative constructor.
+ */
+ static const CompileTimeErrorCode
+ REDIRECT_GENERATIVE_TO_NON_GENERATIVE_CONSTRUCTOR =
+ const CompileTimeErrorCode(
+ 'REDIRECT_GENERATIVE_TO_NON_GENERATIVE_CONSTRUCTOR',
+ "Generative constructor cannot redirect to a factory constructor");
+
+ /**
+ * 5 Variables: A local variable may only be referenced at a source code
+ * location that is after its initializer, if any, is complete, or a
+ * compile-time error occurs.
+ */
+ static const CompileTimeErrorCode REFERENCED_BEFORE_DECLARATION =
+ const CompileTimeErrorCode('REFERENCED_BEFORE_DECLARATION',
+ "Local variable '{0}' cannot be referenced before it is declared");
+
+ /**
+ * 12.8.1 Rethrow: It is a compile-time error if an expression of the form
+ * <i>rethrow;</i> is not enclosed within a on-catch clause.
+ */
+ static const CompileTimeErrorCode RETHROW_OUTSIDE_CATCH =
+ shared_messages.RETHROW_OUTSIDE_CATCH;
+
+ /**
+ * 13.12 Return: It is a compile-time error if a return statement of the form
+ * <i>return e;</i> appears in a generative constructor.
+ */
+ static const CompileTimeErrorCode RETURN_IN_GENERATIVE_CONSTRUCTOR =
+ shared_messages.RETURN_IN_GENERATIVE_CONSTRUCTOR;
+
+ /**
+ * 13.12 Return: It is a compile-time error if a return statement of the form
+ * <i>return e;</i> appears in a generator function.
+ */
+ static const CompileTimeErrorCode RETURN_IN_GENERATOR =
+ shared_messages.RETURN_IN_GENERATOR;
+
+ /**
+ * 14.1 Imports: It is a compile-time error if a prefix used in a deferred
+ * import is used in another import clause.
+ */
+ static const CompileTimeErrorCode SHARED_DEFERRED_PREFIX =
+ const CompileTimeErrorCode('SHARED_DEFERRED_PREFIX',
+ "The prefix of a deferred import cannot be used in other import directives");
+
+ /**
+ * 12.15.4 Super Invocation: A super method invocation <i>i</i> has the form
+ * <i>super.m(a<sub>1</sub>, …, a<sub>n</sub>, x<sub>n+1</sub>:
+ * a<sub>n+1</sub>, … x<sub>n+k</sub>: a<sub>n+k</sub>)</i>. It is a
+ * compile-time error if a super method invocation occurs in a top-level
+ * function or variable initializer, in an instance variable initializer or
+ * initializer list, in class Object, in a factory constructor, or in a static
+ * method or variable initializer.
+ */
+ static const CompileTimeErrorCode SUPER_IN_INVALID_CONTEXT =
+ const CompileTimeErrorCode(
+ 'SUPER_IN_INVALID_CONTEXT', "Invalid context for 'super' invocation");
+
+ /**
+ * 7.6.1 Generative Constructors: A generative constructor may be redirecting,
+ * in which case its only action is to invoke another generative constructor.
+ */
+ static const CompileTimeErrorCode SUPER_IN_REDIRECTING_CONSTRUCTOR =
+ const CompileTimeErrorCode('SUPER_IN_REDIRECTING_CONSTRUCTOR',
+ "The redirecting constructor cannot have a 'super' initializer");
+
+ /**
+ * 7.6.1 Generative Constructors: Let <i>k</i> be a generative constructor. It
+ * is a compile-time error if a generative constructor of class Object
+ * includes a superinitializer.
+ */
+ static const CompileTimeErrorCode SUPER_INITIALIZER_IN_OBJECT =
+ const CompileTimeErrorCode('SUPER_INITIALIZER_IN_OBJECT', "");
+
+ /**
+ * 12.11 Instance Creation: It is a static type warning if any of the type
+ * arguments to a constructor of a generic type <i>G</i> invoked by a new
+ * expression or a constant object expression are not subtypes of the bounds
+ * of the corresponding formal type parameters of <i>G</i>.
+ *
+ * 12.11.1 New: If T is malformed a dynamic error occurs. In checked mode, if
+ * T is mal-bounded a dynamic error occurs.
+ *
+ * 12.1 Constants: It is a compile-time error if evaluation of a compile-time
+ * constant would raise an exception.
+ *
+ * Parameters:
+ * 0: the name of the type used in the instance creation that should be
+ * limited by the bound as specified in the class declaration
+ * 1: the name of the bounding type
+ *
+ * See [StaticTypeWarningCode.TYPE_ARGUMENT_NOT_MATCHING_BOUNDS].
+ */
+ static const CompileTimeErrorCode TYPE_ARGUMENT_NOT_MATCHING_BOUNDS =
+ const CompileTimeErrorCode(
+ 'TYPE_ARGUMENT_NOT_MATCHING_BOUNDS', "'{0}' does not extend '{1}'");
+
+ /**
+ * 15.3.1 Typedef: Any self reference, either directly, or recursively via
+ * another typedef, is a compile time error.
+ */
+ static const CompileTimeErrorCode TYPE_ALIAS_CANNOT_REFERENCE_ITSELF =
+ const CompileTimeErrorCode('TYPE_ALIAS_CANNOT_REFERENCE_ITSELF',
+ "Type alias cannot reference itself directly or recursively via another typedef");
+
+ /**
+ * 12.11.2 Const: It is a compile-time error if <i>T</i> is not a class
+ * accessible in the current scope, optionally followed by type arguments.
+ */
+ static const CompileTimeErrorCode UNDEFINED_CLASS =
+ const CompileTimeErrorCode('UNDEFINED_CLASS', "Undefined class '{0}'");
+
+ /**
+ * 7.6.1 Generative Constructors: Let <i>C</i> be the class in which the
+ * superinitializer appears and let <i>S</i> be the superclass of <i>C</i>.
+ * Let <i>k</i> be a generative constructor. It is a compile-time error if
+ * class <i>S</i> does not declare a generative constructor named <i>S</i>
+ * (respectively <i>S.id</i>)
+ */
+ static const CompileTimeErrorCode UNDEFINED_CONSTRUCTOR_IN_INITIALIZER =
+ const CompileTimeErrorCode('UNDEFINED_CONSTRUCTOR_IN_INITIALIZER',
+ "The class '{0}' does not have a generative constructor '{1}'");
+
+ /**
+ * 7.6.1 Generative Constructors: Let <i>C</i> be the class in which the
+ * superinitializer appears and let <i>S</i> be the superclass of <i>C</i>.
+ * Let <i>k</i> be a generative constructor. It is a compile-time error if
+ * class <i>S</i> does not declare a generative constructor named <i>S</i>
+ * (respectively <i>S.id</i>)
+ */
+ static const CompileTimeErrorCode
+ UNDEFINED_CONSTRUCTOR_IN_INITIALIZER_DEFAULT = const CompileTimeErrorCode(
+ 'UNDEFINED_CONSTRUCTOR_IN_INITIALIZER_DEFAULT',
+ "The class '{0}' does not have a default generative constructor");
+
+ /**
+ * 12.14.2 Binding Actuals to Formals: Furthermore, each <i>q<sub>i</sub></i>,
+ * <i>1<=i<=l</i>, must have a corresponding named parameter in the set
+ * {<i>p<sub>n+1</sub></i> ... <i>p<sub>n+k</sub></i>} or a static warning
+ * occurs.
+ *
+ * 12.11.2 Const: It is a compile-time error if evaluation of a constant
+ * object results in an uncaught exception being thrown.
+ *
+ * Parameters:
+ * 0: the name of the requested named parameter
+ */
+ static const CompileTimeErrorCode UNDEFINED_NAMED_PARAMETER =
+ const CompileTimeErrorCode('UNDEFINED_NAMED_PARAMETER',
+ "The named parameter '{0}' is not defined");
+
+ /**
+ * 14.2 Exports: It is a compile-time error if the compilation unit found at
+ * the specified URI is not a library declaration.
+ *
+ * 14.1 Imports: It is a compile-time error if the compilation unit found at
+ * the specified URI is not a library declaration.
+ *
+ * 14.3 Parts: It is a compile time error if the contents of the URI are not a
+ * valid part declaration.
+ *
+ * Parameters:
+ * 0: the URI pointing to a non-existent file
+ *
+ * See [INVALID_URI], [URI_HAS_NOT_BEEN_GENERATED].
+ */
+ static const CompileTimeErrorCode URI_DOES_NOT_EXIST =
+ const CompileTimeErrorCode(
+ 'URI_DOES_NOT_EXIST', "Target of URI does not exist: '{0}'");
+
+ /**
+ * Just like [URI_DOES_NOT_EXIST], but used when the URI refers to a file that
+ * is expected to be generated.
+ *
+ * Parameters:
+ * 0: the URI pointing to a non-existent file
+ *
+ * See [INVALID_URI], [URI_DOES_NOT_EXIST].
+ */
+ static const CompileTimeErrorCode URI_HAS_NOT_BEEN_GENERATED =
+ const CompileTimeErrorCode('URI_HAS_NOT_BEEN_GENERATED',
+ "Target of URI has not been generated: '{0}'");
+
+ /**
+ * 14.1 Imports: It is a compile-time error if <i>x</i> is not a compile-time
+ * constant, or if <i>x</i> involves string interpolation.
+ *
+ * 14.3 Parts: It is a compile-time error if <i>s</i> is not a compile-time
+ * constant, or if <i>s</i> involves string interpolation.
+ *
+ * 14.5 URIs: It is a compile-time error if the string literal <i>x</i> that
+ * describes a URI is not a compile-time constant, or if <i>x</i> involves
+ * string interpolation.
+ */
+ static const CompileTimeErrorCode URI_WITH_INTERPOLATION =
+ const CompileTimeErrorCode(
+ 'URI_WITH_INTERPOLATION', "URIs cannot use string interpolation");
+
+ /**
+ * 7.1.1 Operators: It is a compile-time error if the arity of the
+ * user-declared operator []= is not 2. It is a compile time error if the
+ * arity of a user-declared operator with one of the names: <, >, <=,
+ * >=, ==, +, /, ~/, *, %, |, ^, &, <<, >>, [] is not 1. It is
+ * a compile time error if the arity of the user-declared operator - is not 0
+ * or 1. It is a compile time error if the arity of the user-declared operator
+ * ~ is not 0.
+ *
+ * Parameters:
+ * 0: the name of the declared operator
+ * 1: the number of parameters expected
+ * 2: the number of parameters found in the operator declaration
+ */
+ static const CompileTimeErrorCode WRONG_NUMBER_OF_PARAMETERS_FOR_OPERATOR =
+ const CompileTimeErrorCode('WRONG_NUMBER_OF_PARAMETERS_FOR_OPERATOR',
+ "Operator '{0}' should declare exactly {1} parameter(s), but {2} found");
+
+ /**
+ * 7.1.1 Operators: It is a compile time error if the arity of the
+ * user-declared operator - is not 0 or 1.
+ *
+ * Parameters:
+ * 0: the number of parameters found in the operator declaration
+ */
+ static const CompileTimeErrorCode
+ WRONG_NUMBER_OF_PARAMETERS_FOR_OPERATOR_MINUS =
+ const CompileTimeErrorCode(
+ 'WRONG_NUMBER_OF_PARAMETERS_FOR_OPERATOR_MINUS',
+ "Operator '-' should declare 0 or 1 parameter, but {0} found");
+
+ /**
+ * 7.3 Setters: It is a compile-time error if a setter's formal parameter list
+ * does not include exactly one required formal parameter <i>p</i>.
+ */
+ static const CompileTimeErrorCode WRONG_NUMBER_OF_PARAMETERS_FOR_SETTER =
+ const CompileTimeErrorCode('WRONG_NUMBER_OF_PARAMETERS_FOR_SETTER',
+ "Setters should declare exactly one required parameter");
+
+ /**
+ * ?? Yield: It is a compile-time error if a yield statement appears in a
+ * function that is not a generator function.
+ */
+ static const CompileTimeErrorCode YIELD_EACH_IN_NON_GENERATOR =
+ const CompileTimeErrorCode('YIELD_EACH_IN_NON_GENERATOR',
+ "Yield-each statements must be in a generator function (one marked with either 'async*' or 'sync*')");
+
+ /**
+ * ?? Yield: It is a compile-time error if a yield statement appears in a
+ * function that is not a generator function.
+ */
+ static const CompileTimeErrorCode YIELD_IN_NON_GENERATOR =
+ const CompileTimeErrorCode('YIELD_IN_NON_GENERATOR',
+ "Yield statements must be in a generator function (one marked with either 'async*' or 'sync*')");
+
+ /**
+ * Initialize a newly created error code to have the given [name]. The message
+ * associated with the error will be created from the given [message]
+ * template. The correction associated with the error will be created from the
+ * given [correction] template.
+ */
+ const CompileTimeErrorCode(String name, String message, [String correction])
+ : super(name, message, correction);
+
+ @override
+ ErrorSeverity get errorSeverity => ErrorType.COMPILE_TIME_ERROR.severity;
+
+ @override
+ ErrorType get type => ErrorType.COMPILE_TIME_ERROR;
+}
+
+/**
+ * The hints and coding recommendations for best practices which are not
+ * mentioned in the Dart Language Specification.
+ */
+class HintCode extends ErrorCode {
+ /**
+ * This hint is generated anywhere where the
+ * [StaticWarningCode.ARGUMENT_TYPE_NOT_ASSIGNABLE] would have been generated,
+ * if we used propagated information for the warnings.
+ *
+ * Parameters:
+ * 0: the name of the actual argument type
+ * 1: the name of the expected type
+ */
+ static const HintCode ARGUMENT_TYPE_NOT_ASSIGNABLE =
+ shared_messages.ARGUMENT_TYPE_NOT_ASSIGNABLE_HINT;
+
+ /**
+ * When the target expression uses '?.' operator, it can be `null`, so all the
+ * subsequent invocations should also use '?.' operator.
+ */
+ static const HintCode CAN_BE_NULL_AFTER_NULL_AWARE = const HintCode(
+ 'CAN_BE_NULL_AFTER_NULL_AWARE',
+ "The expression uses '?.', so can be 'null'",
+ "Replace the '.' with a '?.' in the invocation");
+
+ /**
+ * Dead code is code that is never reached, this can happen for instance if a
+ * statement follows a return statement.
+ */
+ static const HintCode DEAD_CODE = const HintCode('DEAD_CODE', "Dead code");
+
+ /**
+ * Dead code is code that is never reached. This case covers cases where the
+ * user has catch clauses after `catch (e)` or `on Object catch (e)`.
+ */
+ static const HintCode DEAD_CODE_CATCH_FOLLOWING_CATCH = const HintCode(
+ 'DEAD_CODE_CATCH_FOLLOWING_CATCH',
+ "Dead code, catch clauses after a 'catch (e)' or an 'on Object catch (e)' are never reached");
+
+ /**
+ * Dead code is code that is never reached. This case covers cases where the
+ * user has an on-catch clause such as `on A catch (e)`, where a supertype of
+ * `A` was already caught.
+ *
+ * Parameters:
+ * 0: name of the subtype
+ * 1: name of the supertype
+ */
+ static const HintCode DEAD_CODE_ON_CATCH_SUBTYPE = const HintCode(
+ 'DEAD_CODE_ON_CATCH_SUBTYPE',
+ "Dead code, this on-catch block will never be executed since '{0}' is a subtype of '{1}'");
+
+ /**
+ * Deprecated members should not be invoked or used.
+ *
+ * Parameters:
+ * 0: the name of the member
+ */
+ static const HintCode DEPRECATED_MEMBER_USE =
+ const HintCode('DEPRECATED_MEMBER_USE', "'{0}' is deprecated");
+
+ /**
+ * Duplicate imports.
+ */
+ static const HintCode DUPLICATE_IMPORT =
+ const HintCode('DUPLICATE_IMPORT', "Duplicate import");
+
+ /**
+ * Hint to use the ~/ operator.
+ */
+ static const HintCode DIVISION_OPTIMIZATION = const HintCode(
+ 'DIVISION_OPTIMIZATION',
+ "The operator x ~/ y is more efficient than (x / y).toInt()");
+
+ /**
+ * Hint for the `x is double` type checks.
+ */
+ static const HintCode IS_DOUBLE = const HintCode('IS_DOUBLE',
+ "When compiled to JS, this test might return true when the left hand side is an int");
+
+ /**
+ * Hint for the `x is int` type checks.
+ */
+ static const HintCode IS_INT = const HintCode('IS_INT',
+ "When compiled to JS, this test might return true when the left hand side is a double");
+
+ /**
+ * Hint for the `x is! double` type checks.
+ */
+ static const HintCode IS_NOT_DOUBLE = const HintCode('IS_NOT_DOUBLE',
+ "When compiled to JS, this test might return false when the left hand side is an int");
+
+ /**
+ * Hint for the `x is! int` type checks.
+ */
+ static const HintCode IS_NOT_INT = const HintCode('IS_NOT_INT',
+ "When compiled to JS, this test might return false when the left hand side is a double");
+
+ /**
+ * Deferred libraries shouldn't define a top level function 'loadLibrary'.
+ */
+ static const HintCode IMPORT_DEFERRED_LIBRARY_WITH_LOAD_FUNCTION = const HintCode(
+ 'IMPORT_DEFERRED_LIBRARY_WITH_LOAD_FUNCTION',
+ "The library '{0}' defines a top-level function named 'loadLibrary' which is hidden by deferring this library");
+
+ /**
+ * This hint is generated anywhere where the
+ * [StaticTypeWarningCode.INVALID_ASSIGNMENT] would have been generated, if we
+ * used propagated information for the warnings.
+ *
+ * Parameters:
+ * 0: the name of the right hand side type
+ * 1: the name of the left hand side type
+ */
+ static const HintCode INVALID_ASSIGNMENT = const HintCode(
+ 'INVALID_ASSIGNMENT',
+ "A value of type '{0}' cannot be assigned to a variable of type '{1}'");
+
+ /**
+ * This hint is generated anywhere a @factory annotation is associated with
+ * anything other than a method.
+ */
+ static const HintCode INVALID_FACTORY_ANNOTATION = const HintCode(
+ 'INVALID_FACTORY_ANNOTATION',
+ "Only methods can be annotated as factories.");
+
+ /**
+ * This hint is generated anywhere a @factory annotation is associated with
+ * a method that does not declare a return type.
+ */
+ static const HintCode INVALID_FACTORY_METHOD_DECL = const HintCode(
+ 'INVALID_FACTORY_METHOD_DECL',
+ "Factory method '{0}' must have a return type.");
+
+ /**
+ * This hint is generated anywhere a @factory annotation is associated with
+ * a non-abstract method that can return anything other than a newly allocated
+ * object.
+ *
+ * Parameters:
+ * 0: the name of the method
+ */
+ static const HintCode INVALID_FACTORY_METHOD_IMPL = const HintCode(
+ 'INVALID_FACTORY_METHOD_IMPL',
+ "Factory method '{0}' does not return a newly allocated object.");
+
+ /**
+ * This hint is generated anywhere where a member annotated with `@protected`
+ * is used outside an instance member of a subclass.
+ *
+ * Parameters:
+ * 0: the name of the member
+ * 1: the name of the defining class
+ */
+ static const HintCode INVALID_USE_OF_PROTECTED_MEMBER = const HintCode(
+ 'INVALID_USE_OF_PROTECTED_MEMBER',
+ "The member '{0}' can only be used within instance members of subclasses of '{1}'");
+
+ /**
+ * Generate a hint for a constructor, function or method invocation where a
+ * required parameter is missing.
+ *
+ * Parameters:
+ * 0: the name of the parameter
+ */
+ static const HintCode MISSING_REQUIRED_PARAM = const HintCode(
+ 'MISSING_REQUIRED_PARAM', "The parameter '{0}' is required.");
+
+ /**
+ * Generate a hint for a constructor, function or method invocation where a
+ * required parameter is missing.
+ *
+ * Parameters:
+ * 0: the name of the parameter
+ * 1: message details
+ */
+ static const HintCode MISSING_REQUIRED_PARAM_WITH_DETAILS = const HintCode(
+ 'MISSING_REQUIRED_PARAM_WITH_DETAILS',
+ "The parameter '{0}' is required. {1}");
+
+ /**
+ * Generate a hint for an element that is annotated with `@JS(...)` whose
+ * library declaration is not similarly annotated.
+ */
+ static const HintCode MISSING_JS_LIB_ANNOTATION = const HintCode(
+ 'MISSING_JS_LIB_ANNOTATION',
+ "The @JS() annotation can only be used if it is also declared on the library directive.");
+
+ /**
+ * Generate a hint for methods or functions that have a return type, but do
+ * not have a non-void return statement on all branches. At the end of methods
+ * or functions with no return, Dart implicitly returns `null`, avoiding these
+ * implicit returns is considered a best practice.
+ *
+ * Parameters:
+ * 0: the name of the declared return type
+ */
+ static const HintCode MISSING_RETURN = const HintCode(
+ 'MISSING_RETURN',
+ "This function declares a return type of '{0}', but does not end with a return statement",
+ "Either add a return statement or change the return type to 'void'");
+
+ /**
+ * Generate a hint for methods that override methods annotated `@mustCallSuper`
+ * that do not invoke the overridden super method.
+ *
+ * Parameters:
+ * 0: the name of the class declaring the overriden method
+ */
+ static const HintCode MUST_CALL_SUPER = const HintCode(
+ 'MUST_CALL_SUPER',
+ "This method overrides a method annotated as @mustCall super in '{0}', "
+ "but does invoke the overriden method");
+
+ /**
+ * A condition in a control flow statement could evaluate to `null` because it
+ * uses the null-aware '?.' operator.
+ */
+ static const HintCode NULL_AWARE_IN_CONDITION = const HintCode(
+ 'NULL_AWARE_IN_CONDITION',
+ "The value of the '?.' operator can be 'null', which is not appropriate in a condition",
+ "Replace the '?.' with a '.', testing the left-hand side for null if necessary");
+
+ /**
+ * A getter with the override annotation does not override an existing getter.
+ */
+ static const HintCode OVERRIDE_ON_NON_OVERRIDING_GETTER = const HintCode(
+ 'OVERRIDE_ON_NON_OVERRIDING_GETTER',
+ "Getter does not override an inherited getter");
+
+ /**
+ * A field with the override annotation does not override a getter or setter.
+ */
+ static const HintCode OVERRIDE_ON_NON_OVERRIDING_FIELD = const HintCode(
+ 'OVERRIDE_ON_NON_OVERRIDING_FIELD',
+ "Field does not override an inherited getter or setter");
+
+ /**
+ * A method with the override annotation does not override an existing method.
+ */
+ static const HintCode OVERRIDE_ON_NON_OVERRIDING_METHOD = const HintCode(
+ 'OVERRIDE_ON_NON_OVERRIDING_METHOD',
+ "Method does not override an inherited method");
+
+ /**
+ * A setter with the override annotation does not override an existing setter.
+ */
+ static const HintCode OVERRIDE_ON_NON_OVERRIDING_SETTER = const HintCode(
+ 'OVERRIDE_ON_NON_OVERRIDING_SETTER',
+ "Setter does not override an inherited setter");
+
+ /**
+ * Hint for classes that override equals, but not hashCode.
+ *
+ * Parameters:
+ * 0: the name of the current class
+ */
+ static const HintCode OVERRIDE_EQUALS_BUT_NOT_HASH_CODE = const HintCode(
+ 'OVERRIDE_EQUALS_BUT_NOT_HASH_CODE',
+ "The class '{0}' overrides 'operator==', but not 'get hashCode'");
+
+ /**
+ * Type checks of the type `x is! Null` should be done with `x != null`.
+ */
+ static const HintCode TYPE_CHECK_IS_NOT_NULL = const HintCode(
+ 'TYPE_CHECK_IS_NOT_NULL',
+ "Tests for non-null should be done with '!= null'");
+
+ /**
+ * Type checks of the type `x is Null` should be done with `x == null`.
+ */
+ static const HintCode TYPE_CHECK_IS_NULL = const HintCode(
+ 'TYPE_CHECK_IS_NULL', "Tests for null should be done with '== null'");
+
+ /**
+ * This hint is generated anywhere where the
+ * [StaticTypeWarningCode.UNDEFINED_GETTER] or
+ * [StaticWarningCode.UNDEFINED_GETTER] would have been generated, if we used
+ * propagated information for the warnings.
+ *
+ * Parameters:
+ * 0: the name of the getter
+ * 1: the name of the enclosing type where the getter is being looked for
+ */
+ static const HintCode UNDEFINED_GETTER =
+ shared_messages.UNDEFINED_GETTER_HINT;
+
+ /**
+ * An undefined name hidden in an import or export directive.
+ */
+ static const HintCode UNDEFINED_HIDDEN_NAME = const HintCode(
+ 'UNDEFINED_HIDDEN_NAME',
+ "The library '{0}' doesn't export a member with the hidden name '{1}'");
+
+ /**
+ * This hint is generated anywhere where the
+ * [StaticTypeWarningCode.UNDEFINED_METHOD] would have been generated, if we
+ * used propagated information for the warnings.
+ *
+ * Parameters:
+ * 0: the name of the method that is undefined
+ * 1: the resolved type name that the method lookup is happening on
+ */
+ static const HintCode UNDEFINED_METHOD =
+ shared_messages.UNDEFINED_METHOD_HINT;
+
+ /**
+ * This hint is generated anywhere where the
+ * [StaticTypeWarningCode.UNDEFINED_OPERATOR] would have been generated, if we
+ * used propagated information for the warnings.
+ *
+ * Parameters:
+ * 0: the name of the operator
+ * 1: the name of the enclosing type where the operator is being looked for
+ */
+ static const HintCode UNDEFINED_OPERATOR =
+ shared_messages.UNDEFINED_OPERATOR_HINT;
+
+ /**
+ * This hint is generated anywhere where the
+ * [StaticTypeWarningCode.UNDEFINED_SETTER] or
+ * [StaticWarningCode.UNDEFINED_SETTER] would have been generated, if we used
+ * propagated information for the warnings.
+ *
+ * Parameters:
+ * 0: the name of the setter
+ * 1: the name of the enclosing type where the setter is being looked for
+ */
+ static const HintCode UNDEFINED_SETTER =
+ shared_messages.UNDEFINED_SETTER_HINT;
+
+ /**
+ * An undefined name shown in an import or export directive.
+ */
+ static const HintCode UNDEFINED_SHOWN_NAME = const HintCode(
+ 'UNDEFINED_SHOWN_NAME',
+ "The library '{0}' doesn't export a member with the shown name '{1}'");
+
+ /**
+ * Unnecessary cast.
+ */
+ static const HintCode UNNECESSARY_CAST =
+ const HintCode('UNNECESSARY_CAST', "Unnecessary cast");
+
+ /**
+ * Unnecessary `noSuchMethod` declaration.
+ */
+ static const HintCode UNNECESSARY_NO_SUCH_METHOD = const HintCode(
+ 'UNNECESSARY_NO_SUCH_METHOD', "Unnecessary 'noSuchMethod' declaration");
+
+ /**
+ * Unnecessary type checks, the result is always true.
+ */
+ static const HintCode UNNECESSARY_TYPE_CHECK_FALSE = const HintCode(
+ 'UNNECESSARY_TYPE_CHECK_FALSE',
+ "Unnecessary type check, the result is always false");
+
+ /**
+ * Unnecessary type checks, the result is always false.
+ */
+ static const HintCode UNNECESSARY_TYPE_CHECK_TRUE = const HintCode(
+ 'UNNECESSARY_TYPE_CHECK_TRUE',
+ "Unnecessary type check, the result is always true");
+
+ /**
+ * See [Modifier.IS_USED_IN_LIBRARY].
+ */
+ static const HintCode UNUSED_ELEMENT =
+ const HintCode('UNUSED_ELEMENT', "The {0} '{1}' is not used");
+
+ /**
+ * Unused fields are fields which are never read.
+ */
+ static const HintCode UNUSED_FIELD = const HintCode(
+ 'UNUSED_FIELD', "The value of the field '{0}' is not used");
+
+ /**
+ * Unused imports are imports which are never used.
+ */
+ static const HintCode UNUSED_IMPORT =
+ const HintCode('UNUSED_IMPORT', "Unused import");
+
+ /**
+ * Unused catch exception variables.
+ */
+ static const HintCode UNUSED_CATCH_CLAUSE = const HintCode(
+ 'UNUSED_CATCH_CLAUSE',
+ "The exception variable '{0}' is not used, so the 'catch' clause can be removed");
+
+ /**
+ * Unused catch stack trace variables.
+ */
+ static const HintCode UNUSED_CATCH_STACK = const HintCode(
+ 'UNUSED_CATCH_STACK',
+ "The stack trace variable '{0}' is not used and can be removed");
+
+ /**
+ * Unused local variables are local variables which are never read.
+ */
+ static const HintCode UNUSED_LOCAL_VARIABLE = const HintCode(
+ 'UNUSED_LOCAL_VARIABLE',
+ "The value of the local variable '{0}' is not used");
+
+ /**
+ * Unused shown names are names shown on imports which are never used.
+ */
+ static const HintCode UNUSED_SHOWN_NAME = const HintCode(
+ 'UNUSED_SHOWN_NAME', "The name {0} is shown, but not used.");
+
+ /**
+ * Hint for cases where the source expects a method or function to return a
+ * non-void result, but the method or function signature returns void.
+ *
+ * Parameters:
+ * 0: the name of the method or function that returns void
+ */
+ static const HintCode USE_OF_VOID_RESULT = const HintCode(
+ 'USE_OF_VOID_RESULT',
+ "The result of '{0}' is being used, even though it is declared to be 'void'");
+
+ /**
+ * It is a bad practice for a source file in a package "lib" directory
+ * hierarchy to traverse outside that directory hierarchy. For example, a
+ * source file in the "lib" directory should not contain a directive such as
+ * `import '../web/some.dart'` which references a file outside the lib
+ * directory.
+ */
+ static const HintCode FILE_IMPORT_INSIDE_LIB_REFERENCES_FILE_OUTSIDE =
+ const HintCode('FILE_IMPORT_INSIDE_LIB_REFERENCES_FILE_OUTSIDE',
+ "A file in the 'lib' directory hierarchy should not reference a file outside that hierarchy");
+
+ /**
+ * It is a bad practice for a source file ouside a package "lib" directory
+ * hierarchy to traverse into that directory hierarchy. For example, a source
+ * file in the "web" directory should not contain a directive such as
+ * `import '../lib/some.dart'` which references a file inside the lib
+ * directory.
+ */
+ static const HintCode FILE_IMPORT_OUTSIDE_LIB_REFERENCES_FILE_INSIDE =
+ const HintCode('FILE_IMPORT_OUTSIDE_LIB_REFERENCES_FILE_INSIDE',
+ "A file outside the 'lib' directory hierarchy should not reference a file inside that hierarchy. Use a package: reference instead.");
+
+ /**
+ * It is a bad practice for a package import to reference anything outside the
+ * given package, or more generally, it is bad practice for a package import
+ * to contain a "..". For example, a source file should not contain a
+ * directive such as `import 'package:foo/../some.dart'`.
+ */
+ static const HintCode PACKAGE_IMPORT_CONTAINS_DOT_DOT = const HintCode(
+ 'PACKAGE_IMPORT_CONTAINS_DOT_DOT',
+ "A package import should not contain '..'");
+
+ /**
+ * Initialize a newly created error code to have the given [name]. The message
+ * associated with the error will be created from the given [message]
+ * template. The correction associated with the error will be created from the
+ * given [correction] template.
+ */
+ const HintCode(String name, String message, [String correction])
+ : super(name, message, correction);
+
+ @override
+ ErrorSeverity get errorSeverity => ErrorType.HINT.severity;
+
+ @override
+ ErrorType get type => ErrorType.HINT;
+}
+
+/**
+ * The error codes used for errors in HTML files. The convention for this
+ * class is for the name of the error code to indicate the problem that caused
+ * the error to be generated and for the error message to explain what is wrong
+ * and, when appropriate, how the problem can be corrected.
+ */
+class HtmlErrorCode extends ErrorCode {
+ /**
+ * An error code indicating that there is a syntactic error in the file.
+ *
+ * Parameters:
+ * 0: the error message from the parse error
+ */
+ static const HtmlErrorCode PARSE_ERROR =
+ const HtmlErrorCode('PARSE_ERROR', '{0}');
+
+ /**
+ * Initialize a newly created error code to have the given [name]. The message
+ * associated with the error will be created from the given [message]
+ * template. The correction associated with the error will be created from the
+ * given [correction] template.
+ */
+ const HtmlErrorCode(String name, String message, [String correction])
+ : super(name, message, correction);
+
+ @override
+ ErrorSeverity get errorSeverity => ErrorSeverity.ERROR;
+
+ @override
+ ErrorType get type => ErrorType.COMPILE_TIME_ERROR;
+}
+
+/**
+ * The error codes used for warnings in HTML files. The convention for this
+ * class is for the name of the error code to indicate the problem that caused
+ * the error to be generated and for the error message to explain what is wrong
+ * and, when appropriate, how the problem can be corrected.
+ */
+class HtmlWarningCode extends ErrorCode {
+ /**
+ * An error code indicating that the value of the 'src' attribute of a Dart
+ * script tag is not a valid URI.
+ *
+ * Parameters:
+ * 0: the URI that is invalid
+ */
+ static const HtmlWarningCode INVALID_URI =
+ const HtmlWarningCode('INVALID_URI', "Invalid URI syntax: '{0}'");
+
+ /**
+ * An error code indicating that the value of the 'src' attribute of a Dart
+ * script tag references a file that does not exist.
+ *
+ * Parameters:
+ * 0: the URI pointing to a non-existent file
+ */
+ static const HtmlWarningCode URI_DOES_NOT_EXIST = const HtmlWarningCode(
+ 'URI_DOES_NOT_EXIST', "Target of URI does not exist: '{0}'");
+
+ /**
+ * Initialize a newly created error code to have the given [name]. The message
+ * associated with the error will be created from the given [message]
+ * template. The correction associated with the error will be created from the
+ * given [correction] template.
+ */
+ const HtmlWarningCode(String name, String message, [String correction])
+ : super(name, message, correction);
+
+ @override
+ ErrorSeverity get errorSeverity => ErrorSeverity.WARNING;
+
+ @override
+ ErrorType get type => ErrorType.STATIC_WARNING;
+}
+
+/**
+ * Defines style and best practice recommendations.
+ *
+ * Unlike [HintCode]s, which are akin to traditional static warnings from a
+ * compiler, lint recommendations focus on matters of style and practices that
+ * might aggregated to define a project's style guide.
+ */
+class LintCode extends ErrorCode {
+ const LintCode(String name, String message, [String correction])
+ : super(name, message, correction);
+
+ @override
+ ErrorSeverity get errorSeverity => ErrorSeverity.INFO;
+
+ @override
+ ErrorType get type => ErrorType.LINT;
+}
+
+/**
+ * The error codes used for static type warnings. The convention for this class
+ * is for the name of the error code to indicate the problem that caused the
+ * error to be generated and for the error message to explain what is wrong and,
+ * when appropriate, how the problem can be corrected.
+ */
+class StaticTypeWarningCode extends ErrorCode {
+ /**
+ * 12.7 Lists: A fresh instance (7.6.1) <i>a</i>, of size <i>n</i>, whose
+ * class implements the built-in class <i>List<E></i> is allocated.
+ *
+ * Parameters:
+ * 0: the number of provided type arguments
+ */
+ static const StaticTypeWarningCode EXPECTED_ONE_LIST_TYPE_ARGUMENTS =
+ const StaticTypeWarningCode('EXPECTED_ONE_LIST_TYPE_ARGUMENTS',
+ "List literal requires exactly one type arguments or none, but {0} found");
+
+ /**
+ * 12.8 Maps: A fresh instance (7.6.1) <i>m</i>, of size <i>n</i>, whose class
+ * implements the built-in class <i>Map<K, V></i> is allocated.
+ *
+ * Parameters:
+ * 0: the number of provided type arguments
+ */
+ static const StaticTypeWarningCode EXPECTED_TWO_MAP_TYPE_ARGUMENTS =
+ const StaticTypeWarningCode('EXPECTED_TWO_MAP_TYPE_ARGUMENTS',
+ "Map literal requires exactly two type arguments or none, but {0} found");
+
+ /**
+ * 9 Functions: It is a static warning if the declared return type of a
+ * function marked async* may not be assigned to Stream.
+ */
+ static const StaticTypeWarningCode ILLEGAL_ASYNC_GENERATOR_RETURN_TYPE =
+ const StaticTypeWarningCode('ILLEGAL_ASYNC_GENERATOR_RETURN_TYPE',
+ "Functions marked 'async*' must have a return type assignable to 'Stream'");
+
+ /**
+ * 9 Functions: It is a static warning if the declared return type of a
+ * function marked async may not be assigned to Future.
+ */
+ static const StaticTypeWarningCode ILLEGAL_ASYNC_RETURN_TYPE =
+ const StaticTypeWarningCode('ILLEGAL_ASYNC_RETURN_TYPE',
+ "Functions marked 'async' must have a return type assignable to 'Future'");
+
+ /**
+ * 9 Functions: It is a static warning if the declared return type of a
+ * function marked sync* may not be assigned to Iterable.
+ */
+ static const StaticTypeWarningCode ILLEGAL_SYNC_GENERATOR_RETURN_TYPE =
+ const StaticTypeWarningCode('ILLEGAL_SYNC_GENERATOR_RETURN_TYPE',
+ "Functions marked 'sync*' must have a return type assignable to 'Iterable'");
+
+ /**
+ * 12.18 Assignment: Let <i>T</i> be the static type of <i>e<sub>1</sub></i>.
+ * It is a static type warning if <i>T</i> does not have an accessible
+ * instance setter named <i>v=</i>.
+ *
+ * See [UNDEFINED_SETTER].
+ */
+ static const StaticTypeWarningCode INACCESSIBLE_SETTER =
+ const StaticTypeWarningCode('INACCESSIBLE_SETTER', "");
+
+ /**
+ * 8.1.1 Inheritance and Overriding: However, if the above rules would cause
+ * multiple members <i>m<sub>1</sub>, …, m<sub>k</sub></i> with the
+ * same name <i>n</i> that would be inherited (because identically named
+ * members existed in several superinterfaces) then at most one member is
+ * inherited.
+ *
+ * If the static types <i>T<sub>1</sub>, …, T<sub>k</sub></i> of the
+ * members <i>m<sub>1</sub>, …, m<sub>k</sub></i> are not identical,
+ * then there must be a member <i>m<sub>x</sub></i> such that <i>T<sub>x</sub>
+ * <: T<sub>i</sub>, 1 <= x <= k</i> for all <i>i, 1 <= i <=
+ * k</i>, or a static type warning occurs. The member that is inherited is
+ * <i>m<sub>x</sub></i>, if it exists; otherwise:
+ * * Let <i>numberOfPositionals</i>(<i>f</i>) denote the number of positional
+ * parameters of a function <i>f</i>, and let
+ * <i>numberOfRequiredParams</i>(<i>f</i>) denote the number of required
+ * parameters of a function <i>f</i>. Furthermore, let <i>s</i> denote the
+ * set of all named parameters of the <i>m<sub>1</sub>, …,
+ * m<sub>k</sub></i>. Then let
+ * * <i>h = max(numberOfPositionals(m<sub>i</sub>)),</i>
+ * * <i>r = min(numberOfRequiredParams(m<sub>i</sub>)), for all <i>i</i>, 1 <=
+ * i <= k.</i> If <i>r <= h</i> then <i>I</i> has a method named <i>n</i>,
+ * with <i>r</i> required parameters of type <b>dynamic</b>, <i>h</i>
+ * positional parameters of type <b>dynamic</b>, named parameters <i>s</i>
+ * of type <b>dynamic</b> and return type <b>dynamic</b>.
+ * * Otherwise none of the members <i>m<sub>1</sub>, …,
+ * m<sub>k</sub></i> is inherited.
+ */
+ static const StaticTypeWarningCode INCONSISTENT_METHOD_INHERITANCE =
+ const StaticTypeWarningCode('INCONSISTENT_METHOD_INHERITANCE',
+ "'{0}' is inherited by at least two interfaces inconsistently, from {1}");
+
+ /**
+ * 12.15.1 Ordinary Invocation: It is a static type warning if <i>T</i> does
+ * not have an accessible (3.2) instance member named <i>m</i>.
+ *
+ * Parameters:
+ * 0: the name of the static member
+ *
+ * See [UNQUALIFIED_REFERENCE_TO_NON_LOCAL_STATIC_MEMBER].
+ */
+ static const StaticTypeWarningCode INSTANCE_ACCESS_TO_STATIC_MEMBER =
+ const StaticTypeWarningCode('INSTANCE_ACCESS_TO_STATIC_MEMBER',
+ "Static member '{0}' cannot be accessed using instance access");
+
+ /**
+ * 12.18 Assignment: It is a static type warning if the static type of
+ * <i>e</i> may not be assigned to the static type of <i>v</i>. The static
+ * type of the expression <i>v = e</i> is the static type of <i>e</i>.
+ *
+ * 12.18 Assignment: It is a static type warning if the static type of
+ * <i>e</i> may not be assigned to the static type of <i>C.v</i>. The static
+ * type of the expression <i>C.v = e</i> is the static type of <i>e</i>.
+ *
+ * 12.18 Assignment: Let <i>T</i> be the static type of <i>e<sub>1</sub></i>.
+ * It is a static type warning if the static type of <i>e<sub>2</sub></i> may
+ * not be assigned to <i>T</i>.
+ *
+ * Parameters:
+ * 0: the name of the right hand side type
+ * 1: the name of the left hand side type
+ */
+ static const StaticTypeWarningCode INVALID_ASSIGNMENT =
+ const StaticTypeWarningCode('INVALID_ASSIGNMENT',
+ "A value of type '{0}' cannot be assigned to a variable of type '{1}'");
+
+ /**
+ * 12.15.1 Ordinary Invocation: An ordinary method invocation <i>i</i> has the
+ * form <i>o.m(a<sub>1</sub>, …, a<sub>n</sub>, x<sub>n+1</sub>:
+ * a<sub>n+1</sub>, … x<sub>n+k</sub>: a<sub>n+k</sub>)</i>.
+ *
+ * Let <i>T</i> be the static type of <i>o</i>. It is a static type warning if
+ * <i>T</i> does not have an accessible instance member named <i>m</i>. If
+ * <i>T.m</i> exists, it is a static warning if the type <i>F</i> of
+ * <i>T.m</i> may not be assigned to a function type. If <i>T.m</i> does not
+ * exist, or if <i>F</i> is not a function type, the static type of <i>i</i>
+ * is dynamic.
+ *
+ * 12.15.3 Static Invocation: It is a static type warning if the type <i>F</i>
+ * of <i>C.m</i> may not be assigned to a function type.
+ *
+ * 12.15.4 Super Invocation: A super method invocation <i>i</i> has the form
+ * <i>super.m(a<sub>1</sub>, …, a<sub>n</sub>, x<sub>n+1</sub>:
+ * a<sub>n+1</sub>, … x<sub>n+k</sub>: a<sub>n+k</sub>)</i>. If
+ * <i>S.m</i> exists, it is a static warning if the type <i>F</i> of
+ * <i>S.m</i> may not be assigned to a function type.
+ *
+ * Parameters:
+ * 0: the name of the identifier that is not a function type
+ */
+ static const StaticTypeWarningCode INVOCATION_OF_NON_FUNCTION =
+ const StaticTypeWarningCode(
+ 'INVOCATION_OF_NON_FUNCTION', "'{0}' is not a method");
+
+ /**
+ * 12.14.4 Function Expression Invocation: A function expression invocation
+ * <i>i</i> has the form <i>e<sub>f</sub>(a<sub>1</sub>, …,
+ * a<sub>n</sub>, x<sub>n+1</sub>: a<sub>n+1</sub>, …, x<sub>n+k</sub>:
+ * a<sub>n+k</sub>)</i>, where <i>e<sub>f</sub></i> is an expression.
+ *
+ * It is a static type warning if the static type <i>F</i> of
+ * <i>e<sub>f</sub></i> may not be assigned to a function type.
+ */
+ static const StaticTypeWarningCode INVOCATION_OF_NON_FUNCTION_EXPRESSION =
+ const StaticTypeWarningCode('INVOCATION_OF_NON_FUNCTION_EXPRESSION',
+ "Cannot invoke a non-function");
+
+ /**
+ * 12.20 Conditional: It is a static type warning if the type of
+ * <i>e<sub>1</sub></i> may not be assigned to bool.
+ *
+ * 13.5 If: It is a static type warning if the type of the expression <i>b</i>
+ * may not be assigned to bool.
+ *
+ * 13.7 While: It is a static type warning if the type of <i>e</i> may not be
+ * assigned to bool.
+ *
+ * 13.8 Do: It is a static type warning if the type of <i>e</i> cannot be
+ * assigned to bool.
+ */
+ static const StaticTypeWarningCode NON_BOOL_CONDITION =
+ const StaticTypeWarningCode(
+ 'NON_BOOL_CONDITION', "Conditions must have a static type of 'bool'");
+
+ /**
+ * 13.15 Assert: It is a static type warning if the type of <i>e</i> may not
+ * be assigned to either bool or () → bool
+ */
+ static const StaticTypeWarningCode NON_BOOL_EXPRESSION =
+ const StaticTypeWarningCode('NON_BOOL_EXPRESSION',
+ "Assertions must be on either a 'bool' or '() -> bool'");
+
+ /**
+ * 12.28 Unary Expressions: The expression !<i>e</i> is equivalent to the
+ * expression <i>e</i>?<b>false<b> : <b>true</b>.
+ *
+ * 12.20 Conditional: It is a static type warning if the type of
+ * <i>e<sub>1</sub></i> may not be assigned to bool.
+ */
+ static const StaticTypeWarningCode NON_BOOL_NEGATION_EXPRESSION =
+ const StaticTypeWarningCode('NON_BOOL_NEGATION_EXPRESSION',
+ "Negation argument must have a static type of 'bool'");
+
+ /**
+ * 12.21 Logical Boolean Expressions: It is a static type warning if the
+ * static types of both of <i>e<sub>1</sub></i> and <i>e<sub>2</sub></i> may
+ * not be assigned to bool.
+ *
+ * Parameters:
+ * 0: the lexeme of the logical operator
+ */
+ static const StaticTypeWarningCode NON_BOOL_OPERAND =
+ const StaticTypeWarningCode('NON_BOOL_OPERAND',
+ "The operands of the '{0}' operator must be assignable to 'bool'");
+
+ static const StaticTypeWarningCode NON_NULLABLE_FIELD_NOT_INITIALIZED =
+ const StaticTypeWarningCode('NON_NULLABLE_FIELD_NOT_INITIALIZED',
+ "Variable '{0}' of non-nullable type '{1}' must be initialized");
+
+ /**
+ * 15.8 Parameterized Types: It is a static type warning if <i>A<sub>i</sub>,
+ * 1 <= i <= n</i> does not denote a type in the enclosing lexical scope.
+ */
+ static const StaticTypeWarningCode NON_TYPE_AS_TYPE_ARGUMENT =
+ const StaticTypeWarningCode('NON_TYPE_AS_TYPE_ARGUMENT',
+ "The name '{0}' is not a type and cannot be used as a parameterized type");
+
+ /**
+ * 13.11 Return: It is a static type warning if the type of <i>e</i> may not
+ * be assigned to the declared return type of the immediately enclosing
+ * function.
+ *
+ * Parameters:
+ * 0: the return type as declared in the return statement
+ * 1: the expected return type as defined by the method
+ * 2: the name of the method
+ */
+ static const StaticTypeWarningCode RETURN_OF_INVALID_TYPE =
+ shared_messages.RETURN_OF_INVALID_TYPE;
+
+ /**
+ * 12.11 Instance Creation: It is a static type warning if any of the type
+ * arguments to a constructor of a generic type <i>G</i> invoked by a new
+ * expression or a constant object expression are not subtypes of the bounds
+ * of the corresponding formal type parameters of <i>G</i>.
+ *
+ * 15.8 Parameterized Types: If <i>S</i> is the static type of a member
+ * <i>m</i> of <i>G</i>, then the static type of the member <i>m</i> of
+ * <i>G<A<sub>1</sub>, …, A<sub>n</sub>></i> is <i>[A<sub>1</sub>,
+ * …, A<sub>n</sub>/T<sub>1</sub>, …, T<sub>n</sub>]S</i> where
+ * <i>T<sub>1</sub>, …, T<sub>n</sub></i> are the formal type
+ * parameters of <i>G</i>. Let <i>B<sub>i</sub></i> be the bounds of
+ * <i>T<sub>i</sub>, 1 <= i <= n</i>. It is a static type warning if
+ * <i>A<sub>i</sub></i> is not a subtype of <i>[A<sub>1</sub>, …,
+ * A<sub>n</sub>/T<sub>1</sub>, …, T<sub>n</sub>]B<sub>i</sub>, 1 <=
+ * i <= n</i>.
+ *
+ * 7.6.2 Factories: It is a static type warning if any of the type arguments
+ * to <i>k'</i> are not subtypes of the bounds of the corresponding formal
+ * type parameters of type.
+ *
+ * Parameters:
+ * 0: the name of the type used in the instance creation that should be
+ * limited by the bound as specified in the class declaration
+ * 1: the name of the bounding type
+ *
+ * See [TYPE_PARAMETER_SUPERTYPE_OF_ITS_BOUND].
+ */
+ static const StaticTypeWarningCode TYPE_ARGUMENT_NOT_MATCHING_BOUNDS =
+ const StaticTypeWarningCode(
+ 'TYPE_ARGUMENT_NOT_MATCHING_BOUNDS', "'{0}' does not extend '{1}'");
+
+ /**
+ * 10 Generics: It is a static type warning if a type parameter is a supertype
+ * of its upper bound.
+ *
+ * Parameters:
+ * 0: the name of the type parameter
+ *
+ * See [TYPE_ARGUMENT_NOT_MATCHING_BOUNDS].
+ */
+ static const StaticTypeWarningCode TYPE_PARAMETER_SUPERTYPE_OF_ITS_BOUND =
+ const StaticTypeWarningCode('TYPE_PARAMETER_SUPERTYPE_OF_ITS_BOUND',
+ "'{0}' cannot be a supertype of its upper bound");
+
+ /**
+ * 12.17 Getter Invocation: It is a static warning if there is no class
+ * <i>C</i> in the enclosing lexical scope of <i>i</i>, or if <i>C</i> does
+ * not declare, implicitly or explicitly, a getter named <i>m</i>.
+ *
+ * Parameters:
+ * 0: the name of the enumeration constant that is not defined
+ * 1: the name of the enumeration used to access the constant
+ */
+ static const StaticTypeWarningCode UNDEFINED_ENUM_CONSTANT =
+ shared_messages.UNDEFINED_ENUM_CONSTANT;
+
+ /**
+ * 12.15.3 Unqualified Invocation: If there exists a lexically visible
+ * declaration named <i>id</i>, let <i>f<sub>id</sub></i> be the innermost
+ * such declaration. Then: [skip]. Otherwise, <i>f<sub>id</sub></i> is
+ * considered equivalent to the ordinary method invocation
+ * <b>this</b>.<i>id</i>(<i>a<sub>1</sub></i>, ..., <i>a<sub>n</sub></i>,
+ * <i>x<sub>n+1</sub></i> : <i>a<sub>n+1</sub></i>, ...,
+ * <i>x<sub>n+k</sub></i> : <i>a<sub>n+k</sub></i>).
+ *
+ * Parameters:
+ * 0: the name of the method that is undefined
+ */
+ static const StaticTypeWarningCode UNDEFINED_FUNCTION =
+ shared_messages.UNDEFINED_FUNCTION;
+
+ /**
+ * 12.17 Getter Invocation: Let <i>T</i> be the static type of <i>e</i>. It is
+ * a static type warning if <i>T</i> does not have a getter named <i>m</i>.
+ *
+ * Parameters:
+ * 0: the name of the getter
+ * 1: the name of the enclosing type where the getter is being looked for
+ */
+ static const StaticTypeWarningCode UNDEFINED_GETTER =
+ shared_messages.UNDEFINED_GETTER_STATIC_TYPE_WARNING;
+
+ /**
+ * 12.15.1 Ordinary Invocation: Let <i>T</i> be the static type of <i>o</i>.
+ * It is a static type warning if <i>T</i> does not have an accessible
+ * instance member named <i>m</i>.
+ *
+ * Parameters:
+ * 0: the name of the method that is undefined
+ * 1: the resolved type name that the method lookup is happening on
+ */
+ static const StaticTypeWarningCode UNDEFINED_METHOD =
+ shared_messages.UNDEFINED_METHOD_STATIC_TYPE_WARNING;
+
+ /**
+ * 12.15.1 Ordinary Invocation: Let <i>T</i> be the static type of <i>o</i>.
+ * It is a static type warning if <i>T</i> does not have an accessible
+ * instance member named <i>m</i>.
+ *
+ * Parameters:
+ * 0: the name of the method that is undefined
+ * 1: the resolved type name that the method lookup is happening on
+ */
+ static const StaticTypeWarningCode UNDEFINED_METHOD_WITH_CONSTRUCTOR =
+ shared_messages.UNDEFINED_METHOD_WITH_CONSTRUCTOR;
+
+ /**
+ * 12.18 Assignment: Evaluation of an assignment of the form
+ * <i>e<sub>1</sub></i>[<i>e<sub>2</sub></i>] = <i>e<sub>3</sub></i> is
+ * equivalent to the evaluation of the expression (a, i, e){a.[]=(i, e);
+ * return e;} (<i>e<sub>1</sub></i>, <i>e<sub>2</sub></i>,
+ * <i>e<sub>2</sub></i>).
+ *
+ * 12.29 Assignable Expressions: An assignable expression of the form
+ * <i>e<sub>1</sub></i>[<i>e<sub>2</sub></i>] is evaluated as a method
+ * invocation of the operator method [] on <i>e<sub>1</sub></i> with argument
+ * <i>e<sub>2</sub></i>.
+ *
+ * 12.15.1 Ordinary Invocation: Let <i>T</i> be the static type of <i>o</i>.
+ * It is a static type warning if <i>T</i> does not have an accessible
+ * instance member named <i>m</i>.
+ *
+ * Parameters:
+ * 0: the name of the operator
+ * 1: the name of the enclosing type where the operator is being looked for
+ */
+ static const StaticTypeWarningCode UNDEFINED_OPERATOR =
+ shared_messages.UNDEFINED_OPERATOR_STATIC_TYPE_WARNING;
+
+ /**
+ * 12.18 Assignment: Let <i>T</i> be the static type of <i>e<sub>1</sub></i>.
+ * It is a static type warning if <i>T</i> does not have an accessible
+ * instance setter named <i>v=</i>.
+ *
+ * Parameters:
+ * 0: the name of the setter
+ * 1: the name of the enclosing type where the setter is being looked for
+ *
+ * See [INACCESSIBLE_SETTER].
+ */
+ static const StaticTypeWarningCode UNDEFINED_SETTER =
+ shared_messages.UNDEFINED_SETTER_STATIC_TYPE_WARNING;
+
+ /**
+ * 12.17 Getter Invocation: Let <i>T</i> be the static type of <i>e</i>. It is
+ * a static type warning if <i>T</i> does not have a getter named <i>m</i>.
+ *
+ * Parameters:
+ * 0: the name of the getter
+ * 1: the name of the enclosing type where the getter is being looked for
+ */
+ static const StaticTypeWarningCode UNDEFINED_SUPER_GETTER =
+ shared_messages.UNDEFINED_SUPER_GETTER_STATIC_TYPE_WARNING;
+
+ /**
+ * 12.15.4 Super Invocation: A super method invocation <i>i</i> has the form
+ * <i>super.m(a<sub>1</sub>, …, a<sub>n</sub>, x<sub>n+1</sub>:
+ * a<sub>n+1</sub>, … x<sub>n+k</sub>: a<sub>n+k</sub>)</i>. It is a
+ * static type warning if <i>S</i> does not have an accessible instance member
+ * named <i>m</i>.
+ *
+ * Parameters:
+ * 0: the name of the method that is undefined
+ * 1: the resolved type name that the method lookup is happening on
+ */
+ static const StaticTypeWarningCode UNDEFINED_SUPER_METHOD =
+ shared_messages.UNDEFINED_SUPER_METHOD;
+
+ /**
+ * 12.18 Assignment: Evaluation of an assignment of the form
+ * <i>e<sub>1</sub></i>[<i>e<sub>2</sub></i>] = <i>e<sub>3</sub></i> is
+ * equivalent to the evaluation of the expression (a, i, e){a.[]=(i, e);
+ * return e;} (<i>e<sub>1</sub></i>, <i>e<sub>2</sub></i>,
+ * <i>e<sub>2</sub></i>).
+ *
+ * 12.29 Assignable Expressions: An assignable expression of the form
+ * <i>e<sub>1</sub></i>[<i>e<sub>2</sub></i>] is evaluated as a method
+ * invocation of the operator method [] on <i>e<sub>1</sub></i> with argument
+ * <i>e<sub>2</sub></i>.
+ *
+ * 12.15.1 Ordinary Invocation: Let <i>T</i> be the static type of <i>o</i>.
+ * It is a static type warning if <i>T</i> does not have an accessible
+ * instance member named <i>m</i>.
+ *
+ * Parameters:
+ * 0: the name of the operator
+ * 1: the name of the enclosing type where the operator is being looked for
+ */
+ static const StaticTypeWarningCode UNDEFINED_SUPER_OPERATOR =
+ shared_messages.UNDEFINED_SUPER_OPERATOR;
+
+ /**
+ * 12.18 Assignment: Let <i>T</i> be the static type of <i>e<sub>1</sub></i>.
+ * It is a static type warning if <i>T</i> does not have an accessible
+ * instance setter named <i>v=</i>.
+ *
+ * Parameters:
+ * 0: the name of the setter
+ * 1: the name of the enclosing type where the setter is being looked for
+ *
+ * See [INACCESSIBLE_SETTER].
+ */
+ static const StaticTypeWarningCode UNDEFINED_SUPER_SETTER =
+ shared_messages.UNDEFINED_SUPER_SETTER_STATIC_TYPE_WARNING;
+
+ /**
+ * 12.15.1 Ordinary Invocation: It is a static type warning if <i>T</i> does
+ * not have an accessible (3.2) instance member named <i>m</i>.
+ *
+ * This is a specialization of [INSTANCE_ACCESS_TO_STATIC_MEMBER] that is used
+ * when we are able to find the name defined in a supertype. It exists to
+ * provide a more informative error message.
+ */
+ static const StaticTypeWarningCode
+ UNQUALIFIED_REFERENCE_TO_NON_LOCAL_STATIC_MEMBER =
+ const StaticTypeWarningCode(
+ 'UNQUALIFIED_REFERENCE_TO_NON_LOCAL_STATIC_MEMBER',
+ "Static members from supertypes must be qualified by the name of the defining type");
+
+ /**
+ * 15.8 Parameterized Types: It is a static type warning if <i>G</i> is not a
+ * generic type with exactly <i>n</i> type parameters.
+ *
+ * Parameters:
+ * 0: the name of the type being referenced (<i>G</i>)
+ * 1: the number of type parameters that were declared
+ * 2: the number of type arguments provided
+ *
+ * See [CompileTimeErrorCode.CONST_WITH_INVALID_TYPE_PARAMETERS], and
+ * [CompileTimeErrorCode.NEW_WITH_INVALID_TYPE_PARAMETERS].
+ */
+ static const StaticTypeWarningCode WRONG_NUMBER_OF_TYPE_ARGUMENTS =
+ const StaticTypeWarningCode('WRONG_NUMBER_OF_TYPE_ARGUMENTS',
+ "The type '{0}' is declared with {1} type parameters, but {2} type arguments were given");
+
+ /**
+ * 17.16.1 Yield: Let T be the static type of e [the expression to the right
+ * of "yield"] and let f be the immediately enclosing function. It is a
+ * static type warning if either:
+ *
+ * - the body of f is marked async* and the type Stream<T> may not be
+ * assigned to the declared return type of f.
+ *
+ * - the body of f is marked sync* and the type Iterable<T> may not be
+ * assigned to the declared return type of f.
+ *
+ * 17.16.2 Yield-Each: Let T be the static type of e [the expression to the
+ * right of "yield*"] and let f be the immediately enclosing function. It is
+ * a static type warning if T may not be assigned to the declared return type
+ * of f. If f is synchronous it is a static type warning if T may not be
+ * assigned to Iterable. If f is asynchronous it is a static type warning if
+ * T may not be assigned to Stream.
+ */
+ static const StaticTypeWarningCode YIELD_OF_INVALID_TYPE =
+ const StaticTypeWarningCode('YIELD_OF_INVALID_TYPE',
+ "The type '{0}' implied by the 'yield' expression must be assignable to '{1}'");
+
+ /**
+ * 17.6.2 For-in. If the iterable expression does not implement Iterable,
+ * this warning is reported.
+ *
+ * Parameters:
+ * 0: The type of the iterable expression.
+ * 1: The sequence type -- Iterable for `for` or Stream for `await for`.
+ */
+ static const StaticTypeWarningCode FOR_IN_OF_INVALID_TYPE =
+ const StaticTypeWarningCode('FOR_IN_OF_INVALID_TYPE',
+ "The type '{0}' used in the 'for' loop must implement {1}");
+
+ /**
+ * 17.6.2 For-in. It the iterable expression does not implement Iterable with
+ * a type argument that can be assigned to the for-in variable's type, this
+ * warning is reported.
+ *
+ * Parameters:
+ * 0: The type of the iterable expression.
+ * 1: The sequence type -- Iterable for `for` or Stream for `await for`.
+ * 2: The loop variable type.
+ */
+ static const StaticTypeWarningCode FOR_IN_OF_INVALID_ELEMENT_TYPE =
+ const StaticTypeWarningCode('FOR_IN_OF_INVALID_ELEMENT_TYPE',
+ "The type '{0}' used in the 'for' loop must implement {1} with a type argument that can be assigned to '{2}'");
+
+ /**
+ * Initialize a newly created error code to have the given [name]. The message
+ * associated with the error will be created from the given [message]
+ * template. The correction associated with the error will be created from the
+ * given [correction] template.
+ */
+ const StaticTypeWarningCode(String name, String message, [String correction])
+ : super(name, message, correction);
+
+ @override
+ ErrorSeverity get errorSeverity => ErrorType.STATIC_TYPE_WARNING.severity;
+
+ @override
+ ErrorType get type => ErrorType.STATIC_TYPE_WARNING;
+}
+
+/**
+ * The error codes used for static warnings. The convention for this class is
+ * for the name of the error code to indicate the problem that caused the error
+ * to be generated and for the error message to explain what is wrong and, when
+ * appropriate, how the problem can be corrected.
+ */
+class StaticWarningCode extends ErrorCode {
+ /**
+ * 14.1 Imports: If a name <i>N</i> is referenced by a library <i>L</i> and
+ * <i>N</i> is introduced into the top level scope <i>L</i> by more than one
+ * import then:
+ * 1. A static warning occurs.
+ * 2. If <i>N</i> is referenced as a function, getter or setter, a
+ * <i>NoSuchMethodError</i> is raised.
+ * 3. If <i>N</i> is referenced as a type, it is treated as a malformed type.
+ *
+ * Parameters:
+ * 0: the name of the ambiguous type
+ * 1: the name of the first library that the type is found
+ * 2: the name of the second library that the type is found
+ */
+ static const StaticWarningCode AMBIGUOUS_IMPORT = const StaticWarningCode(
+ 'AMBIGUOUS_IMPORT',
+ "The name '{0}' is defined in the libraries {1}",
+ "Consider using 'as prefix' for one of the import directives "
+ "or hiding the name from all but one of the imports.");
+
+ /**
+ * 12.11.1 New: It is a static warning if the static type of <i>a<sub>i</sub>,
+ * 1 <= i <= n+ k</i> may not be assigned to the type of the
+ * corresponding formal parameter of the constructor <i>T.id</i> (respectively
+ * <i>T</i>).
+ *
+ * 12.11.2 Const: It is a static warning if the static type of
+ * <i>a<sub>i</sub>, 1 <= i <= n+ k</i> may not be assigned to the type
+ * of the corresponding formal parameter of the constructor <i>T.id</i>
+ * (respectively <i>T</i>).
+ *
+ * 12.14.2 Binding Actuals to Formals: Let <i>T<sub>i</sub></i> be the static
+ * type of <i>a<sub>i</sub></i>, let <i>S<sub>i</sub></i> be the type of
+ * <i>p<sub>i</sub>, 1 <= i <= n+k</i> and let <i>S<sub>q</sub></i> be
+ * the type of the named parameter <i>q</i> of <i>f</i>. It is a static
+ * warning if <i>T<sub>j</sub></i> may not be assigned to <i>S<sub>j</sub>, 1
+ * <= j <= m</i>.
+ *
+ * 12.14.2 Binding Actuals to Formals: Furthermore, each <i>q<sub>i</sub>, 1
+ * <= i <= l</i>, must have a corresponding named parameter in the set
+ * <i>{p<sub>n+1</sub>, … p<sub>n+k</sub>}</i> or a static warning
+ * occurs. It is a static warning if <i>T<sub>m+j</sub></i> may not be
+ * assigned to <i>S<sub>r</sub></i>, where <i>r = q<sub>j</sub>, 1 <= j
+ * <= l</i>.
+ *
+ * Parameters:
+ * 0: the name of the actual argument type
+ * 1: the name of the expected type
+ */
+ static const StaticWarningCode ARGUMENT_TYPE_NOT_ASSIGNABLE =
+ shared_messages.ARGUMENT_TYPE_NOT_ASSIGNABLE_STATIC_WARNING;
+
+ /**
+ * 5 Variables: Attempting to assign to a final variable elsewhere will cause
+ * a NoSuchMethodError to be thrown, because no setter is defined for it. The
+ * assignment will also give rise to a static warning for the same reason.
+ *
+ * A constant variable is always implicitly final.
+ */
+ static const StaticWarningCode ASSIGNMENT_TO_CONST = const StaticWarningCode(
+ 'ASSIGNMENT_TO_CONST', "Constant variables cannot be assigned a value");
+
+ /**
+ * 5 Variables: Attempting to assign to a final variable elsewhere will cause
+ * a NoSuchMethodError to be thrown, because no setter is defined for it. The
+ * assignment will also give rise to a static warning for the same reason.
+ */
+ static const StaticWarningCode ASSIGNMENT_TO_FINAL = const StaticWarningCode(
+ 'ASSIGNMENT_TO_FINAL', "'{0}' cannot be used as a setter, it is final");
+
+ /**
+ * 5 Variables: Attempting to assign to a final variable elsewhere will cause
+ * a NoSuchMethodError to be thrown, because no setter is defined for it. The
+ * assignment will also give rise to a static warning for the same reason.
+ */
+ static const StaticWarningCode ASSIGNMENT_TO_FINAL_NO_SETTER =
+ const StaticWarningCode('ASSIGNMENT_TO_FINAL_NO_SETTER',
+ "No setter named '{0}' in class '{1}'");
+
+ /**
+ * 12.18 Assignment: It is as static warning if an assignment of the form
+ * <i>v = e</i> occurs inside a top level or static function (be it function,
+ * method, getter, or setter) or variable initializer and there is neither a
+ * local variable declaration with name <i>v</i> nor setter declaration with
+ * name <i>v=</i> in the lexical scope enclosing the assignment.
+ */
+ static const StaticWarningCode ASSIGNMENT_TO_FUNCTION =
+ const StaticWarningCode(
+ 'ASSIGNMENT_TO_FUNCTION', "Functions cannot be assigned a value");
+
+ /**
+ * 12.18 Assignment: Let <i>T</i> be the static type of <i>e<sub>1</sub></i>
+ * It is a static type warning if <i>T</i> does not have an accessible
+ * instance setter named <i>v=</i>.
+ */
+ static const StaticWarningCode ASSIGNMENT_TO_METHOD = const StaticWarningCode(
+ 'ASSIGNMENT_TO_METHOD', "Methods cannot be assigned a value");
+
+ /**
+ * 12.18 Assignment: It is as static warning if an assignment of the form
+ * <i>v = e</i> occurs inside a top level or static function (be it function,
+ * method, getter, or setter) or variable initializer and there is neither a
+ * local variable declaration with name <i>v</i> nor setter declaration with
+ * name <i>v=</i> in the lexical scope enclosing the assignment.
+ */
+ static const StaticWarningCode ASSIGNMENT_TO_TYPE = const StaticWarningCode(
+ 'ASSIGNMENT_TO_TYPE', "Types cannot be assigned a value");
+
+ /**
+ * 13.9 Switch: It is a static warning if the last statement of the statement
+ * sequence <i>s<sub>k</sub></i> is not a break, continue, return or throw
+ * statement.
+ */
+ static const StaticWarningCode CASE_BLOCK_NOT_TERMINATED =
+ const StaticWarningCode('CASE_BLOCK_NOT_TERMINATED',
+ "The last statement of the 'case' should be 'break', 'continue', 'return' or 'throw'");
+
+ /**
+ * 12.32 Type Cast: It is a static warning if <i>T</i> does not denote a type
+ * available in the current lexical scope.
+ */
+ static const StaticWarningCode CAST_TO_NON_TYPE = const StaticWarningCode(
+ 'CAST_TO_NON_TYPE',
+ "The name '{0}' is not a type and cannot be used in an 'as' expression");
+
+ /**
+ * 7.4 Abstract Instance Members: It is a static warning if an abstract member
+ * is declared or inherited in a concrete class.
+ */
+ static const StaticWarningCode CONCRETE_CLASS_WITH_ABSTRACT_MEMBER =
+ const StaticWarningCode('CONCRETE_CLASS_WITH_ABSTRACT_MEMBER',
+ "'{0}' must have a method body because '{1}' is not abstract");
+
+ /**
+ * 14.1 Imports: If a name <i>N</i> is referenced by a library <i>L</i> and
+ * <i>N</i> would be introduced into the top level scope of <i>L</i> by an
+ * import from a library whose URI begins with <i>dart:</i> and an import from
+ * a library whose URI does not begin with <i>dart:</i>:
+ * * The import from <i>dart:</i> is implicitly extended by a hide N clause.
+ * * A static warning is issued.
+ *
+ * Parameters:
+ * 0: the ambiguous name
+ * 1: the name of the dart: library in which the element is found
+ * 2: the name of the non-dart: library in which the element is found
+ */
+ static const StaticWarningCode CONFLICTING_DART_IMPORT =
+ const StaticWarningCode('CONFLICTING_DART_IMPORT',
+ "Element '{0}' from SDK library '{1}' is implicitly hidden by '{2}'");
+
+ /**
+ * 7.2 Getters: It is a static warning if a class <i>C</i> declares an
+ * instance getter named <i>v</i> and an accessible static member named
+ * <i>v</i> or <i>v=</i> is declared in a superclass of <i>C</i>.
+ *
+ * Parameters:
+ * 0: the name of the super class declaring a static member
+ */
+ static const StaticWarningCode
+ CONFLICTING_INSTANCE_GETTER_AND_SUPERCLASS_MEMBER =
+ const StaticWarningCode(
+ 'CONFLICTING_INSTANCE_GETTER_AND_SUPERCLASS_MEMBER',
+ "Superclass '{0}' declares static member with the same name");
+
+ /**
+ * 7.1 Instance Methods: It is a static warning if a class <i>C</i> declares
+ * an instance method named <i>n</i> and has a setter named <i>n=</i>.
+ */
+ static const StaticWarningCode CONFLICTING_INSTANCE_METHOD_SETTER =
+ const StaticWarningCode('CONFLICTING_INSTANCE_METHOD_SETTER',
+ "Class '{0}' declares instance method '{1}', but also has a setter with the same name from '{2}'");
+
+ /**
+ * 7.1 Instance Methods: It is a static warning if a class <i>C</i> declares
+ * an instance method named <i>n</i> and has a setter named <i>n=</i>.
+ */
+ static const StaticWarningCode CONFLICTING_INSTANCE_METHOD_SETTER2 =
+ const StaticWarningCode('CONFLICTING_INSTANCE_METHOD_SETTER2',
+ "Class '{0}' declares the setter '{1}', but also has an instance method in the same class");
+
+ /**
+ * 7.3 Setters: It is a static warning if a class <i>C</i> declares an
+ * instance setter named <i>v=</i> and an accessible static member named
+ * <i>v=</i> or <i>v</i> is declared in a superclass of <i>C</i>.
+ *
+ * Parameters:
+ * 0: the name of the super class declaring a static member
+ */
+ static const StaticWarningCode
+ CONFLICTING_INSTANCE_SETTER_AND_SUPERCLASS_MEMBER =
+ const StaticWarningCode(
+ 'CONFLICTING_INSTANCE_SETTER_AND_SUPERCLASS_MEMBER',
+ "Superclass '{0}' declares static member with the same name");
+
+ /**
+ * 7.2 Getters: It is a static warning if a class declares a static getter
+ * named <i>v</i> and also has a non-static setter named <i>v=</i>.
+ */
+ static const StaticWarningCode CONFLICTING_STATIC_GETTER_AND_INSTANCE_SETTER =
+ const StaticWarningCode('CONFLICTING_STATIC_GETTER_AND_INSTANCE_SETTER',
+ "Class '{0}' declares non-static setter with the same name");
+
+ /**
+ * 7.3 Setters: It is a static warning if a class declares a static setter
+ * named <i>v=</i> and also has a non-static member named <i>v</i>.
+ */
+ static const StaticWarningCode CONFLICTING_STATIC_SETTER_AND_INSTANCE_MEMBER =
+ const StaticWarningCode('CONFLICTING_STATIC_SETTER_AND_INSTANCE_MEMBER',
+ "Class '{0}' declares non-static member with the same name");
+
+ /**
+ * 12.11.2 Const: Given an instance creation expression of the form <i>const
+ * q(a<sub>1</sub>, … a<sub>n</sub>)</i> it is a static warning if
+ * <i>q</i> is the constructor of an abstract class but <i>q</i> is not a
+ * factory constructor.
+ */
+ static const StaticWarningCode CONST_WITH_ABSTRACT_CLASS =
+ const StaticWarningCode('CONST_WITH_ABSTRACT_CLASS',
+ "Abstract classes cannot be created with a 'const' expression");
+
+ /**
+ * 12.7 Maps: It is a static warning if the values of any two keys in a map
+ * literal are equal.
+ */
+ static const StaticWarningCode EQUAL_KEYS_IN_MAP = const StaticWarningCode(
+ 'EQUAL_KEYS_IN_MAP', "Keys in a map cannot be equal");
+
+ /**
+ * 14.2 Exports: It is a static warning to export two different libraries with
+ * the same name.
+ *
+ * Parameters:
+ * 0: the uri pointing to a first library
+ * 1: the uri pointing to a second library
+ * 2:e the shared name of the exported libraries
+ */
+ static const StaticWarningCode EXPORT_DUPLICATED_LIBRARY_NAMED =
+ const StaticWarningCode('EXPORT_DUPLICATED_LIBRARY_NAMED',
+ "The exported libraries '{0}' and '{1}' cannot have the same name '{2}'");
+
+ /**
+ * 12.14.2 Binding Actuals to Formals: It is a static warning if <i>m <
+ * h</i> or if <i>m > n</i>.
+ *
+ * Parameters:
+ * 0: the maximum number of positional arguments
+ * 1: the actual number of positional arguments given
+ *
+ * See [NOT_ENOUGH_REQUIRED_ARGUMENTS].
+ */
+ static const StaticWarningCode EXTRA_POSITIONAL_ARGUMENTS =
+ const StaticWarningCode('EXTRA_POSITIONAL_ARGUMENTS',
+ "{0} positional arguments expected, but {1} found");
+
+ /**
+ * 5. Variables: It is a static warning if a final instance variable that has
+ * been initialized at its point of declaration is also initialized in a
+ * constructor.
+ */
+ static const StaticWarningCode
+ FIELD_INITIALIZED_IN_INITIALIZER_AND_DECLARATION =
+ const StaticWarningCode(
+ 'FIELD_INITIALIZED_IN_INITIALIZER_AND_DECLARATION',
+ "Values cannot be set in the constructor if they are final, and have already been set");
+
+ /**
+ * 5. Variables: It is a static warning if a final instance variable that has
+ * been initialized at its point of declaration is also initialized in a
+ * constructor.
+ *
+ * Parameters:
+ * 0: the name of the field in question
+ */
+ static const StaticWarningCode
+ FINAL_INITIALIZED_IN_DECLARATION_AND_CONSTRUCTOR =
+ const StaticWarningCode(
+ 'FINAL_INITIALIZED_IN_DECLARATION_AND_CONSTRUCTOR',
+ "'{0}' is final and was given a value when it was declared, so it cannot be set to a new value");
+
+ /**
+ * 7.6.1 Generative Constructors: Execution of an initializer of the form
+ * <b>this</b>.<i>v</i> = <i>e</i> proceeds as follows: First, the expression
+ * <i>e</i> is evaluated to an object <i>o</i>. Then, the instance variable
+ * <i>v</i> of the object denoted by this is bound to <i>o</i>.
+ *
+ * 12.14.2 Binding Actuals to Formals: Let <i>T<sub>i</sub></i> be the static
+ * type of <i>a<sub>i</sub></i>, let <i>S<sub>i</sub></i> be the type of
+ * <i>p<sub>i</sub>, 1 <= i <= n+k</i> and let <i>S<sub>q</sub></i> be
+ * the type of the named parameter <i>q</i> of <i>f</i>. It is a static
+ * warning if <i>T<sub>j</sub></i> may not be assigned to <i>S<sub>j</sub>, 1
+ * <= j <= m</i>.
+ *
+ * Parameters:
+ * 0: the name of the type of the initializer expression
+ * 1: the name of the type of the field
+ */
+ static const StaticWarningCode FIELD_INITIALIZER_NOT_ASSIGNABLE =
+ const StaticWarningCode('FIELD_INITIALIZER_NOT_ASSIGNABLE',
+ "The initializer type '{0}' cannot be assigned to the field type '{1}'");
+
+ /**
+ * 7.6.1 Generative Constructors: An initializing formal has the form
+ * <i>this.id</i>. It is a static warning if the static type of <i>id</i> is
+ * not assignable to <i>T<sub>id</sub></i>.
+ *
+ * Parameters:
+ * 0: the name of the type of the field formal parameter
+ * 1: the name of the type of the field
+ */
+ static const StaticWarningCode FIELD_INITIALIZING_FORMAL_NOT_ASSIGNABLE =
+ const StaticWarningCode('FIELD_INITIALIZING_FORMAL_NOT_ASSIGNABLE',
+ "The parameter type '{0}' is incompatable with the field type '{1}'");
+
+ /**
+ * 5 Variables: It is a static warning if a library, static or local variable
+ * <i>v</i> is final and <i>v</i> is not initialized at its point of
+ * declaration.
+ *
+ * Parameters:
+ * 0: the name of the uninitialized final variable
+ */
+ static const StaticWarningCode FINAL_NOT_INITIALIZED =
+ const StaticWarningCode('FINAL_NOT_INITIALIZED',
+ "The final variable '{0}' must be initialized", null, false);
+
+ /**
+ * 7.6.1 Generative Constructors: Each final instance variable <i>f</i>
+ * declared in the immediately enclosing class must have an initializer in
+ * <i>k</i>'s initializer list unless it has already been initialized by one
+ * of the following means:
+ * * Initialization at the declaration of <i>f</i>.
+ * * Initialization by means of an initializing formal of <i>k</i>.
+ * or a static warning occurs.
+ *
+ * Parameters:
+ * 0: the name of the uninitialized final variable
+ */
+ static const StaticWarningCode FINAL_NOT_INITIALIZED_CONSTRUCTOR_1 =
+ const StaticWarningCode('FINAL_NOT_INITIALIZED_CONSTRUCTOR_1',
+ "The final variable '{0}' must be initialized", null, false);
+
+ /**
+ * 7.6.1 Generative Constructors: Each final instance variable <i>f</i>
+ * declared in the immediately enclosing class must have an initializer in
+ * <i>k</i>'s initializer list unless it has already been initialized by one
+ * of the following means:
+ * * Initialization at the declaration of <i>f</i>.
+ * * Initialization by means of an initializing formal of <i>k</i>.
+ * or a static warning occurs.
+ *
+ * Parameters:
+ * 0: the name of the uninitialized final variable
+ * 1: the name of the uninitialized final variable
+ */
+ static const StaticWarningCode FINAL_NOT_INITIALIZED_CONSTRUCTOR_2 =
+ const StaticWarningCode(
+ 'FINAL_NOT_INITIALIZED_CONSTRUCTOR_2',
+ "The final variables '{0}' and '{1}' must be initialized",
+ null,
+ false);
+
+ /**
+ * 7.6.1 Generative Constructors: Each final instance variable <i>f</i>
+ * declared in the immediately enclosing class must have an initializer in
+ * <i>k</i>'s initializer list unless it has already been initialized by one
+ * of the following means:
+ * * Initialization at the declaration of <i>f</i>.
+ * * Initialization by means of an initializing formal of <i>k</i>.
+ * or a static warning occurs.
+ *
+ * Parameters:
+ * 0: the name of the uninitialized final variable
+ * 1: the name of the uninitialized final variable
+ * 2: the number of additional not initialized variables that aren't listed
+ */
+ static const StaticWarningCode FINAL_NOT_INITIALIZED_CONSTRUCTOR_3_PLUS =
+ const StaticWarningCode(
+ 'FINAL_NOT_INITIALIZED_CONSTRUCTOR_3',
+ "The final variables '{0}', '{1}' and '{2}' more must be initialized",
+ null,
+ false);
+
+ /**
+ * 15.5 Function Types: It is a static warning if a concrete class implements
+ * Function and does not have a concrete method named call().
+ */
+ static const StaticWarningCode FUNCTION_WITHOUT_CALL = const StaticWarningCode(
+ 'FUNCTION_WITHOUT_CALL',
+ "Concrete classes that implement Function must implement the method call()");
+
+ /**
+ * 14.1 Imports: It is a static warning to import two different libraries with
+ * the same name.
+ *
+ * Parameters:
+ * 0: the uri pointing to a first library
+ * 1: the uri pointing to a second library
+ * 2: the shared name of the imported libraries
+ */
+ static const StaticWarningCode IMPORT_DUPLICATED_LIBRARY_NAMED =
+ const StaticWarningCode('IMPORT_DUPLICATED_LIBRARY_NAMED',
+ "The imported libraries '{0}' and '{1}' cannot have the same name '{2}'");
+
+ /**
+ * 14.1 Imports: It is a static warning if the specified URI of a deferred
+ * import does not refer to a library declaration.
+ *
+ * Parameters:
+ * 0: the uri pointing to a non-library declaration
+ *
+ * See [CompileTimeErrorCode.IMPORT_OF_NON_LIBRARY].
+ */
+ static const StaticWarningCode IMPORT_OF_NON_LIBRARY =
+ const StaticWarningCode('IMPORT_OF_NON_LIBRARY',
+ "The imported library '{0}' must not have a part-of directive");
+
+ /**
+ * 8.1.1 Inheritance and Overriding: However, if the above rules would cause
+ * multiple members <i>m<sub>1</sub>, …, m<sub>k</sub></i> with the
+ * same name <i>n</i> that would be inherited (because identically named
+ * members existed in several superinterfaces) then at most one member is
+ * inherited.
+ *
+ * If some but not all of the <i>m<sub>i</sub>, 1 <= i <= k</i> are
+ * getters none of the <i>m<sub>i</sub></i> are inherited, and a static
+ * warning is issued.
+ */
+ static const StaticWarningCode
+ INCONSISTENT_METHOD_INHERITANCE_GETTER_AND_METHOD =
+ const StaticWarningCode(
+ 'INCONSISTENT_METHOD_INHERITANCE_GETTER_AND_METHOD',
+ "'{0}' is inherited as a getter and also a method");
+
+ /**
+ * 7.1 Instance Methods: It is a static warning if a class <i>C</i> declares
+ * an instance method named <i>n</i> and an accessible static member named
+ * <i>n</i> is declared in a superclass of <i>C</i>.
+ *
+ * Parameters:
+ * 0: the name of the member with the name conflict
+ * 1: the name of the enclosing class that has the static member
+ */
+ static const StaticWarningCode
+ INSTANCE_METHOD_NAME_COLLIDES_WITH_SUPERCLASS_STATIC =
+ const StaticWarningCode(
+ 'INSTANCE_METHOD_NAME_COLLIDES_WITH_SUPERCLASS_STATIC',
+ "'{0}' collides with a static member in the superclass '{1}'");
+
+ /**
+ * 7.2 Getters: It is a static warning if a getter <i>m1</i> overrides a
+ * getter <i>m2</i> and the type of <i>m1</i> is not a subtype of the type of
+ * <i>m2</i>.
+ *
+ * Parameters:
+ * 0: the name of the actual return type
+ * 1: the name of the expected return type, not assignable to the actual
+ * return type
+ * 2: the name of the class where the overridden getter is declared
+ *
+ * See [INVALID_METHOD_OVERRIDE_RETURN_TYPE].
+ */
+ static const StaticWarningCode INVALID_GETTER_OVERRIDE_RETURN_TYPE =
+ const StaticWarningCode('INVALID_GETTER_OVERRIDE_RETURN_TYPE',
+ "The return type '{0}' is not assignable to '{1}' as required by the getter it is overriding from '{2}'");
+
+ /**
+ * 7.1 Instance Methods: It is a static warning if an instance method
+ * <i>m1</i> overrides an instance method <i>m2</i> and the type of <i>m1</i>
+ * is not a subtype of the type of <i>m2</i>.
+ *
+ * Parameters:
+ * 0: the name of the actual parameter type
+ * 1: the name of the expected parameter type, not assignable to the actual
+ * parameter type
+ * 2: the name of the class where the overridden method is declared
+ */
+ static const StaticWarningCode INVALID_METHOD_OVERRIDE_NAMED_PARAM_TYPE =
+ const StaticWarningCode('INVALID_METHOD_OVERRIDE_NAMED_PARAM_TYPE',
+ "The parameter type '{0}' is not assignable to '{1}' as required by the method it is overriding from '{2}'");
+
+ /**
+ * Generic Method DEP: number of type parameters must match.
+ * <https://github.com/leafpetersen/dep-generic-methods/blob/master/proposal.md#function-subtyping>
+ *
+ * Parameters:
+ * 0: the number of type parameters in the method
+ * 1: the number of type parameters in the overridden method
+ * 2: the name of the class where the overridden method is declared
+ */
+ static const StaticWarningCode INVALID_METHOD_OVERRIDE_TYPE_PARAMETERS =
+ const StaticWarningCode('INVALID_METHOD_OVERRIDE_TYPE_PARAMETERS',
+ "The method has {0} type parameters, but it is overriding a method with {1} type parameters from '{2}'");
+
+ /**
+ * Generic Method DEP: bounds of type parameters must be compatible.
+ * <https://github.com/leafpetersen/dep-generic-methods/blob/master/proposal.md#function-subtyping>
+ *
+ * Parameters:
+ * 0: the type parameter name
+ * 1: the type parameter bound
+ * 2: the overridden type parameter name
+ * 3: the overridden type parameter bound
+ * 4: the name of the class where the overridden method is declared
+ */
+ static const StaticWarningCode INVALID_METHOD_OVERRIDE_TYPE_PARAMETER_BOUND =
+ const StaticWarningCode('INVALID_METHOD_OVERRIDE_TYPE_PARAMETER_BOUND',
+ "The type parameter '{0}' extends '{1}', but that is stricter than '{2}' extends '{3}' in the overridden method from '{4}'");
+
+ /**
+ * 7.1 Instance Methods: It is a static warning if an instance method
+ * <i>m1</i> overrides an instance method <i>m2</i> and the type of <i>m1</i>
+ * is not a subtype of the type of <i>m2</i>.
+ *
+ * Parameters:
+ * 0: the name of the actual parameter type
+ * 1: the name of the expected parameter type, not assignable to the actual
+ * parameter type
+ * 2: the name of the class where the overridden method is declared
+ * See [INVALID_SETTER_OVERRIDE_NORMAL_PARAM_TYPE].
+ */
+ static const StaticWarningCode INVALID_METHOD_OVERRIDE_NORMAL_PARAM_TYPE =
+ const StaticWarningCode('INVALID_METHOD_OVERRIDE_NORMAL_PARAM_TYPE',
+ "The parameter type '{0}' is not assignable to '{1}' as required by the method it is overriding from '{2}'");
+
+ /**
+ * 7.1 Instance Methods: It is a static warning if an instance method
+ * <i>m1</i> overrides an instance method <i>m2</i> and the type of <i>m1</i>
+ * is not a subtype of the type of <i>m2</i>.
+ *
+ * Parameters:
+ * 0: the name of the actual parameter type
+ * 1: the name of the expected parameter type, not assignable to the actual
+ * parameter type
+ * 2: the name of the class where the overridden method is declared
+ */
+ static const StaticWarningCode INVALID_METHOD_OVERRIDE_OPTIONAL_PARAM_TYPE =
+ const StaticWarningCode('INVALID_METHOD_OVERRIDE_OPTIONAL_PARAM_TYPE',
+ "The parameter type '{0}' is not assignable to '{1}' as required by the method it is overriding from '{2}'");
+
+ /**
+ * 7.1 Instance Methods: It is a static warning if an instance method
+ * <i>m1</i> overrides an instance method <i>m2</i> and the type of <i>m1</i>
+ * is not a subtype of the type of <i>m2</i>.
+ *
+ * Parameters:
+ * 0: the name of the actual return type
+ * 1: the name of the expected return type, not assignable to the actual
+ * return type
+ * 2: the name of the class where the overridden method is declared
+ *
+ * See [INVALID_GETTER_OVERRIDE_RETURN_TYPE].
+ */
+ static const StaticWarningCode INVALID_METHOD_OVERRIDE_RETURN_TYPE =
+ const StaticWarningCode('INVALID_METHOD_OVERRIDE_RETURN_TYPE',
+ "The return type '{0}' is not assignable to '{1}' as required by the method it is overriding from '{2}'");
+
+ /**
+ * 7.1 Instance Methods: It is a static warning if an instance method
+ * <i>m1</i> overrides an instance member <i>m2</i>, the signature of
+ * <i>m2</i> explicitly specifies a default value for a formal parameter
+ * <i>p</i> and the signature of <i>m1</i> specifies a different default value
+ * for <i>p</i>.
+ */
+ static const StaticWarningCode
+ INVALID_OVERRIDE_DIFFERENT_DEFAULT_VALUES_NAMED = const StaticWarningCode(
+ 'INVALID_OVERRIDE_DIFFERENT_DEFAULT_VALUES_NAMED',
+ "Parameters cannot override default values, this method overrides '{0}.{1}' where '{2}' has a different value");
+
+ /**
+ * 7.1 Instance Methods: It is a static warning if an instance method
+ * <i>m1</i> overrides an instance member <i>m2</i>, the signature of
+ * <i>m2</i> explicitly specifies a default value for a formal parameter
+ * <i>p</i> and the signature of <i>m1</i> specifies a different default value
+ * for <i>p</i>.
+ */
+ static const StaticWarningCode
+ INVALID_OVERRIDE_DIFFERENT_DEFAULT_VALUES_POSITIONAL =
+ const StaticWarningCode(
+ 'INVALID_OVERRIDE_DIFFERENT_DEFAULT_VALUES_POSITIONAL',
+ "Parameters cannot override default values, this method overrides '{0}.{1}' where this positional parameter has a different value");
+
+ /**
+ * 7.1 Instance Methods: It is a static warning if an instance method
+ * <i>m1</i> overrides an instance member <i>m2</i> and <i>m1</i> does not
+ * declare all the named parameters declared by <i>m2</i>.
+ *
+ * Parameters:
+ * 0: the number of named parameters in the overridden member
+ * 1: the signature of the overridden member
+ * 2: the name of the class from the overridden method
+ */
+ static const StaticWarningCode INVALID_OVERRIDE_NAMED = const StaticWarningCode(
+ 'INVALID_OVERRIDE_NAMED',
+ "Missing the named parameter '{0}' to match the overridden method from '{1}' from '{2}'");
+
+ /**
+ * 7.1 Instance Methods: It is a static warning if an instance method
+ * <i>m1</i> overrides an instance member <i>m2</i> and <i>m1</i> has fewer
+ * positional parameters than <i>m2</i>.
+ *
+ * Parameters:
+ * 0: the number of positional parameters in the overridden member
+ * 1: the signature of the overridden member
+ * 2: the name of the class from the overridden method
+ */
+ static const StaticWarningCode INVALID_OVERRIDE_POSITIONAL =
+ const StaticWarningCode('INVALID_OVERRIDE_POSITIONAL',
+ "Must have at least {0} parameters to match the overridden method '{1}' from '{2}'");
+
+ /**
+ * 7.1 Instance Methods: It is a static warning if an instance method
+ * <i>m1</i> overrides an instance member <i>m2</i> and <i>m1</i> has a
+ * greater number of required parameters than <i>m2</i>.
+ *
+ * Parameters:
+ * 0: the number of required parameters in the overridden member
+ * 1: the signature of the overridden member
+ * 2: the name of the class from the overridden method
+ */
+ static const StaticWarningCode INVALID_OVERRIDE_REQUIRED =
+ const StaticWarningCode('INVALID_OVERRIDE_REQUIRED',
+ "Must have {0} required parameters or less to match the overridden method '{1}' from '{2}'");
+
+ /**
+ * 7.3 Setters: It is a static warning if a setter <i>m1</i> overrides a
+ * setter <i>m2</i> and the type of <i>m1</i> is not a subtype of the type of
+ * <i>m2</i>.
+ *
+ * Parameters:
+ * 0: the name of the actual parameter type
+ * 1: the name of the expected parameter type, not assignable to the actual
+ * parameter type
+ * 2: the name of the class where the overridden setter is declared
+ *
+ * See [INVALID_METHOD_OVERRIDE_NORMAL_PARAM_TYPE].
+ */
+ static const StaticWarningCode INVALID_SETTER_OVERRIDE_NORMAL_PARAM_TYPE =
+ const StaticWarningCode('INVALID_SETTER_OVERRIDE_NORMAL_PARAM_TYPE',
+ "The parameter type '{0}' is not assignable to '{1}' as required by the setter it is overriding from '{2}'");
+
+ /**
+ * 12.6 Lists: A run-time list literal <<i>E</i>> [<i>e<sub>1</sub></i>
+ * … <i>e<sub>n</sub></i>] is evaluated as follows:
+ * * The operator []= is invoked on <i>a</i> with first argument <i>i</i> and
+ * second argument <i>o<sub>i+1</sub></i><i>, 1 <= i <= n</i>
+ *
+ * 12.14.2 Binding Actuals to Formals: Let <i>T<sub>i</sub></i> be the static
+ * type of <i>a<sub>i</sub></i>, let <i>S<sub>i</sub></i> be the type of
+ * <i>p<sub>i</sub>, 1 <= i <= n+k</i> and let <i>S<sub>q</sub></i> be
+ * the type of the named parameter <i>q</i> of <i>f</i>. It is a static
+ * warning if <i>T<sub>j</sub></i> may not be assigned to <i>S<sub>j</sub>, 1
+ * <= j <= m</i>.
+ */
+ static const StaticWarningCode LIST_ELEMENT_TYPE_NOT_ASSIGNABLE =
+ const StaticWarningCode('LIST_ELEMENT_TYPE_NOT_ASSIGNABLE',
+ "The element type '{0}' cannot be assigned to the list type '{1}'");
+
+ /**
+ * 12.7 Map: A run-time map literal <<i>K</i>, <i>V</i>>
+ * [<i>k<sub>1</sub></i> : <i>e<sub>1</sub></i> … <i>k<sub>n</sub></i>
+ * : <i>e<sub>n</sub></i>] is evaluated as follows:
+ * * The operator []= is invoked on <i>m</i> with first argument
+ * <i>k<sub>i</sub></i> and second argument <i>e<sub>i</sub></i><i>, 1 <=
+ * i <= n</i>
+ *
+ * 12.14.2 Binding Actuals to Formals: Let <i>T<sub>i</sub></i> be the static
+ * type of <i>a<sub>i</sub></i>, let <i>S<sub>i</sub></i> be the type of
+ * <i>p<sub>i</sub>, 1 <= i <= n+k</i> and let <i>S<sub>q</sub></i> be
+ * the type of the named parameter <i>q</i> of <i>f</i>. It is a static
+ * warning if <i>T<sub>j</sub></i> may not be assigned to <i>S<sub>j</sub>, 1
+ * <= j <= m</i>.
+ */
+ static const StaticWarningCode MAP_KEY_TYPE_NOT_ASSIGNABLE =
+ const StaticWarningCode('MAP_KEY_TYPE_NOT_ASSIGNABLE',
+ "The element type '{0}' cannot be assigned to the map key type '{1}'");
+
+ /**
+ * 12.7 Map: A run-time map literal <<i>K</i>, <i>V</i>>
+ * [<i>k<sub>1</sub></i> : <i>e<sub>1</sub></i> … <i>k<sub>n</sub></i>
+ * : <i>e<sub>n</sub></i>] is evaluated as follows:
+ * * The operator []= is invoked on <i>m</i> with first argument
+ * <i>k<sub>i</sub></i> and second argument <i>e<sub>i</sub></i><i>, 1 <=
+ * i <= n</i>
+ *
+ * 12.14.2 Binding Actuals to Formals: Let <i>T<sub>i</sub></i> be the static
+ * type of <i>a<sub>i</sub></i>, let <i>S<sub>i</sub></i> be the type of
+ * <i>p<sub>i</sub>, 1 <= i <= n+k</i> and let <i>S<sub>q</sub></i> be
+ * the type of the named parameter <i>q</i> of <i>f</i>. It is a static
+ * warning if <i>T<sub>j</sub></i> may not be assigned to <i>S<sub>j</sub>, 1
+ * <= j <= m</i>.
+ */
+ static const StaticWarningCode MAP_VALUE_TYPE_NOT_ASSIGNABLE =
+ const StaticWarningCode('MAP_VALUE_TYPE_NOT_ASSIGNABLE',
+ "The element type '{0}' cannot be assigned to the map value type '{1}'");
+
+ /**
+ * 7.3 Setters: It is a static warning if a class has a setter named <i>v=</i>
+ * with argument type <i>T</i> and a getter named <i>v</i> with return type
+ * <i>S</i>, and <i>T</i> may not be assigned to <i>S</i>.
+ */
+ static const StaticWarningCode MISMATCHED_GETTER_AND_SETTER_TYPES =
+ const StaticWarningCode(
+ 'MISMATCHED_GETTER_AND_SETTER_TYPES',
+ "The parameter type for setter '{0}' is '{1}' which is not assignable to its getter (of type '{2}')",
+ null,
+ false);
+
+ /**
+ * 7.3 Setters: It is a static warning if a class has a setter named <i>v=</i>
+ * with argument type <i>T</i> and a getter named <i>v</i> with return type
+ * <i>S</i>, and <i>T</i> may not be assigned to <i>S</i>.
+ */
+ static const StaticWarningCode
+ MISMATCHED_GETTER_AND_SETTER_TYPES_FROM_SUPERTYPE =
+ const StaticWarningCode(
+ 'MISMATCHED_GETTER_AND_SETTER_TYPES_FROM_SUPERTYPE',
+ "The parameter type for setter '{0}' is '{1}' which is not assignable to its getter (of type '{2}'), from superclass '{3}'",
+ null,
+ false);
+
+ /**
+ * 17.9 Switch: It is a static warning if all of the following conditions
+ * hold:
+ * * The switch statement does not have a 'default' clause.
+ * * The static type of <i>e</i> is an enumerated typed with elements
+ * <i>id<sub>1</sub></i>, …, <i>id<sub>n</sub></i>.
+ * * The sets {<i>e<sub>1</sub></i>, …, <i>e<sub>k</sub></i>} and
+ * {<i>id<sub>1</sub></i>, …, <i>id<sub>n</sub></i>} are not the
+ * same.
+ *
+ * Parameters:
+ * 0: the name of the constant that is missing
+ */
+ static const StaticWarningCode MISSING_ENUM_CONSTANT_IN_SWITCH =
+ const StaticWarningCode(
+ 'MISSING_ENUM_CONSTANT_IN_SWITCH',
+ "Missing case clause for '{0}'",
+ "Add a case clause for the missing constant or add a default clause.",
+ false);
+
+ /**
+ * 13.12 Return: It is a static warning if a function contains both one or
+ * more return statements of the form <i>return;</i> and one or more return
+ * statements of the form <i>return e;</i>.
+ */
+ static const StaticWarningCode MIXED_RETURN_TYPES = const StaticWarningCode(
+ 'MIXED_RETURN_TYPES',
+ "Methods and functions cannot use return both with and without values",
+ null,
+ false);
+
+ /**
+ * 12.11.1 New: It is a static warning if <i>q</i> is a constructor of an
+ * abstract class and <i>q</i> is not a factory constructor.
+ */
+ static const StaticWarningCode NEW_WITH_ABSTRACT_CLASS =
+ const StaticWarningCode('NEW_WITH_ABSTRACT_CLASS',
+ "Abstract classes cannot be created with a 'new' expression");
+
+ /**
+ * 15.8 Parameterized Types: Any use of a malbounded type gives rise to a
+ * static warning.
+ *
+ * Parameters:
+ * 0: the name of the type being referenced (<i>S</i>)
+ * 1: the number of type parameters that were declared
+ * 2: the number of type arguments provided
+ *
+ * See [CompileTimeErrorCode.CONST_WITH_INVALID_TYPE_PARAMETERS], and
+ * [StaticTypeWarningCode.WRONG_NUMBER_OF_TYPE_ARGUMENTS].
+ */
+ static const StaticWarningCode NEW_WITH_INVALID_TYPE_PARAMETERS =
+ const StaticWarningCode('NEW_WITH_INVALID_TYPE_PARAMETERS',
+ "The type '{0}' is declared with {1} type parameters, but {2} type arguments were given");
+
+ /**
+ * 12.11.1 New: It is a static warning if <i>T</i> is not a class accessible
+ * in the current scope, optionally followed by type arguments.
+ *
+ * Parameters:
+ * 0: the name of the non-type element
+ */
+ static const StaticWarningCode NEW_WITH_NON_TYPE = const StaticWarningCode(
+ 'NEW_WITH_NON_TYPE', "The name '{0}' is not a class");
+
+ /**
+ * 12.11.1 New: If <i>T</i> is a class or parameterized type accessible in the
+ * current scope then:
+ * 1. If <i>e</i> is of the form <i>new T.id(a<sub>1</sub>, …,
+ * a<sub>n</sub>, x<sub>n+1</sub>: a<sub>n+1</sub>, …,
+ * x<sub>n+k</sub>: a<sub>n+k</sub>)</i> it is a static warning if
+ * <i>T.id</i> is not the name of a constructor declared by the type
+ * <i>T</i>.
+ * If <i>e</i> of the form <i>new T(a<sub>1</sub>, …, a<sub>n</sub>,
+ * x<sub>n+1</sub>: a<sub>n+1</sub>, …, x<sub>n+k</sub>:
+ * a<sub>n+kM/sub>)</i> it is a static warning if the type <i>T</i> does not
+ * declare a constructor with the same name as the declaration of <i>T</i>.
+ */
+ static const StaticWarningCode NEW_WITH_UNDEFINED_CONSTRUCTOR =
+ const StaticWarningCode('NEW_WITH_UNDEFINED_CONSTRUCTOR',
+ "The class '{0}' does not have a constructor '{1}'");
+
+ /**
+ * 12.11.1 New: If <i>T</i> is a class or parameterized type accessible in the
+ * current scope then:
+ * 1. If <i>e</i> is of the form <i>new T.id(a<sub>1</sub>, …,
+ * a<sub>n</sub>, x<sub>n+1</sub>: a<sub>n+1</sub>, …, x<sub>n+k</sub>:
+ * a<sub>n+k</sub>)</i> it is a static warning if <i>T.id</i> is not the name
+ * of a constructor declared by the type <i>T</i>. If <i>e</i> of the form
+ * <i>new T(a<sub>1</sub>, …, a<sub>n</sub>, x<sub>n+1</sub>:
+ * a<sub>n+1</sub>, …, x<sub>n+k</sub>: a<sub>n+kM/sub>)</i> it is a
+ * static warning if the type <i>T</i> does not declare a constructor with the
+ * same name as the declaration of <i>T</i>.
+ */
+ static const StaticWarningCode NEW_WITH_UNDEFINED_CONSTRUCTOR_DEFAULT =
+ const StaticWarningCode('NEW_WITH_UNDEFINED_CONSTRUCTOR_DEFAULT',
+ "The class '{0}' does not have a default constructor");
+
+ /**
+ * 7.9.1 Inheritance and Overriding: It is a static warning if a non-abstract
+ * class inherits an abstract method.
+ *
+ * 7.10 Superinterfaces: Let <i>C</i> be a concrete class that does not
+ * declare its own <i>noSuchMethod()</i> method. It is a static warning if the
+ * implicit interface of <i>C</i> includes an instance member <i>m</i> of type
+ * <i>F</i> and <i>C</i> does not declare or inherit a corresponding instance
+ * member <i>m</i> of type <i>F'</i> such that <i>F' <: F</i>.
+ *
+ * 7.4 Abstract Instance Members: It is a static warning if an abstract member
+ * is declared or inherited in a concrete class unless that member overrides a
+ * concrete one.
+ *
+ * Parameters:
+ * 0: the name of the first member
+ * 1: the name of the second member
+ * 2: the name of the third member
+ * 3: the name of the fourth member
+ * 4: the number of additional missing members that aren't listed
+ */
+ static const StaticWarningCode
+ NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER_FIVE_PLUS =
+ const StaticWarningCode(
+ 'NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER_FIVE_PLUS',
+ "Missing concrete implementation of {0}, {1}, {2}, {3} and {4} more");
+
+ /**
+ * 7.9.1 Inheritance and Overriding: It is a static warning if a non-abstract
+ * class inherits an abstract method.
+ *
+ * 7.10 Superinterfaces: Let <i>C</i> be a concrete class that does not
+ * declare its own <i>noSuchMethod()</i> method. It is a static warning if the
+ * implicit interface of <i>C</i> includes an instance member <i>m</i> of type
+ * <i>F</i> and <i>C</i> does not declare or inherit a corresponding instance
+ * member <i>m</i> of type <i>F'</i> such that <i>F' <: F</i>.
+ *
+ * 7.4 Abstract Instance Members: It is a static warning if an abstract member
+ * is declared or inherited in a concrete class unless that member overrides a
+ * concrete one.
+ *
+ * Parameters:
+ * 0: the name of the first member
+ * 1: the name of the second member
+ * 2: the name of the third member
+ * 3: the name of the fourth member
+ */
+ static const StaticWarningCode
+ NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER_FOUR =
+ const StaticWarningCode(
+ 'NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER_FOUR',
+ "Missing concrete implementation of {0}, {1}, {2} and {3}");
+
+ /**
+ * 7.9.1 Inheritance and Overriding: It is a static warning if a non-abstract
+ * class inherits an abstract method.
+ *
+ * 7.10 Superinterfaces: Let <i>C</i> be a concrete class that does not
+ * declare its own <i>noSuchMethod()</i> method. It is a static warning if the
+ * implicit interface of <i>C</i> includes an instance member <i>m</i> of type
+ * <i>F</i> and <i>C</i> does not declare or inherit a corresponding instance
+ * member <i>m</i> of type <i>F'</i> such that <i>F' <: F</i>.
+ *
+ * 7.4 Abstract Instance Members: It is a static warning if an abstract member
+ * is declared or inherited in a concrete class unless that member overrides a
+ * concrete one.
+ *
+ * Parameters:
+ * 0: the name of the member
+ */
+ static const StaticWarningCode
+ NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER_ONE = const StaticWarningCode(
+ 'NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER_ONE',
+ "Missing concrete implementation of {0}");
+
+ /**
+ * 7.9.1 Inheritance and Overriding: It is a static warning if a non-abstract
+ * class inherits an abstract method.
+ *
+ * 7.10 Superinterfaces: Let <i>C</i> be a concrete class that does not
+ * declare its own <i>noSuchMethod()</i> method. It is a static warning if the
+ * implicit interface of <i>C</i> includes an instance member <i>m</i> of type
+ * <i>F</i> and <i>C</i> does not declare or inherit a corresponding instance
+ * member <i>m</i> of type <i>F'</i> such that <i>F' <: F</i>.
+ *
+ * 7.4 Abstract Instance Members: It is a static warning if an abstract member
+ * is declared or inherited in a concrete class unless that member overrides a
+ * concrete one.
+ *
+ * Parameters:
+ * 0: the name of the first member
+ * 1: the name of the second member
+ * 2: the name of the third member
+ */
+ static const StaticWarningCode
+ NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER_THREE =
+ const StaticWarningCode(
+ 'NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER_THREE',
+ "Missing concrete implementation of {0}, {1} and {2}");
+
+ /**
+ * 7.9.1 Inheritance and Overriding: It is a static warning if a non-abstract
+ * class inherits an abstract method.
+ *
+ * 7.10 Superinterfaces: Let <i>C</i> be a concrete class that does not
+ * declare its own <i>noSuchMethod()</i> method. It is a static warning if the
+ * implicit interface of <i>C</i> includes an instance member <i>m</i> of type
+ * <i>F</i> and <i>C</i> does not declare or inherit a corresponding instance
+ * member <i>m</i> of type <i>F'</i> such that <i>F' <: F</i>.
+ *
+ * 7.4 Abstract Instance Members: It is a static warning if an abstract member
+ * is declared or inherited in a concrete class unless that member overrides a
+ * concrete one.
+ *
+ * Parameters:
+ * 0: the name of the first member
+ * 1: the name of the second member
+ */
+ static const StaticWarningCode
+ NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER_TWO = const StaticWarningCode(
+ 'NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER_TWO',
+ "Missing concrete implementation of {0} and {1}");
+
+ /**
+ * 13.11 Try: An on-catch clause of the form <i>on T catch (p<sub>1</sub>,
+ * p<sub>2</sub>) s</i> or <i>on T s</i> matches an object <i>o</i> if the
+ * type of <i>o</i> is a subtype of <i>T</i>. It is a static warning if
+ * <i>T</i> does not denote a type available in the lexical scope of the
+ * catch clause.
+ *
+ * Parameters:
+ * 0: the name of the non-type element
+ */
+ static const StaticWarningCode NON_TYPE_IN_CATCH_CLAUSE =
+ const StaticWarningCode('NON_TYPE_IN_CATCH_CLAUSE',
+ "The name '{0}' is not a type and cannot be used in an on-catch clause");
+
+ /**
+ * 7.1.1 Operators: It is a static warning if the return type of the
+ * user-declared operator []= is explicitly declared and not void.
+ */
+ static const StaticWarningCode NON_VOID_RETURN_FOR_OPERATOR =
+ const StaticWarningCode('NON_VOID_RETURN_FOR_OPERATOR',
+ "The return type of the operator []= must be 'void'", null, false);
+
+ /**
+ * 7.3 Setters: It is a static warning if a setter declares a return type
+ * other than void.
+ */
+ static const StaticWarningCode NON_VOID_RETURN_FOR_SETTER =
+ const StaticWarningCode('NON_VOID_RETURN_FOR_SETTER',
+ "The return type of the setter must be 'void'", null, false);
+
+ /**
+ * 15.1 Static Types: A type <i>T</i> is malformed iff:
+ * * <i>T</i> has the form <i>id</i> or the form <i>prefix.id</i>, and in the
+ * enclosing lexical scope, the name <i>id</i> (respectively
+ * <i>prefix.id</i>) does not denote a type.
+ * * <i>T</i> denotes a type parameter in the enclosing lexical scope, but
+ * occurs in the signature or body of a static member.
+ * * <i>T</i> is a parameterized type of the form <i>G<S<sub>1</sub>, ..,
+ * S<sub>n</sub>></i>,
+ *
+ * Any use of a malformed type gives rise to a static warning.
+ *
+ * Parameters:
+ * 0: the name that is not a type
+ */
+ static const StaticWarningCode NOT_A_TYPE =
+ const StaticWarningCode('NOT_A_TYPE', "{0} is not a type");
+
+ /**
+ * 12.14.2 Binding Actuals to Formals: It is a static warning if <i>m <
+ * h</i> or if <i>m > n</i>.
+ *
+ * Parameters:
+ * 0: the expected number of required arguments
+ * 1: the actual number of positional arguments given
+ *
+ * See [EXTRA_POSITIONAL_ARGUMENTS].
+ */
+ static const StaticWarningCode NOT_ENOUGH_REQUIRED_ARGUMENTS =
+ const StaticWarningCode('NOT_ENOUGH_REQUIRED_ARGUMENTS',
+ "{0} required argument(s) expected, but {1} found");
+
+ /**
+ * 14.3 Parts: It is a static warning if the referenced part declaration
+ * <i>p</i> names a library other than the current library as the library to
+ * which <i>p</i> belongs.
+ *
+ * Parameters:
+ * 0: the name of expected library name
+ * 1: the non-matching actual library name from the "part of" declaration
+ */
+ static const StaticWarningCode PART_OF_DIFFERENT_LIBRARY =
+ const StaticWarningCode('PART_OF_DIFFERENT_LIBRARY',
+ "Expected this library to be part of '{0}', not '{1}'");
+
+ /**
+ * 7.6.2 Factories: It is a static warning if the function type of <i>k'</i>
+ * is not a subtype of the type of <i>k</i>.
+ *
+ * Parameters:
+ * 0: the name of the redirected constructor
+ * 1: the name of the redirecting constructor
+ */
+ static const StaticWarningCode REDIRECT_TO_INVALID_FUNCTION_TYPE =
+ const StaticWarningCode('REDIRECT_TO_INVALID_FUNCTION_TYPE',
+ "The redirected constructor '{0}' has incompatible parameters with '{1}'");
+
+ /**
+ * 7.6.2 Factories: It is a static warning if the function type of <i>k'</i>
+ * is not a subtype of the type of <i>k</i>.
+ *
+ * Parameters:
+ * 0: the name of the redirected constructor return type
+ * 1: the name of the redirecting constructor return type
+ */
+ static const StaticWarningCode REDIRECT_TO_INVALID_RETURN_TYPE =
+ const StaticWarningCode('REDIRECT_TO_INVALID_RETURN_TYPE',
+ "The return type '{0}' of the redirected constructor is not assignable to '{1}'");
+
+ /**
+ * 7.6.2 Factories: It is a static warning if type does not denote a class
+ * accessible in the current scope; if type does denote such a class <i>C</i>
+ * it is a static warning if the referenced constructor (be it <i>type</i> or
+ * <i>type.id</i>) is not a constructor of <i>C</i>.
+ */
+ static const StaticWarningCode REDIRECT_TO_MISSING_CONSTRUCTOR =
+ const StaticWarningCode('REDIRECT_TO_MISSING_CONSTRUCTOR',
+ "The constructor '{0}' could not be found in '{1}'");
+
+ /**
+ * 7.6.2 Factories: It is a static warning if type does not denote a class
+ * accessible in the current scope; if type does denote such a class <i>C</i>
+ * it is a static warning if the referenced constructor (be it <i>type</i> or
+ * <i>type.id</i>) is not a constructor of <i>C</i>.
+ */
+ static const StaticWarningCode REDIRECT_TO_NON_CLASS = const StaticWarningCode(
+ 'REDIRECT_TO_NON_CLASS',
+ "The name '{0}' is not a type and cannot be used in a redirected constructor");
+
+ /**
+ * 13.12 Return: Let <i>f</i> be the function immediately enclosing a return
+ * statement of the form <i>return;</i> It is a static warning if both of the
+ * following conditions hold:
+ * * <i>f</i> is not a generative constructor.
+ * * The return type of <i>f</i> may not be assigned to void.
+ */
+ static const StaticWarningCode RETURN_WITHOUT_VALUE = const StaticWarningCode(
+ 'RETURN_WITHOUT_VALUE',
+ "Missing return value after 'return'",
+ null,
+ false);
+
+ /**
+ * 12.16.3 Static Invocation: It is a static warning if <i>C</i> does not
+ * declare a static method or getter <i>m</i>.
+ *
+ * Parameters:
+ * 0: the name of the instance member
+ */
+ static const StaticWarningCode STATIC_ACCESS_TO_INSTANCE_MEMBER =
+ const StaticWarningCode('STATIC_ACCESS_TO_INSTANCE_MEMBER',
+ "Instance member '{0}' cannot be accessed using static access");
+
+ /**
+ * 13.9 Switch: It is a static warning if the type of <i>e</i> may not be
+ * assigned to the type of <i>e<sub>k</sub></i>.
+ */
+ static const StaticWarningCode SWITCH_EXPRESSION_NOT_ASSIGNABLE =
+ const StaticWarningCode('SWITCH_EXPRESSION_NOT_ASSIGNABLE',
+ "Type '{0}' of the switch expression is not assignable to the type '{1}' of case expressions");
+
+ /**
+ * 15.1 Static Types: It is a static warning to use a deferred type in a type
+ * annotation.
+ *
+ * Parameters:
+ * 0: the name of the type that is deferred and being used in a type
+ * annotation
+ */
+ static const StaticWarningCode TYPE_ANNOTATION_DEFERRED_CLASS =
+ const StaticWarningCode('TYPE_ANNOTATION_DEFERRED_CLASS',
+ "The deferred type '{0}' cannot be used in a declaration, cast or type test");
+
+ /**
+ * 12.31 Type Test: It is a static warning if <i>T</i> does not denote a type
+ * available in the current lexical scope.
+ */
+ static const StaticWarningCode TYPE_TEST_WITH_NON_TYPE = const StaticWarningCode(
+ 'TYPE_TEST_WITH_NON_TYPE',
+ "The name '{0}' is not a type and cannot be used in an 'is' expression");
+
+ /**
+ * 12.31 Type Test: It is a static warning if <i>T</i> does not denote a type
+ * available in the current lexical scope.
+ */
+ static const StaticWarningCode TYPE_TEST_WITH_UNDEFINED_NAME =
+ const StaticWarningCode('TYPE_TEST_WITH_UNDEFINED_NAME',
+ "The name '{0}' is not defined and cannot be used in an 'is' expression");
+
+ /**
+ * 10 Generics: However, a type parameter is considered to be a malformed type
+ * when referenced by a static member.
+ *
+ * 15.1 Static Types: Any use of a malformed type gives rise to a static
+ * warning. A malformed type is then interpreted as dynamic by the static type
+ * checker and the runtime.
+ */
+ static const StaticWarningCode TYPE_PARAMETER_REFERENCED_BY_STATIC =
+ const StaticWarningCode('TYPE_PARAMETER_REFERENCED_BY_STATIC',
+ "Static members cannot reference type parameters of the class");
+
+ /**
+ * 12.16.3 Static Invocation: A static method invocation <i>i</i> has the form
+ * <i>C.m(a<sub>1</sub>, …, a<sub>n</sub>, x<sub>n+1</sub>:
+ * a<sub>n+1</sub>, … x<sub>n+k</sub>: a<sub>n+k</sub>)</i>. It is a
+ * static warning if <i>C</i> does not denote a class in the current scope.
+ *
+ * Parameters:
+ * 0: the name of the undefined class
+ */
+ static const StaticWarningCode UNDEFINED_CLASS =
+ const StaticWarningCode('UNDEFINED_CLASS', "Undefined class '{0}'");
+
+ /**
+ * Same as [UNDEFINED_CLASS], but to catch using "boolean" instead of "bool".
+ */
+ static const StaticWarningCode UNDEFINED_CLASS_BOOLEAN =
+ const StaticWarningCode('UNDEFINED_CLASS_BOOLEAN',
+ "Undefined class 'boolean'; did you mean 'bool'?");
+
+ /**
+ * 12.17 Getter Invocation: It is a static warning if there is no class
+ * <i>C</i> in the enclosing lexical scope of <i>i</i>, or if <i>C</i> does
+ * not declare, implicitly or explicitly, a getter named <i>m</i>.
+ *
+ * Parameters:
+ * 0: the name of the getter
+ * 1: the name of the enclosing type where the getter is being looked for
+ */
+ static const StaticWarningCode UNDEFINED_GETTER =
+ shared_messages.UNDEFINED_GETTER_STATIC_WARNING;
+
+ /**
+ * 12.30 Identifier Reference: It is as static warning if an identifier
+ * expression of the form <i>id</i> occurs inside a top level or static
+ * function (be it function, method, getter, or setter) or variable
+ * initializer and there is no declaration <i>d</i> with name <i>id</i> in the
+ * lexical scope enclosing the expression.
+ *
+ * Parameters:
+ * 0: the name of the identifier
+ */
+ static const StaticWarningCode UNDEFINED_IDENTIFIER =
+ const StaticWarningCode('UNDEFINED_IDENTIFIER', "Undefined name '{0}'");
+
+ /**
+ * If the identifier is 'await', be helpful about it.
+ */
+ static const StaticWarningCode UNDEFINED_IDENTIFIER_AWAIT =
+ const StaticWarningCode('UNDEFINED_IDENTIFIER_AWAIT',
+ "Undefined name 'await'; did you mean to add the 'async' marker to '{0}'?");
+
+ /**
+ * 12.14.2 Binding Actuals to Formals: Furthermore, each <i>q<sub>i</sub></i>,
+ * <i>1<=i<=l</i>, must have a corresponding named parameter in the set
+ * {<i>p<sub>n+1</sub></i> … <i>p<sub>n+k</sub></i>} or a static
+ * warning occurs.
+ *
+ * Parameters:
+ * 0: the name of the requested named parameter
+ */
+ static const StaticWarningCode UNDEFINED_NAMED_PARAMETER =
+ const StaticWarningCode('UNDEFINED_NAMED_PARAMETER',
+ "The named parameter '{0}' is not defined");
+
+ /**
+ * 12.18 Assignment: It is as static warning if an assignment of the form
+ * <i>v = e</i> occurs inside a top level or static function (be it function,
+ * method, getter, or setter) or variable initializer and there is no
+ * declaration <i>d</i> with name <i>v=</i> in the lexical scope enclosing the
+ * assignment.
+ *
+ * 12.18 Assignment: It is a static warning if there is no class <i>C</i> in
+ * the enclosing lexical scope of the assignment, or if <i>C</i> does not
+ * declare, implicitly or explicitly, a setter <i>v=</i>.
+ *
+ * Parameters:
+ * 0: the name of the getter
+ * 1: the name of the enclosing type where the setter is being looked for
+ */
+ static const StaticWarningCode UNDEFINED_SETTER =
+ shared_messages.UNDEFINED_SETTER_STATIC_WARNING;
+
+ /**
+ * 12.16.3 Static Invocation: It is a static warning if <i>C</i> does not
+ * declare a static method or getter <i>m</i>.
+ *
+ * Parameters:
+ * 0: the name of the method
+ * 1: the name of the enclosing type where the method is being looked for
+ */
+ static const StaticWarningCode UNDEFINED_STATIC_METHOD_OR_GETTER =
+ const StaticWarningCode('UNDEFINED_STATIC_METHOD_OR_GETTER',
+ "The static method, getter or setter '{0}' is not defined for the class '{1}'");
+
+ /**
+ * 12.17 Getter Invocation: It is a static warning if there is no class
+ * <i>C</i> in the enclosing lexical scope of <i>i</i>, or if <i>C</i> does
+ * not declare, implicitly or explicitly, a getter named <i>m</i>.
+ *
+ * Parameters:
+ * 0: the name of the getter
+ * 1: the name of the enclosing type where the getter is being looked for
+ */
+ static const StaticWarningCode UNDEFINED_SUPER_GETTER =
+ shared_messages.UNDEFINED_SUPER_GETTER_STATIC_WARNING;
+
+ /**
+ * 12.18 Assignment: It is as static warning if an assignment of the form
+ * <i>v = e</i> occurs inside a top level or static function (be it function,
+ * method, getter, or setter) or variable initializer and there is no
+ * declaration <i>d</i> with name <i>v=</i> in the lexical scope enclosing the
+ * assignment.
+ *
+ * 12.18 Assignment: It is a static warning if there is no class <i>C</i> in
+ * the enclosing lexical scope of the assignment, or if <i>C</i> does not
+ * declare, implicitly or explicitly, a setter <i>v=</i>.
+ *
+ * Parameters:
+ * 0: the name of the getter
+ * 1: the name of the enclosing type where the setter is being looked for
+ */
+ static const StaticWarningCode UNDEFINED_SUPER_SETTER =
+ shared_messages.UNDEFINED_SUPER_SETTER_STATIC_WARNING;
+
+ /**
+ * 7.2 Getters: It is a static warning if the return type of a getter is void.
+ */
+ static const StaticWarningCode VOID_RETURN_FOR_GETTER =
+ const StaticWarningCode('VOID_RETURN_FOR_GETTER',
+ "The return type of the getter must not be 'void'", null, false);
+
+ /**
+ * A flag indicating whether this warning is an error when running with strong
+ * mode enabled.
+ */
+ final bool isStrongModeError;
+
+ /**
+ * Initialize a newly created error code to have the given [name]. The message
+ * associated with the error will be created from the given [message]
+ * template. The correction associated with the error will be created from the
+ * given [correction] template.
+ */
+ const StaticWarningCode(String name, String message,
+ [String correction, this.isStrongModeError = true])
+ : super(name, message, correction);
+
+ @override
+ ErrorSeverity get errorSeverity => ErrorType.STATIC_WARNING.severity;
+
+ @override
+ ErrorType get type => ErrorType.STATIC_WARNING;
+}
+
+/**
+ * This class has Strong Mode specific error codes.
+ *
+ * These error codes tend to use the same message across different severity
+ * levels, so they are grouped for clarity.
+ *
+ * All of these error codes also use the "STRONG_MODE_" prefix in their name.
+ */
+class StrongModeCode extends ErrorCode {
+ static const String _implicitCastMessage =
+ 'Unsound implicit cast from {0} to {1}';
+
+ static const String _unsafeBlockClosureInferenceMessage =
+ 'Unsafe use of block closure in a type-inferred variable outside a '
+ 'function body. Workaround: add a type annotation for `{0}`. See '
+ 'dartbug.com/26947';
+
+ static const String _typeCheckMessage =
+ 'Type check failed: {0} is not of type {1}';
+
+ static const String _invalidOverrideMessage =
+ 'The type of {0}.{1} ({2}) is not a '
+ 'subtype of {3}.{1} ({4}).';
+
+ /**
+ * This is appended to the end of an error message about implicit dynamic.
+ *
+ * The idea is to make sure the user is aware that this error message is the
+ * result of turning on a particular option, and they are free to turn it
+ * back off.
+ */
+ static const String _implicitDynamicTip =
+ ". Either add an explicit type like 'dynamic'"
+ ", or enable implicit-dynamic in your Analyzer options.";
+
+ static const String _inferredTypeMessage = '{0} has inferred type {1}';
+
+ static const StrongModeCode DOWN_CAST_COMPOSITE = const StrongModeCode(
+ ErrorType.STATIC_WARNING, 'DOWN_CAST_COMPOSITE', _implicitCastMessage);
+
+ static const StrongModeCode DOWN_CAST_IMPLICIT = const StrongModeCode(
+ ErrorType.HINT, 'DOWN_CAST_IMPLICIT', _implicitCastMessage);
+
+ static const StrongModeCode DYNAMIC_CAST = const StrongModeCode(
+ ErrorType.HINT, 'DYNAMIC_CAST', _implicitCastMessage);
+
+ static const StrongModeCode ASSIGNMENT_CAST = const StrongModeCode(
+ ErrorType.HINT, 'ASSIGNMENT_CAST', _implicitCastMessage);
+
+ static const StrongModeCode INVALID_PARAMETER_DECLARATION =
+ const StrongModeCode(ErrorType.COMPILE_TIME_ERROR,
+ 'INVALID_PARAMETER_DECLARATION', _typeCheckMessage);
+
+ static const StrongModeCode COULD_NOT_INFER = const StrongModeCode(
+ ErrorType.COMPILE_TIME_ERROR,
+ 'COULD_NOT_INFER',
+ "Could not infer type parameter {0}, {1} must be of type {2}.");
+
+ static const StrongModeCode INFERRED_TYPE = const StrongModeCode(
+ ErrorType.HINT, 'INFERRED_TYPE', _inferredTypeMessage);
+
+ static const StrongModeCode INFERRED_TYPE_LITERAL = const StrongModeCode(
+ ErrorType.HINT, 'INFERRED_TYPE_LITERAL', _inferredTypeMessage);
+
+ static const StrongModeCode INFERRED_TYPE_ALLOCATION = const StrongModeCode(
+ ErrorType.HINT, 'INFERRED_TYPE_ALLOCATION', _inferredTypeMessage);
+
+ static const StrongModeCode INFERRED_TYPE_CLOSURE = const StrongModeCode(
+ ErrorType.HINT, 'INFERRED_TYPE_CLOSURE', _inferredTypeMessage);
+
+ static const StrongModeCode STATIC_TYPE_ERROR = const StrongModeCode(
+ ErrorType.COMPILE_TIME_ERROR,
+ 'STATIC_TYPE_ERROR',
+ 'Type check failed: {0} ({1}) is not of type {2}');
+
+ static const StrongModeCode INVALID_SUPER_INVOCATION = const StrongModeCode(
+ ErrorType.COMPILE_TIME_ERROR,
+ 'INVALID_SUPER_INVOCATION',
+ "super call must be last in an initializer "
+ "list (see https://goo.gl/EY6hDP): {0}");
+
+ static const StrongModeCode NON_GROUND_TYPE_CHECK_INFO = const StrongModeCode(
+ ErrorType.HINT,
+ 'NON_GROUND_TYPE_CHECK_INFO',
+ "Runtime check on non-ground type {0} may throw StrongModeError");
+
+ static const StrongModeCode DYNAMIC_INVOKE = const StrongModeCode(
+ ErrorType.HINT, 'DYNAMIC_INVOKE', '{0} requires a dynamic invoke');
+
+ static const StrongModeCode INVALID_METHOD_OVERRIDE = const StrongModeCode(
+ ErrorType.COMPILE_TIME_ERROR,
+ 'INVALID_METHOD_OVERRIDE',
+ 'Invalid override. $_invalidOverrideMessage');
+
+ static const StrongModeCode INVALID_METHOD_OVERRIDE_FROM_BASE =
+ const StrongModeCode(
+ ErrorType.COMPILE_TIME_ERROR,
+ 'INVALID_METHOD_OVERRIDE_FROM_BASE',
+ 'Base class introduces an invalid override. '
+ '$_invalidOverrideMessage');
+
+ static const StrongModeCode INVALID_METHOD_OVERRIDE_FROM_MIXIN =
+ const StrongModeCode(
+ ErrorType.COMPILE_TIME_ERROR,
+ 'INVALID_METHOD_OVERRIDE_FROM_MIXIN',
+ 'Mixin introduces an invalid override. $_invalidOverrideMessage');
+
+ static const StrongModeCode INVALID_FIELD_OVERRIDE = const StrongModeCode(
+ ErrorType.COMPILE_TIME_ERROR,
+ 'INVALID_FIELD_OVERRIDE',
+ 'Field declaration {3}.{1} cannot be '
+ 'overridden in {0}.');
+
+ static const StrongModeCode IMPLICIT_DYNAMIC_PARAMETER = const StrongModeCode(
+ ErrorType.COMPILE_TIME_ERROR,
+ 'IMPLICIT_DYNAMIC_PARAMETER',
+ "Missing parameter type for '{0}'$_implicitDynamicTip");
+
+ static const StrongModeCode IMPLICIT_DYNAMIC_RETURN = const StrongModeCode(
+ ErrorType.COMPILE_TIME_ERROR,
+ 'IMPLICIT_DYNAMIC_RETURN',
+ "Missing return type for '{0}'$_implicitDynamicTip");
+
+ static const StrongModeCode IMPLICIT_DYNAMIC_VARIABLE = const StrongModeCode(
+ ErrorType.COMPILE_TIME_ERROR,
+ 'IMPLICIT_DYNAMIC_VARIABLE',
+ "Missing variable type for '{0}'$_implicitDynamicTip");
+
+ static const StrongModeCode IMPLICIT_DYNAMIC_FIELD = const StrongModeCode(
+ ErrorType.COMPILE_TIME_ERROR,
+ 'IMPLICIT_DYNAMIC_FIELD',
+ "Missing field type for '{0}'$_implicitDynamicTip");
+
+ static const StrongModeCode IMPLICIT_DYNAMIC_TYPE = const StrongModeCode(
+ ErrorType.COMPILE_TIME_ERROR,
+ 'IMPLICIT_DYNAMIC_TYPE',
+ "Missing type arguments for generic type '{0}'"
+ "$_implicitDynamicTip");
+
+ static const StrongModeCode IMPLICIT_DYNAMIC_LIST_LITERAL =
+ const StrongModeCode(
+ ErrorType.COMPILE_TIME_ERROR,
+ 'IMPLICIT_DYNAMIC_LIST_LITERAL',
+ "Missing type argument for list literal$_implicitDynamicTip");
+
+ static const StrongModeCode IMPLICIT_DYNAMIC_MAP_LITERAL =
+ const StrongModeCode(
+ ErrorType.COMPILE_TIME_ERROR,
+ 'IMPLICIT_DYNAMIC_MAP_LITERAL',
+ 'Missing type arguments for map literal$_implicitDynamicTip');
+
+ static const StrongModeCode IMPLICIT_DYNAMIC_FUNCTION = const StrongModeCode(
+ ErrorType.COMPILE_TIME_ERROR,
+ 'IMPLICIT_DYNAMIC_FUNCTION',
+ "Missing type arguments for generic function '{0}<{1}>'"
+ "$_implicitDynamicTip");
+
+ static const StrongModeCode IMPLICIT_DYNAMIC_METHOD = const StrongModeCode(
+ ErrorType.COMPILE_TIME_ERROR,
+ 'IMPLICIT_DYNAMIC_METHOD',
+ "Missing type arguments for generic method '{0}<{1}>'"
+ "$_implicitDynamicTip");
+
+ static const StrongModeCode IMPLICIT_DYNAMIC_INVOKE = const StrongModeCode(
+ ErrorType.COMPILE_TIME_ERROR,
+ 'IMPLICIT_DYNAMIC_INVOKE',
+ "Missing type arguments for calling generic function type '{0}'"
+ "$_implicitDynamicTip");
+
+ static const StrongModeCode UNSAFE_BLOCK_CLOSURE_INFERENCE =
+ const StrongModeCode(
+ ErrorType.STATIC_WARNING,
+ 'UNSAFE_BLOCK_CLOSURE_INFERENCE',
+ _unsafeBlockClosureInferenceMessage);
+
+ @override
+ final ErrorType type;
+
+ /**
+ * Initialize a newly created error code to have the given [type] and [name].
+ *
+ * The message associated with the error will be created from the given
+ * [message] template. The correction associated with the error will be
+ * created from the optional [correction] template.
+ */
+ const StrongModeCode(ErrorType type, String name, String message,
+ [String correction])
+ : type = type,
+ super('STRONG_MODE_$name', message, correction);
+
+ @override
+ ErrorSeverity get errorSeverity => type.severity;
+}
+
+/**
+ * The error code indicating a marker in code for work that needs to be finished
+ * or revisited.
+ */
+class TodoCode extends ErrorCode {
+ /**
+ * The single enum of TodoCode.
+ */
+ static const TodoCode TODO = const TodoCode('TODO');
+
+ /**
+ * This matches the two common Dart task styles
+ *
+ * * TODO:
+ * * TODO(username):
+ *
+ * As well as
+ * * TODO
+ *
+ * But not
+ * * todo
+ * * TODOS
+ */
+ static RegExp TODO_REGEX =
+ new RegExp("([\\s/\\*])((TODO[^\\w\\d][^\\r\\n]*)|(TODO:?\$))");
+
+ /**
+ * Initialize a newly created error code to have the given [name].
+ */
+ const TodoCode(String name) : super(name, "{0}");
+
+ @override
+ ErrorSeverity get errorSeverity => ErrorSeverity.INFO;
+
+ @override
+ ErrorType get type => ErrorType.TODO;
+}
diff --git a/pkg/analyzer/lib/src/error/pending_error.dart b/pkg/analyzer/lib/src/error/pending_error.dart
index 6562166..d0c9211 100644
--- a/pkg/analyzer/lib/src/error/pending_error.dart
+++ b/pkg/analyzer/lib/src/error/pending_error.dart
@@ -6,8 +6,9 @@
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/element/element.dart';
+import 'package:analyzer/error/error.dart';
+import 'package:analyzer/src/error/codes.dart';
import 'package:analyzer/src/generated/constant.dart';
-import 'package:analyzer/src/generated/error.dart';
import 'package:analyzer/src/generated/source.dart';
/**
diff --git a/pkg/analyzer/lib/src/generated/constant.dart b/pkg/analyzer/lib/src/generated/constant.dart
index 0bd0f84..6dd6c16 100644
--- a/pkg/analyzer/lib/src/generated/constant.dart
+++ b/pkg/analyzer/lib/src/generated/constant.dart
@@ -6,11 +6,11 @@
import 'package:analyzer/context/declared_variables.dart';
import 'package:analyzer/dart/ast/ast.dart';
+import 'package:analyzer/error/listener.dart';
import 'package:analyzer/src/dart/constant/evaluation.dart';
import 'package:analyzer/src/dart/constant/value.dart';
import 'package:analyzer/src/generated/engine.dart';
import 'package:analyzer/src/generated/engine.dart' show RecordingErrorListener;
-import 'package:analyzer/src/generated/error.dart';
import 'package:analyzer/src/generated/resolver.dart' show TypeProvider;
import 'package:analyzer/src/generated/source.dart' show Source;
import 'package:analyzer/src/generated/type_system.dart'
diff --git a/pkg/analyzer/lib/src/generated/element_resolver.dart b/pkg/analyzer/lib/src/generated/element_resolver.dart
index e70c1d8..ba6c884 100644
--- a/pkg/analyzer/lib/src/generated/element_resolver.dart
+++ b/pkg/analyzer/lib/src/generated/element_resolver.dart
@@ -11,6 +11,7 @@
import 'package:analyzer/dart/ast/visitor.dart';
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/type.dart';
+import 'package:analyzer/error/error.dart';
import 'package:analyzer/src/dart/ast/ast.dart'
show
ChildEntities,
@@ -20,8 +21,8 @@
import 'package:analyzer/src/dart/ast/token.dart';
import 'package:analyzer/src/dart/element/element.dart';
import 'package:analyzer/src/dart/element/type.dart';
+import 'package:analyzer/src/error/codes.dart';
import 'package:analyzer/src/generated/engine.dart';
-import 'package:analyzer/src/generated/error.dart';
import 'package:analyzer/src/generated/resolver.dart';
/**
@@ -419,7 +420,7 @@
@override
Object visitFieldFormalParameter(FieldFormalParameter node) {
- _resolveMetadataForParameter(node.element, node);
+ _resolveMetadataForParameter(node);
return super.visitFieldFormalParameter(node);
}
@@ -463,7 +464,7 @@
@override
Object visitFunctionTypedFormalParameter(FunctionTypedFormalParameter node) {
- _resolveMetadataForParameter(node.element, node);
+ _resolveMetadataForParameter(node);
return null;
}
@@ -1055,7 +1056,7 @@
@override
Object visitSimpleFormalParameter(SimpleFormalParameter node) {
- _resolveMetadataForParameter(node.element, node);
+ _resolveMetadataForParameter(node);
return null;
}
@@ -2270,8 +2271,7 @@
* Given a [node] that can have annotations associated with it, resolve the
* annotations in the element model representing annotations to the node.
*/
- void _resolveMetadataForParameter(
- Element element, NormalFormalParameter node) {
+ void _resolveMetadataForParameter(NormalFormalParameter node) {
_resolveAnnotations(node.metadata);
}
diff --git a/pkg/analyzer/lib/src/generated/engine.dart b/pkg/analyzer/lib/src/generated/engine.dart
index c3093a2..d4064c4 100644
--- a/pkg/analyzer/lib/src/generated/engine.dart
+++ b/pkg/analyzer/lib/src/generated/engine.dart
@@ -10,6 +10,7 @@
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/ast/visitor.dart';
import 'package:analyzer/dart/element/element.dart';
+import 'package:analyzer/error/error.dart';
import 'package:analyzer/exception/exception.dart';
import 'package:analyzer/instrumentation/instrumentation.dart';
import 'package:analyzer/plugin/resolver_provider.dart';
@@ -18,7 +19,6 @@
import 'package:analyzer/src/context/cache.dart';
import 'package:analyzer/src/context/context.dart';
import 'package:analyzer/src/generated/constant.dart';
-import 'package:analyzer/src/generated/error.dart';
import 'package:analyzer/src/generated/java_core.dart';
import 'package:analyzer/src/generated/java_engine.dart';
import 'package:analyzer/src/generated/resolver.dart';
@@ -35,6 +35,8 @@
import 'package:plugin/manager.dart';
import 'package:plugin/plugin.dart';
+export 'package:analyzer/error/listener.dart' show RecordingErrorListener;
+
/**
* Used by [AnalysisOptions] to allow function bodies to be analyzed in some
* sources but not others.
@@ -2363,66 +2365,6 @@
}
/**
- * An error listener that will record the errors that are reported to it in a
- * way that is appropriate for caching those errors within an analysis context.
- */
-class RecordingErrorListener implements AnalysisErrorListener {
- /**
- * A map of sets containing the errors that were collected, keyed by each
- * source.
- */
- Map<Source, HashSet<AnalysisError>> _errors =
- new HashMap<Source, HashSet<AnalysisError>>();
-
- /**
- * Return the errors collected by the listener.
- */
- List<AnalysisError> get errors {
- int numEntries = _errors.length;
- if (numEntries == 0) {
- return AnalysisError.NO_ERRORS;
- }
- List<AnalysisError> resultList = new List<AnalysisError>();
- for (HashSet<AnalysisError> errors in _errors.values) {
- resultList.addAll(errors);
- }
- return resultList;
- }
-
- /**
- * Add all of the errors recorded by the given [listener] to this listener.
- */
- void addAll(RecordingErrorListener listener) {
- for (AnalysisError error in listener.errors) {
- onError(error);
- }
- }
-
- /**
- * Return the errors collected by the listener for the given [source].
- */
- List<AnalysisError> getErrorsForSource(Source source) {
- HashSet<AnalysisError> errorsForSource = _errors[source];
- if (errorsForSource == null) {
- return AnalysisError.NO_ERRORS;
- } else {
- return new List.from(errorsForSource);
- }
- }
-
- @override
- void onError(AnalysisError error) {
- Source source = error.source;
- HashSet<AnalysisError> errorsForSource = _errors[source];
- if (_errors[source] == null) {
- errorsForSource = new HashSet<AnalysisError>();
- _errors[source] = errorsForSource;
- }
- errorsForSource.add(error);
- }
-}
-
-/**
* An visitor that removes any resolution information from an AST structure when
* used to visit that structure.
*/
diff --git a/pkg/analyzer/lib/src/generated/error.dart b/pkg/analyzer/lib/src/generated/error.dart
index 630c910..b04e50b 100644
--- a/pkg/analyzer/lib/src/generated/error.dart
+++ b/pkg/analyzer/lib/src/generated/error.dart
@@ -2,6148 +2,11 @@
// 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.
+@deprecated
library analyzer.src.generated.error;
-import 'dart:collection';
-
-import 'package:analyzer/dart/ast/ast.dart' show AstNode;
-import 'package:analyzer/dart/ast/token.dart';
-import 'package:analyzer/dart/element/element.dart';
-import 'package:analyzer/dart/element/type.dart';
-import 'package:analyzer/source/error_processor.dart';
-import 'package:analyzer/src/dart/element/element.dart';
-import 'package:analyzer/src/dart/element/type.dart';
-import 'package:analyzer/src/dart/scanner/scanner.dart' show ScannerErrorCode;
-import 'package:analyzer/src/generated/generated/shared_messages.dart'
- as shared_messages;
-import 'package:analyzer/src/generated/java_core.dart';
-import 'package:analyzer/src/generated/parser.dart' show ParserErrorCode;
-import 'package:analyzer/src/generated/source.dart';
-import 'package:analyzer/src/task/model.dart';
-import 'package:analyzer/task/model.dart';
-import 'package:source_span/source_span.dart';
-
-/**
- * The descriptor used to associate error processors with analysis contexts in
- * configuration data.
- */
-final ListResultDescriptor<ErrorProcessor> CONFIGURED_ERROR_PROCESSORS =
- new ListResultDescriptorImpl('configured.errors', const <ErrorProcessor>[]);
-
-/**
- * An error discovered during the analysis of some Dart code.
- *
- * See [AnalysisErrorListener].
- */
-class AnalysisError {
- /**
- * An empty array of errors used when no errors are expected.
- */
- static const List<AnalysisError> NO_ERRORS = const <AnalysisError>[];
-
- /**
- * A [Comparator] that sorts by the name of the file that the [AnalysisError]
- * was found.
- */
- static Comparator<AnalysisError> FILE_COMPARATOR =
- (AnalysisError o1, AnalysisError o2) =>
- o1.source.shortName.compareTo(o2.source.shortName);
-
- /**
- * A [Comparator] that sorts error codes first by their severity (errors
- * first, warnings second), and then by the error code type.
- */
- static Comparator<AnalysisError> ERROR_CODE_COMPARATOR =
- (AnalysisError o1, AnalysisError o2) {
- ErrorCode errorCode1 = o1.errorCode;
- ErrorCode errorCode2 = o2.errorCode;
- ErrorSeverity errorSeverity1 = errorCode1.errorSeverity;
- ErrorSeverity errorSeverity2 = errorCode2.errorSeverity;
- if (errorSeverity1 == errorSeverity2) {
- ErrorType errorType1 = errorCode1.type;
- ErrorType errorType2 = errorCode2.type;
- return errorType1.compareTo(errorType2);
- } else {
- return errorSeverity2.compareTo(errorSeverity1);
- }
- };
-
- /**
- * The error code associated with the error.
- */
- final ErrorCode errorCode;
-
- /**
- * The localized error message.
- */
- String _message;
-
- /**
- * The correction to be displayed for this error, or `null` if there is no
- * correction information for this error.
- */
- String _correction;
-
- /**
- * The source in which the error occurred, or `null` if unknown.
- */
- final Source source;
-
- /**
- * The character offset from the beginning of the source (zero based) where
- * the error occurred.
- */
- int offset = 0;
-
- /**
- * The number of characters from the offset to the end of the source which
- * encompasses the compilation error.
- */
- int length = 0;
-
- /**
- * A flag indicating whether this error can be shown to be a non-issue because
- * of the result of type propagation.
- */
- bool isStaticOnly = false;
-
- /**
- * Initialize a newly created analysis error. The error is associated with the
- * given [source] and is located at the given [offset] with the given
- * [length]. The error will have the given [errorCode] and the list of
- * [arguments] will be used to complete the message.
- */
- AnalysisError(this.source, this.offset, this.length, this.errorCode,
- [List<Object> arguments]) {
- this._message = formatList(errorCode.message, arguments);
- String correctionTemplate = errorCode.correction;
- if (correctionTemplate != null) {
- this._correction = formatList(correctionTemplate, arguments);
- }
- }
-
- /**
- * Initialize a newly created analysis error with given values.
- */
- AnalysisError.forValues(this.source, this.offset, this.length, this.errorCode,
- this._message, this._correction);
-
- /**
- * Return the template used to create the correction to be displayed for this
- * error, or `null` if there is no correction information for this error. The
- * correction should indicate how the user can fix the error.
- */
- String get correction => _correction;
-
- @override
- int get hashCode {
- int hashCode = offset;
- hashCode ^= (_message != null) ? _message.hashCode : 0;
- hashCode ^= (source != null) ? source.hashCode : 0;
- return hashCode;
- }
-
- /**
- * Return the message to be displayed for this error. The message should
- * indicate what is wrong and why it is wrong.
- */
- String get message => _message;
-
- @override
- bool operator ==(Object other) {
- if (identical(other, this)) {
- return true;
- }
- // prepare other AnalysisError
- if (other is AnalysisError) {
- // Quick checks.
- if (!identical(errorCode, other.errorCode)) {
- return false;
- }
- if (offset != other.offset || length != other.length) {
- return false;
- }
- if (isStaticOnly != other.isStaticOnly) {
- return false;
- }
- // Deep checks.
- if (_message != other._message) {
- return false;
- }
- if (source != other.source) {
- return false;
- }
- // OK
- return true;
- }
- return false;
- }
-
- /**
- * Return the value of the given [property], or `null` if the given property
- * is not defined for this error.
- */
- Object/*=V*/ getProperty/*<V>*/(ErrorProperty/*<V>*/ property) => null;
-
- @override
- String toString() {
- StringBuffer buffer = new StringBuffer();
- buffer.write((source != null) ? source.fullName : "<unknown source>");
- buffer.write("(");
- buffer.write(offset);
- buffer.write("..");
- buffer.write(offset + length - 1);
- buffer.write("): ");
- //buffer.write("(" + lineNumber + ":" + columnNumber + "): ");
- buffer.write(_message);
- return buffer.toString();
- }
-
- /**
- * Merge all of the errors in the lists in the given list of [errorLists] into
- * a single list of errors.
- */
- static List<AnalysisError> mergeLists(List<List<AnalysisError>> errorLists) {
- Set<AnalysisError> errors = new HashSet<AnalysisError>();
- for (List<AnalysisError> errorList in errorLists) {
- errors.addAll(errorList);
- }
- return errors.toList();
- }
-}
-
-/**
- * An object that listen for [AnalysisError]s being produced by the analysis
- * engine.
- */
-abstract class AnalysisErrorListener {
- /**
- * An error listener that ignores errors that are reported to it.
- */
- static final AnalysisErrorListener NULL_LISTENER =
- new AnalysisErrorListener_NULL_LISTENER();
-
- /**
- * This method is invoked when an [error] has been found by the analysis
- * engine.
- */
- void onError(AnalysisError error);
-}
-
-/**
- * An [AnalysisErrorListener] that ignores error.
- */
-class AnalysisErrorListener_NULL_LISTENER implements AnalysisErrorListener {
- @override
- void onError(AnalysisError event) {
- // Ignore errors
- }
-}
-
-/**
- * An [AnalysisError] that can have arbitrary properties associated with it.
- */
-class AnalysisErrorWithProperties extends AnalysisError {
- /**
- * The properties associated with this error.
- */
- HashMap<ErrorProperty, Object> _propertyMap =
- new HashMap<ErrorProperty, Object>();
-
- /**
- * Initialize a newly created analysis error. The error is associated with the
- * given [source] and is located at the given [offset] with the given
- * [length]. The error will have the given [errorCode] and the list of
- * [arguments] will be used to complete the message.
- */
- AnalysisErrorWithProperties(
- Source source, int offset, int length, ErrorCode errorCode,
- [List<Object> arguments])
- : super(source, offset, length, errorCode, arguments);
-
- @override
- Object/*=V*/ getProperty/*<V>*/(ErrorProperty/*<V>*/ property) =>
- _propertyMap[property] as Object/*=V*/;
-
- /**
- * Set the value of the given [property] to the given [value]. Using a value
- * of `null` will effectively remove the property from this error.
- */
- void setProperty/*<V>*/(ErrorProperty/*<V>*/ property, Object/*=V*/ value) {
- _propertyMap[property] = value;
- }
-}
-
-/**
- * The error codes used for errors in analysis options files. The convention for
- * this class is for the name of the error code to indicate the problem that
- * caused the error to be generated and for the error message to explain what is
- * wrong and, when appropriate, how the problem can be corrected.
- */
-class AnalysisOptionsErrorCode extends ErrorCode {
- /**
- * An error code indicating that there is a syntactic error in the file.
- *
- * Parameters:
- * 0: the error message from the parse error
- */
- static const AnalysisOptionsErrorCode PARSE_ERROR =
- const AnalysisOptionsErrorCode('PARSE_ERROR', '{0}');
-
- /**
- * Initialize a newly created error code to have the given [name].
- */
- const AnalysisOptionsErrorCode(String name, String message,
- [String correction])
- : super(name, message, correction);
-
- @override
- ErrorSeverity get errorSeverity => ErrorSeverity.ERROR;
-
- @override
- ErrorType get type => ErrorType.COMPILE_TIME_ERROR;
-}
-
-/**
- * The error codes used for warnings in analysis options files. The convention
- * for this class is for the name of the error code to indicate the problem that
- * caused the error to be generated and for the error message to explain what is
- * wrong and, when appropriate, how the problem can be corrected.
- */
-class AnalysisOptionsWarningCode extends ErrorCode {
- /**
- * An error code indicating that a plugin is being configured with an
- * unsupported option and legal options are provided.
- *
- * Parameters:
- * 0: the plugin name
- * 1: the unsupported option key
- * 2: legal values
- */
- static const AnalysisOptionsWarningCode UNSUPPORTED_OPTION_WITH_LEGAL_VALUES =
- const AnalysisOptionsWarningCode('UNSUPPORTED_OPTION_WITH_LEGAL_VALUES',
- "The option '{1}' is not supported by {0}, supported values are {2}");
-
- /**
- * An error code indicating that a plugin is being configured with an
- * unsupported option where there is just one legal value.
- *
- * Parameters:
- * 0: the plugin name
- * 1: the unsupported option key
- * 2: the legal value
- */
- static const AnalysisOptionsWarningCode UNSUPPORTED_OPTION_WITH_LEGAL_VALUE =
- const AnalysisOptionsWarningCode('UNSUPPORTED_OPTION_WITH_LEGAL_VALUE',
- "The option '{1}' is not supported by {0}, did you mean {2}?");
-
- /**
- * An error code indicating that an option entry is being configured with an
- * unsupported value.
- *
- * Parameters:
- * 0: the option name
- * 1: the unsupported value
- * 2: legal values
- */
- static const AnalysisOptionsWarningCode UNSUPPORTED_VALUE =
- const AnalysisOptionsWarningCode('UNSUPPORTED_VALUE',
- "The value '{1}' is not supported by {0}, legal values are {2}");
-
- /**
- * An error code indicating that an unrecognized error code is being used to
- * specify an error filter.
- *
- * Parameters:
- * 0: the unrecognized error code
- */
- static const AnalysisOptionsWarningCode UNRECOGNIZED_ERROR_CODE =
- const AnalysisOptionsWarningCode(
- 'UNRECOGNIZED_ERROR_CODE', "'{0}' is not a recognized error code");
-
- /**
- * Initialize a newly created warning code to have the given [name].
- */
- const AnalysisOptionsWarningCode(String name, String message,
- [String correction])
- : super(name, message, correction);
-
- @override
- ErrorSeverity get errorSeverity => ErrorSeverity.WARNING;
-
- @override
- ErrorType get type => ErrorType.STATIC_WARNING;
-}
-
-/**
- * An [AnalysisErrorListener] that keeps track of whether any error has been
- * reported to it.
- */
-class BooleanErrorListener implements AnalysisErrorListener {
- /**
- * A flag indicating whether an error has been reported to this listener.
- */
- bool _errorReported = false;
-
- /**
- * Return `true` if an error has been reported to this listener.
- */
- bool get errorReported => _errorReported;
-
- @override
- void onError(AnalysisError error) {
- _errorReported = true;
- }
-}
-
-/**
- * The error codes used for compile time errors caused by constant evaluation
- * that would throw an exception when run in checked mode. The client of the
- * analysis engine is responsible for determining how these errors should be
- * presented to the user (for example, a command-line compiler might elect to
- * treat these errors differently depending whether it is compiling it "checked"
- * mode).
- */
-class CheckedModeCompileTimeErrorCode extends ErrorCode {
- // TODO(paulberry): improve the text of these error messages so that it's
- // clear to the user that the error is coming from constant evaluation (and
- // hence the constant needs to be a subtype of the annotated type) as opposed
- // to static type analysis (which only requires that the two types be
- // assignable). Also consider populating the "correction" field for these
- // errors.
-
- /**
- * 12.11.2 Const: It is a compile-time error if evaluation of a constant
- * object results in an uncaught exception being thrown.
- */
- static const CheckedModeCompileTimeErrorCode
- CONST_CONSTRUCTOR_FIELD_TYPE_MISMATCH =
- const CheckedModeCompileTimeErrorCode(
- 'CONST_CONSTRUCTOR_FIELD_TYPE_MISMATCH',
- "The object type '{0}' cannot be assigned to the field '{1}', which has type '{2}'");
-
- /**
- * 12.11.2 Const: It is a compile-time error if evaluation of a constant
- * object results in an uncaught exception being thrown.
- */
- static const CheckedModeCompileTimeErrorCode
- CONST_CONSTRUCTOR_PARAM_TYPE_MISMATCH =
- const CheckedModeCompileTimeErrorCode(
- 'CONST_CONSTRUCTOR_PARAM_TYPE_MISMATCH',
- "The object type '{0}' cannot be assigned to a parameter of type '{1}'");
-
- /**
- * 7.6.1 Generative Constructors: In checked mode, it is a dynamic type error
- * if o is not <b>null</b> and the interface of the class of <i>o</i> is not a
- * subtype of the static type of the field <i>v</i>.
- *
- * 12.11.2 Const: It is a compile-time error if evaluation of a constant
- * object results in an uncaught exception being thrown.
- *
- * Parameters:
- * 0: the name of the type of the initializer expression
- * 1: the name of the type of the field
- */
- static const CheckedModeCompileTimeErrorCode
- CONST_FIELD_INITIALIZER_NOT_ASSIGNABLE =
- const CheckedModeCompileTimeErrorCode(
- 'CONST_FIELD_INITIALIZER_NOT_ASSIGNABLE',
- "The initializer type '{0}' cannot be assigned to the field type '{1}'");
-
- /**
- * 12.6 Lists: A run-time list literal <<i>E</i>> [<i>e<sub>1</sub></i>
- * ... <i>e<sub>n</sub></i>] is evaluated as follows:
- * * The operator []= is invoked on <i>a</i> with first argument <i>i</i> and
- * second argument <i>o<sub>i+1</sub></i><i>, 1 <= i <= n</i>
- *
- * 12.14.2 Binding Actuals to Formals: Let <i>T<sub>i</sub></i> be the static
- * type of <i>a<sub>i</sub></i>, let <i>S<sub>i</sub></i> be the type of
- * <i>p<sub>i</sub>, 1 <= i <= n+k</i> and let <i>S<sub>q</sub></i> be
- * the type of the named parameter <i>q</i> of <i>f</i>. It is a static
- * warning if <i>T<sub>j</sub></i> may not be assigned to <i>S<sub>j</sub>,
- * 1 <= j <= m</i>.
- */
- static const CheckedModeCompileTimeErrorCode
- LIST_ELEMENT_TYPE_NOT_ASSIGNABLE = const CheckedModeCompileTimeErrorCode(
- 'LIST_ELEMENT_TYPE_NOT_ASSIGNABLE',
- "The element type '{0}' cannot be assigned to the list type '{1}'");
-
- /**
- * 12.7 Map: A run-time map literal <<i>K</i>, <i>V</i>>
- * [<i>k<sub>1</sub></i> : <i>e<sub>1</sub></i> ... <i>k<sub>n</sub></i> :
- * <i>e<sub>n</sub></i>] is evaluated as follows:
- * * The operator []= is invoked on <i>m</i> with first argument
- * <i>k<sub>i</sub></i> and second argument <i>e<sub>i</sub></i><i>, 1 <=
- * i <= n</i>
- *
- * 12.14.2 Binding Actuals to Formals: Let <i>T<sub>i</sub></i> be the static
- * type of <i>a<sub>i</sub></i>, let <i>S<sub>i</sub></i> be the type of
- * <i>p<sub>i</sub>, 1 <= i <= n+k</i> and let <i>S<sub>q</sub></i> be
- * the type of the named parameter <i>q</i> of <i>f</i>. It is a static
- * warning if <i>T<sub>j</sub></i> may not be assigned to <i>S<sub>j</sub>, 1
- * <= j <= m</i>.
- */
- static const CheckedModeCompileTimeErrorCode MAP_KEY_TYPE_NOT_ASSIGNABLE =
- const CheckedModeCompileTimeErrorCode('MAP_KEY_TYPE_NOT_ASSIGNABLE',
- "The element type '{0}' cannot be assigned to the map key type '{1}'");
-
- /**
- * 12.7 Map: A run-time map literal <<i>K</i>, <i>V</i>>
- * [<i>k<sub>1</sub></i> : <i>e<sub>1</sub></i> ... <i>k<sub>n</sub></i> :
- * <i>e<sub>n</sub></i>] is evaluated as follows:
- * * The operator []= is invoked on <i>m</i> with first argument
- * <i>k<sub>i</sub></i> and second argument <i>e<sub>i</sub></i><i>, 1 <=
- * i <= n</i>
- *
- * 12.14.2 Binding Actuals to Formals: Let <i>T<sub>i</sub></i> be the static
- * type of <i>a<sub>i</sub></i>, let <i>S<sub>i</sub></i> be the type of
- * <i>p<sub>i</sub>, 1 <= i <= n+k</i> and let <i>S<sub>q</sub></i> be
- * the type of the named parameter <i>q</i> of <i>f</i>. It is a static
- * warning if <i>T<sub>j</sub></i> may not be assigned to <i>S<sub>j</sub>, 1
- * <= j <= m</i>.
- */
- static const CheckedModeCompileTimeErrorCode MAP_VALUE_TYPE_NOT_ASSIGNABLE =
- const CheckedModeCompileTimeErrorCode('MAP_VALUE_TYPE_NOT_ASSIGNABLE',
- "The element type '{0}' cannot be assigned to the map value type '{1}'");
-
- /**
- * 12.11.2 Const: It is a compile-time error if evaluation of a constant
- * object results in an uncaught exception being thrown.
- */
- static const CheckedModeCompileTimeErrorCode VARIABLE_TYPE_MISMATCH =
- const CheckedModeCompileTimeErrorCode('VARIABLE_TYPE_MISMATCH',
- "The object type '{0}' cannot be assigned to a variable of type '{1}'");
-
- /**
- * Initialize a newly created error code to have the given [name]. The message
- * associated with the error will be created from the given [message]
- * template. The correction associated with the error will be created from the
- * given [correction] template.
- */
- const CheckedModeCompileTimeErrorCode(String name, String message,
- [String correction])
- : super(name, message, correction);
-
- @override
- ErrorSeverity get errorSeverity =>
- ErrorType.CHECKED_MODE_COMPILE_TIME_ERROR.severity;
-
- @override
- ErrorType get type => ErrorType.CHECKED_MODE_COMPILE_TIME_ERROR;
-}
-
-/**
- * The error codes used for compile time errors. The convention for this class
- * is for the name of the error code to indicate the problem that caused the
- * error to be generated and for the error message to explain what is wrong and,
- * when appropriate, how the problem can be corrected.
- */
-class CompileTimeErrorCode extends ErrorCode {
- /**
- * Enum proposal: It is also a compile-time error to explicitly instantiate an
- * enum via 'new' or 'const' or to access its private fields.
- */
- static const CompileTimeErrorCode ACCESS_PRIVATE_ENUM_FIELD =
- const CompileTimeErrorCode('ACCESS_PRIVATE_ENUM_FIELD',
- "The private fields of an enum cannot be accessed, even within the same library");
-
- /**
- * 14.2 Exports: It is a compile-time error if a name <i>N</i> is re-exported
- * by a library <i>L</i> and <i>N</i> is introduced into the export namespace
- * of <i>L</i> by more than one export, unless each all exports refer to same
- * declaration for the name N.
- *
- * Parameters:
- * 0: the name of the ambiguous element
- * 1: the name of the first library that the type is found
- * 2: the name of the second library that the type is found
- */
- static const CompileTimeErrorCode AMBIGUOUS_EXPORT =
- const CompileTimeErrorCode('AMBIGUOUS_EXPORT',
- "The name '{0}' is defined in the libraries '{1}' and '{2}'");
-
- /**
- * 15 Metadata: The constant expression given in an annotation is type checked
- * and evaluated in the scope surrounding the declaration being annotated.
- *
- * 12.11.2 Const: It is a compile-time error if <i>T</i> is not a class
- * accessible in the current scope, optionally followed by type arguments.
- *
- * 12.11.2 Const: If <i>e</i> is of the form <i>const T.id(a<sub>1</sub>,
- * …, a<sub>n</sub>, x<sub>n+1</sub>: a<sub>n+1</sub>, …
- * x<sub>n+k</sub>: a<sub>n+k</sub>)</i> it is a compile-time error if
- * <i>T</i> is not a class accessible in the current scope, optionally
- * followed by type arguments.
- *
- * Parameters:
- * 0: the name of the non-type element
- */
- static const CompileTimeErrorCode ANNOTATION_WITH_NON_CLASS =
- const CompileTimeErrorCode(
- 'ANNOTATION_WITH_NON_CLASS', "The name '{0}' is not a class");
-
- /**
- * 12.33 Argument Definition Test: It is a compile time error if <i>v</i> does
- * not denote a formal parameter.
- *
- * Parameters:
- * 0: the name of the identifier in the argument definition test that is not a
- * parameter
- */
- static const CompileTimeErrorCode ARGUMENT_DEFINITION_TEST_NON_PARAMETER =
- const CompileTimeErrorCode(
- 'ARGUMENT_DEFINITION_TEST_NON_PARAMETER', "'{0}' is not a parameter");
-
- /**
- * ?? Asynchronous For-in: It is a compile-time error if an asynchronous
- * for-in statement appears inside a synchronous function.
- */
- static const CompileTimeErrorCode ASYNC_FOR_IN_WRONG_CONTEXT =
- const CompileTimeErrorCode('ASYNC_FOR_IN_WRONG_CONTEXT',
- "The asynchronous for-in can only be used in a function marked with async or async*");
-
- /**
- * ??: It is a compile-time error if the function immediately enclosing a is
- * not declared asynchronous.
- */
- static const CompileTimeErrorCode AWAIT_IN_WRONG_CONTEXT =
- const CompileTimeErrorCode('AWAIT_IN_WRONG_CONTEXT',
- "The await expression can only be used in a function marked as async or async*");
-
- /**
- * 12.30 Identifier Reference: It is a compile-time error to use a built-in
- * identifier other than dynamic as a type annotation.
- */
- static const CompileTimeErrorCode BUILT_IN_IDENTIFIER_AS_TYPE =
- const CompileTimeErrorCode('BUILT_IN_IDENTIFIER_AS_TYPE',
- "The built-in identifier '{0}' cannot be used as a type");
-
- /**
- * 12.30 Identifier Reference: It is a compile-time error if a built-in
- * identifier is used as the declared name of a class, type parameter or type
- * alias.
- */
- static const CompileTimeErrorCode BUILT_IN_IDENTIFIER_AS_TYPE_NAME =
- const CompileTimeErrorCode('BUILT_IN_IDENTIFIER_AS_TYPE_NAME',
- "The built-in identifier '{0}' cannot be used as a type name");
-
- /**
- * 12.30 Identifier Reference: It is a compile-time error if a built-in
- * identifier is used as the declared name of a class, type parameter or type
- * alias.
- */
- static const CompileTimeErrorCode BUILT_IN_IDENTIFIER_AS_TYPEDEF_NAME =
- const CompileTimeErrorCode('BUILT_IN_IDENTIFIER_AS_TYPEDEF_NAME',
- "The built-in identifier '{0}' cannot be used as a type alias name");
-
- /**
- * 12.30 Identifier Reference: It is a compile-time error if a built-in
- * identifier is used as the declared name of a class, type parameter or type
- * alias.
- */
- static const CompileTimeErrorCode BUILT_IN_IDENTIFIER_AS_TYPE_PARAMETER_NAME =
- const CompileTimeErrorCode('BUILT_IN_IDENTIFIER_AS_TYPE_PARAMETER_NAME',
- "The built-in identifier '{0}' cannot be used as a type parameter name");
-
- /**
- * 13.9 Switch: It is a compile-time error if the class <i>C</i> implements
- * the operator <i>==</i>.
- */
- static const CompileTimeErrorCode CASE_EXPRESSION_TYPE_IMPLEMENTS_EQUALS =
- const CompileTimeErrorCode('CASE_EXPRESSION_TYPE_IMPLEMENTS_EQUALS',
- "The switch case expression type '{0}' cannot override the == operator");
-
- /**
- * 12.1 Constants: It is a compile-time error if evaluation of a compile-time
- * constant would raise
- * an exception.
- */
- static const CompileTimeErrorCode COMPILE_TIME_CONSTANT_RAISES_EXCEPTION =
- const CompileTimeErrorCode('COMPILE_TIME_CONSTANT_RAISES_EXCEPTION', "");
-
- /**
- * 7.2 Getters: It is a compile-time error if a class has both a getter and a
- * method with the same name. This restriction holds regardless of whether the
- * getter is defined explicitly or implicitly, or whether the getter or the
- * method are inherited or not.
- */
- static const CompileTimeErrorCode CONFLICTING_GETTER_AND_METHOD =
- const CompileTimeErrorCode('CONFLICTING_GETTER_AND_METHOD',
- "Class '{0}' cannot have both getter '{1}.{2}' and method with the same name");
-
- /**
- * 7.2 Getters: It is a compile-time error if a class has both a getter and a
- * method with the same name. This restriction holds regardless of whether the
- * getter is defined explicitly or implicitly, or whether the getter or the
- * method are inherited or not.
- */
- static const CompileTimeErrorCode CONFLICTING_METHOD_AND_GETTER =
- const CompileTimeErrorCode('CONFLICTING_METHOD_AND_GETTER',
- "Class '{0}' cannot have both method '{1}.{2}' and getter with the same name");
-
- /**
- * 7.6 Constructors: A constructor name always begins with the name of its
- * immediately enclosing class, and may optionally be followed by a dot and an
- * identifier <i>id</i>. It is a compile-time error if <i>id</i> is the name
- * of a member declared in the immediately enclosing class.
- */
- static const CompileTimeErrorCode CONFLICTING_CONSTRUCTOR_NAME_AND_FIELD =
- const CompileTimeErrorCode('CONFLICTING_CONSTRUCTOR_NAME_AND_FIELD',
- "'{0}' cannot be used to name a constructor and a field in this class");
-
- /**
- * 7.6 Constructors: A constructor name always begins with the name of its
- * immediately enclosing class, and may optionally be followed by a dot and an
- * identifier <i>id</i>. It is a compile-time error if <i>id</i> is the name
- * of a member declared in the immediately enclosing class.
- */
- static const CompileTimeErrorCode CONFLICTING_CONSTRUCTOR_NAME_AND_METHOD =
- const CompileTimeErrorCode('CONFLICTING_CONSTRUCTOR_NAME_AND_METHOD',
- "'{0}' cannot be used to name a constructor and a method in this class");
-
- /**
- * 7. Classes: It is a compile time error if a generic class declares a type
- * variable with the same name as the class or any of its members or
- * constructors.
- */
- static const CompileTimeErrorCode CONFLICTING_TYPE_VARIABLE_AND_CLASS =
- const CompileTimeErrorCode('CONFLICTING_TYPE_VARIABLE_AND_CLASS',
- "'{0}' cannot be used to name a type variable in a class with the same name");
-
- /**
- * 7. Classes: It is a compile time error if a generic class declares a type
- * variable with the same name as the class or any of its members or
- * constructors.
- */
- static const CompileTimeErrorCode CONFLICTING_TYPE_VARIABLE_AND_MEMBER =
- const CompileTimeErrorCode('CONFLICTING_TYPE_VARIABLE_AND_MEMBER',
- "'{0}' cannot be used to name a type variable and member in this class");
-
- /**
- * 12.11.2 Const: It is a compile-time error if evaluation of a constant
- * object results in an uncaught exception being thrown.
- */
- static const CompileTimeErrorCode CONST_CONSTRUCTOR_THROWS_EXCEPTION =
- const CompileTimeErrorCode('CONST_CONSTRUCTOR_THROWS_EXCEPTION',
- "'const' constructors cannot throw exceptions");
-
- /**
- * 10.6.3 Constant Constructors: It is a compile-time error if a constant
- * constructor is declared by a class C if any instance variable declared in C
- * is initialized with an expression that is not a constant expression.
- */
- static const CompileTimeErrorCode
- CONST_CONSTRUCTOR_WITH_FIELD_INITIALIZED_BY_NON_CONST =
- const CompileTimeErrorCode(
- 'CONST_CONSTRUCTOR_WITH_FIELD_INITIALIZED_BY_NON_CONST',
- "Can't define the 'const' constructor because the field '{0}' is initialized with a non-constant value");
-
- /**
- * 7.6.3 Constant Constructors: The superinitializer that appears, explicitly
- * or implicitly, in the initializer list of a constant constructor must
- * specify a constant constructor of the superclass of the immediately
- * enclosing class or a compile-time error occurs.
- *
- * 9 Mixins: For each generative constructor named ... an implicitly declared
- * constructor named ... is declared.
- */
- static const CompileTimeErrorCode CONST_CONSTRUCTOR_WITH_MIXIN =
- const CompileTimeErrorCode('CONST_CONSTRUCTOR_WITH_MIXIN',
- "Constant constructor cannot be declared for a class with a mixin");
-
- /**
- * 7.6.3 Constant Constructors: The superinitializer that appears, explicitly
- * or implicitly, in the initializer list of a constant constructor must
- * specify a constant constructor of the superclass of the immediately
- * enclosing class or a compile-time error occurs.
- */
- static const CompileTimeErrorCode CONST_CONSTRUCTOR_WITH_NON_CONST_SUPER =
- const CompileTimeErrorCode('CONST_CONSTRUCTOR_WITH_NON_CONST_SUPER',
- "Constant constructor cannot call non-constant super constructor of '{0}'");
-
- /**
- * 7.6.3 Constant Constructors: It is a compile-time error if a constant
- * constructor is declared by a class that has a non-final instance variable.
- *
- * The above refers to both locally declared and inherited instance variables.
- */
- static const CompileTimeErrorCode CONST_CONSTRUCTOR_WITH_NON_FINAL_FIELD =
- const CompileTimeErrorCode('CONST_CONSTRUCTOR_WITH_NON_FINAL_FIELD',
- "Cannot define the 'const' constructor for a class with non-final fields");
-
- /**
- * 12.12.2 Const: It is a compile-time error if <i>T</i> is a deferred type.
- */
- static const CompileTimeErrorCode CONST_DEFERRED_CLASS =
- const CompileTimeErrorCode('CONST_DEFERRED_CLASS',
- "Deferred classes cannot be created with 'const'");
-
- /**
- * 6.2 Formal Parameters: It is a compile-time error if a formal parameter is
- * declared as a constant variable.
- */
- static const CompileTimeErrorCode CONST_FORMAL_PARAMETER =
- const CompileTimeErrorCode(
- 'CONST_FORMAL_PARAMETER', "Parameters cannot be 'const'");
-
- /**
- * 5 Variables: A constant variable must be initialized to a compile-time
- * constant or a compile-time error occurs.
- */
- static const CompileTimeErrorCode CONST_INITIALIZED_WITH_NON_CONSTANT_VALUE =
- const CompileTimeErrorCode('CONST_INITIALIZED_WITH_NON_CONSTANT_VALUE',
- "'const' variables must be constant value");
-
- /**
- * 5 Variables: A constant variable must be initialized to a compile-time
- * constant or a compile-time error occurs.
- *
- * 12.1 Constants: A qualified reference to a static constant variable that is
- * not qualified by a deferred prefix.
- */
- static const CompileTimeErrorCode
- CONST_INITIALIZED_WITH_NON_CONSTANT_VALUE_FROM_DEFERRED_LIBRARY =
- const CompileTimeErrorCode(
- 'CONST_INITIALIZED_WITH_NON_CONSTANT_VALUE_FROM_DEFERRED_LIBRARY',
- "Constant values from a deferred library cannot be used to initialized a 'const' variable");
-
- /**
- * 7.5 Instance Variables: It is a compile-time error if an instance variable
- * is declared to be constant.
- */
- static const CompileTimeErrorCode CONST_INSTANCE_FIELD =
- const CompileTimeErrorCode('CONST_INSTANCE_FIELD',
- "Only static fields can be declared as 'const'");
-
- /**
- * 12.8 Maps: It is a compile-time error if the key of an entry in a constant
- * map literal is an instance of a class that implements the operator
- * <i>==</i> unless the key is a string or integer.
- */
- static const CompileTimeErrorCode
- CONST_MAP_KEY_EXPRESSION_TYPE_IMPLEMENTS_EQUALS =
- const CompileTimeErrorCode(
- 'CONST_MAP_KEY_EXPRESSION_TYPE_IMPLEMENTS_EQUALS',
- "The constant map entry key expression type '{0}' cannot override the == operator");
-
- /**
- * 5 Variables: A constant variable must be initialized to a compile-time
- * constant (12.1) or a compile-time error occurs.
- *
- * Parameters:
- * 0: the name of the uninitialized final variable
- */
- static const CompileTimeErrorCode CONST_NOT_INITIALIZED =
- const CompileTimeErrorCode('CONST_NOT_INITIALIZED',
- "The const variable '{0}' must be initialized");
-
- /**
- * 12.11.2 Const: An expression of one of the forms !e, e1 && e2 or e1 || e2,
- * where e, e1 and e2 are constant expressions that evaluate to a boolean
- * value.
- */
- static const CompileTimeErrorCode CONST_EVAL_TYPE_BOOL =
- const CompileTimeErrorCode('CONST_EVAL_TYPE_BOOL',
- "In constant expressions, operand(s) of this operator must be of type 'bool'");
-
- /**
- * 12.11.2 Const: An expression of one of the forms e1 == e2 or e1 != e2 where
- * e1 and e2 are constant expressions that evaluate to a numeric, string or
- * boolean value or to null.
- */
- static const CompileTimeErrorCode CONST_EVAL_TYPE_BOOL_NUM_STRING =
- const CompileTimeErrorCode('CONST_EVAL_TYPE_BOOL_NUM_STRING',
- "In constant expressions, operands of this operator must be of type 'bool', 'num', 'String' or 'null'");
-
- /**
- * 12.11.2 Const: An expression of one of the forms ~e, e1 ^ e2, e1 & e2,
- * e1 | e2, e1 >> e2 or e1 << e2, where e, e1 and e2 are constant expressions
- * that evaluate to an integer value or to null.
- */
- static const CompileTimeErrorCode CONST_EVAL_TYPE_INT =
- const CompileTimeErrorCode('CONST_EVAL_TYPE_INT',
- "In constant expressions, operand(s) of this operator must be of type 'int'");
-
- /**
- * 12.11.2 Const: An expression of one of the forms e, e1 + e2, e1 - e2, e1 *
- * e2, e1 / e2, e1 ~/ e2, e1 > e2, e1 < e2, e1 >= e2, e1 <= e2 or e1 % e2,
- * where e, e1 and e2 are constant expressions that evaluate to a numeric
- * value or to null.
- */
- static const CompileTimeErrorCode CONST_EVAL_TYPE_NUM =
- const CompileTimeErrorCode('CONST_EVAL_TYPE_NUM',
- "In constant expressions, operand(s) of this operator must be of type 'num'");
-
- /**
- * 12.11.2 Const: It is a compile-time error if evaluation of a constant
- * object results in an uncaught exception being thrown.
- */
- static const CompileTimeErrorCode CONST_EVAL_THROWS_EXCEPTION =
- const CompileTimeErrorCode('CONST_EVAL_THROWS_EXCEPTION',
- "Evaluation of this constant expression causes exception");
-
- /**
- * 12.11.2 Const: It is a compile-time error if evaluation of a constant
- * object results in an uncaught exception being thrown.
- */
- static const CompileTimeErrorCode CONST_EVAL_THROWS_IDBZE =
- const CompileTimeErrorCode('CONST_EVAL_THROWS_IDBZE',
- "Evaluation of this constant expression throws IntegerDivisionByZeroException");
-
- /**
- * 12.11.2 Const: If <i>T</i> is a parameterized type <i>S<U<sub>1</sub>,
- * …, U<sub>m</sub>></i>, let <i>R = S</i>; It is a compile time
- * error if <i>S</i> is not a generic type with <i>m</i> type parameters.
- *
- * Parameters:
- * 0: the name of the type being referenced (<i>S</i>)
- * 1: the number of type parameters that were declared
- * 2: the number of type arguments provided
- *
- * See [StaticWarningCode.NEW_WITH_INVALID_TYPE_PARAMETERS], and
- * [StaticTypeWarningCode.WRONG_NUMBER_OF_TYPE_ARGUMENTS].
- */
- static const CompileTimeErrorCode CONST_WITH_INVALID_TYPE_PARAMETERS =
- const CompileTimeErrorCode('CONST_WITH_INVALID_TYPE_PARAMETERS',
- "The type '{0}' is declared with {1} type parameters, but {2} type arguments were given");
-
- /**
- * 12.11.2 Const: If <i>e</i> is of the form <i>const T(a<sub>1</sub>,
- * …, a<sub>n</sub>, x<sub>n+1</sub>: a<sub>n+1</sub>, …,
- * x<sub>n+k</sub>: a<sub>n+k</sub>)</i> it is a compile-time error if the
- * type <i>T</i> does not declare a constant constructor with the same name as
- * the declaration of <i>T</i>.
- */
- static const CompileTimeErrorCode CONST_WITH_NON_CONST =
- const CompileTimeErrorCode('CONST_WITH_NON_CONST',
- "The constructor being called is not a 'const' constructor");
-
- /**
- * 12.11.2 Const: In all of the above cases, it is a compile-time error if
- * <i>a<sub>i</sub>, 1 <= i <= n + k</i>, is not a compile-time constant
- * expression.
- */
- static const CompileTimeErrorCode CONST_WITH_NON_CONSTANT_ARGUMENT =
- const CompileTimeErrorCode('CONST_WITH_NON_CONSTANT_ARGUMENT',
- "Arguments of a constant creation must be constant expressions");
-
- /**
- * 12.11.2 Const: It is a compile-time error if <i>T</i> is not a class
- * accessible in the current scope, optionally followed by type arguments.
- *
- * 12.11.2 Const: If <i>e</i> is of the form <i>const T.id(a<sub>1</sub>,
- * …, a<sub>n</sub>, x<sub>n+1</sub>: a<sub>n+1</sub>, …
- * x<sub>n+k</sub>: a<sub>n+k</sub>)</i> it is a compile-time error if
- * <i>T</i> is not a class accessible in the current scope, optionally
- * followed by type arguments.
- *
- * Parameters:
- * 0: the name of the non-type element
- */
- static const CompileTimeErrorCode CONST_WITH_NON_TYPE =
- const CompileTimeErrorCode(
- 'CONST_WITH_NON_TYPE', "The name '{0}' is not a class");
-
- /**
- * 12.11.2 Const: It is a compile-time error if <i>T</i> includes any type
- * parameters.
- */
- static const CompileTimeErrorCode CONST_WITH_TYPE_PARAMETERS =
- const CompileTimeErrorCode('CONST_WITH_TYPE_PARAMETERS',
- "The constant creation cannot use a type parameter");
-
- /**
- * 12.11.2 Const: It is a compile-time error if <i>T.id</i> is not the name of
- * a constant constructor declared by the type <i>T</i>.
- *
- * Parameters:
- * 0: the name of the type
- * 1: the name of the requested constant constructor
- */
- static const CompileTimeErrorCode CONST_WITH_UNDEFINED_CONSTRUCTOR =
- const CompileTimeErrorCode('CONST_WITH_UNDEFINED_CONSTRUCTOR',
- "The class '{0}' does not have a constant constructor '{1}'");
-
- /**
- * 12.11.2 Const: It is a compile-time error if <i>T.id</i> is not the name of
- * a constant constructor declared by the type <i>T</i>.
- *
- * Parameters:
- * 0: the name of the type
- */
- static const CompileTimeErrorCode CONST_WITH_UNDEFINED_CONSTRUCTOR_DEFAULT =
- const CompileTimeErrorCode('CONST_WITH_UNDEFINED_CONSTRUCTOR_DEFAULT',
- "The class '{0}' does not have a default constant constructor");
-
- /**
- * 15.3.1 Typedef: It is a compile-time error if any default values are
- * specified in the signature of a function type alias.
- */
- static const CompileTimeErrorCode DEFAULT_VALUE_IN_FUNCTION_TYPE_ALIAS =
- const CompileTimeErrorCode('DEFAULT_VALUE_IN_FUNCTION_TYPE_ALIAS',
- "Default values aren't allowed in typedefs");
-
- /**
- * 6.2.1 Required Formals: By means of a function signature that names the
- * parameter and describes its type as a function type. It is a compile-time
- * error if any default values are specified in the signature of such a
- * function type.
- */
- static const CompileTimeErrorCode DEFAULT_VALUE_IN_FUNCTION_TYPED_PARAMETER =
- const CompileTimeErrorCode('DEFAULT_VALUE_IN_FUNCTION_TYPED_PARAMETER',
- "Default values aren't allowed in function type parameters");
-
- /**
- * 7.6.2 Factories: It is a compile-time error if <i>k</i> explicitly
- * specifies a default value for an optional parameter.
- */
- static const CompileTimeErrorCode
- DEFAULT_VALUE_IN_REDIRECTING_FACTORY_CONSTRUCTOR =
- const CompileTimeErrorCode(
- 'DEFAULT_VALUE_IN_REDIRECTING_FACTORY_CONSTRUCTOR',
- "Default values aren't allowed in factory constructors that redirect to another constructor");
-
- /**
- * 3.1 Scoping: It is a compile-time error if there is more than one entity
- * with the same name declared in the same scope.
- */
- static const CompileTimeErrorCode DUPLICATE_CONSTRUCTOR_DEFAULT =
- const CompileTimeErrorCode('DUPLICATE_CONSTRUCTOR_DEFAULT',
- "The default constructor is already defined");
-
- /**
- * 3.1 Scoping: It is a compile-time error if there is more than one entity
- * with the same name declared in the same scope.
- *
- * Parameters:
- * 0: the name of the duplicate entity
- */
- static const CompileTimeErrorCode DUPLICATE_CONSTRUCTOR_NAME =
- const CompileTimeErrorCode('DUPLICATE_CONSTRUCTOR_NAME',
- "The constructor with name '{0}' is already defined");
-
- /**
- * 3.1 Scoping: It is a compile-time error if there is more than one entity
- * with the same name declared in the same scope.
- *
- * 7 Classes: It is a compile-time error if a class declares two members of
- * the same name.
- *
- * 7 Classes: It is a compile-time error if a class has an instance member and
- * a static member with the same name.
- *
- * Parameters:
- * 0: the name of the duplicate entity
- */
- static const CompileTimeErrorCode DUPLICATE_DEFINITION =
- const CompileTimeErrorCode(
- 'DUPLICATE_DEFINITION', "The name '{0}' is already defined");
-
- /**
- * 7. Classes: It is a compile-time error if a class has an instance member
- * and a static member with the same name.
- *
- * This covers the additional duplicate definition cases where inheritance has
- * to be considered.
- *
- * Parameters:
- * 0: the name of the class that has conflicting instance/static members
- * 1: the name of the conflicting members
- *
- * See [DUPLICATE_DEFINITION].
- */
- static const CompileTimeErrorCode DUPLICATE_DEFINITION_INHERITANCE =
- const CompileTimeErrorCode('DUPLICATE_DEFINITION_INHERITANCE',
- "The name '{0}' is already defined in '{1}'");
-
- /**
- * 12.14.2 Binding Actuals to Formals: It is a compile-time error if
- * <i>q<sub>i</sub> = q<sub>j</sub></i> for any <i>i != j</i> [where
- * <i>q<sub>i</sub></i> is the label for a named argument].
- */
- static const CompileTimeErrorCode DUPLICATE_NAMED_ARGUMENT =
- const CompileTimeErrorCode('DUPLICATE_NAMED_ARGUMENT',
- "The argument for the named parameter '{0}' was already specified");
-
- /**
- * SDK implementation libraries can be exported only by other SDK libraries.
- *
- * Parameters:
- * 0: the uri pointing to a library
- */
- static const CompileTimeErrorCode EXPORT_INTERNAL_LIBRARY =
- const CompileTimeErrorCode('EXPORT_INTERNAL_LIBRARY',
- "The library '{0}' is internal and cannot be exported");
-
- /**
- * 14.2 Exports: It is a compile-time error if the compilation unit found at
- * the specified URI is not a library declaration.
- *
- * Parameters:
- * 0: the uri pointing to a non-library declaration
- */
- static const CompileTimeErrorCode EXPORT_OF_NON_LIBRARY =
- const CompileTimeErrorCode('EXPORT_OF_NON_LIBRARY',
- "The exported library '{0}' must not have a part-of directive");
-
- /**
- * Enum proposal: It is a compile-time error to subclass, mix-in or implement
- * an enum.
- */
- static const CompileTimeErrorCode EXTENDS_ENUM = const CompileTimeErrorCode(
- 'EXTENDS_ENUM', "Classes cannot extend an enum");
-
- /**
- * 7.9 Superclasses: It is a compile-time error if the extends clause of a
- * class <i>C</i> includes a type expression that does not denote a class
- * available in the lexical scope of <i>C</i>.
- *
- * Parameters:
- * 0: the name of the superclass that was not found
- */
- static const CompileTimeErrorCode EXTENDS_NON_CLASS =
- const CompileTimeErrorCode(
- 'EXTENDS_NON_CLASS', "Classes can only extend other classes");
-
- /**
- * 12.2 Null: It is a compile-time error for a class to attempt to extend or
- * implement Null.
- *
- * 12.3 Numbers: It is a compile-time error for a class to attempt to extend
- * or implement int.
- *
- * 12.3 Numbers: It is a compile-time error for a class to attempt to extend
- * or implement double.
- *
- * 12.3 Numbers: It is a compile-time error for any type other than the types
- * int and double to
- * attempt to extend or implement num.
- *
- * 12.4 Booleans: It is a compile-time error for a class to attempt to extend
- * or implement bool.
- *
- * 12.5 Strings: It is a compile-time error for a class to attempt to extend
- * or implement String.
- *
- * Parameters:
- * 0: the name of the type that cannot be extended
- *
- * See [IMPLEMENTS_DISALLOWED_CLASS].
- */
- static const CompileTimeErrorCode EXTENDS_DISALLOWED_CLASS =
- const CompileTimeErrorCode(
- 'EXTENDS_DISALLOWED_CLASS', "Classes cannot extend '{0}'");
-
- /**
- * 7.9 Superclasses: It is a compile-time error if the extends clause of a
- * class <i>C</i> includes a deferred type expression.
- *
- * Parameters:
- * 0: the name of the type that cannot be extended
- *
- * See [IMPLEMENTS_DEFERRED_CLASS], and [MIXIN_DEFERRED_CLASS].
- */
- static const CompileTimeErrorCode EXTENDS_DEFERRED_CLASS =
- const CompileTimeErrorCode('EXTENDS_DEFERRED_CLASS',
- "This class cannot extend the deferred class '{0}'");
-
- /**
- * DEP 37 extends the syntax for assert() to allow a second "message"
- * argument. We issue this error if the user tries to supply a "message"
- * argument but the DEP is not enabled.
- */
- static const CompileTimeErrorCode EXTRA_ARGUMENT_TO_ASSERT =
- const CompileTimeErrorCode('EXTRA_ARGUMENT_TO_ASSERT',
- "Assertions only accept a single argument");
-
- /**
- * 12.14.2 Binding Actuals to Formals: It is a static warning if <i>m <
- * h</i> or if <i>m > n</i>.
- *
- * 12.11.2 Const: It is a compile-time error if evaluation of a constant
- * object results in an uncaught exception being thrown.
- *
- * Parameters:
- * 0: the maximum number of positional arguments
- * 1: the actual number of positional arguments given
- */
- static const CompileTimeErrorCode EXTRA_POSITIONAL_ARGUMENTS =
- const CompileTimeErrorCode('EXTRA_POSITIONAL_ARGUMENTS',
- "{0} positional arguments expected, but {1} found");
-
- /**
- * 7.6.1 Generative Constructors: Let <i>k</i> be a generative constructor. It
- * is a compile time error if more than one initializer corresponding to a
- * given instance variable appears in <i>k</i>'s list.
- */
- static const CompileTimeErrorCode FIELD_INITIALIZED_BY_MULTIPLE_INITIALIZERS =
- const CompileTimeErrorCode('FIELD_INITIALIZED_BY_MULTIPLE_INITIALIZERS',
- "The field '{0}' cannot be initialized twice in the same constructor");
-
- /**
- * 7.6.1 Generative Constructors: Let <i>k</i> be a generative constructor. It
- * is a compile time error if <i>k</i>'s initializer list contains an
- * initializer for a variable that is initialized by means of an initializing
- * formal of <i>k</i>.
- */
- static const CompileTimeErrorCode
- FIELD_INITIALIZED_IN_PARAMETER_AND_INITIALIZER =
- const CompileTimeErrorCode(
- 'FIELD_INITIALIZED_IN_PARAMETER_AND_INITIALIZER',
- "Fields cannot be initialized in both the parameter list and the initializers");
-
- /**
- * 5 Variables: It is a compile-time error if a final instance variable that
- * has is initialized by means of an initializing formal of a constructor is
- * also initialized elsewhere in the same constructor.
- *
- * Parameters:
- * 0: the name of the field in question
- */
- static const CompileTimeErrorCode FINAL_INITIALIZED_MULTIPLE_TIMES =
- const CompileTimeErrorCode('FINAL_INITIALIZED_MULTIPLE_TIMES',
- "'{0}' is a final field and so can only be set once");
-
- /**
- * 7.6.1 Generative Constructors: It is a compile-time error if an
- * initializing formal is used by a function other than a non-redirecting
- * generative constructor.
- */
- static const CompileTimeErrorCode FIELD_INITIALIZER_FACTORY_CONSTRUCTOR =
- const CompileTimeErrorCode('FIELD_INITIALIZER_FACTORY_CONSTRUCTOR',
- "Initializing formal fields cannot be used in factory constructors");
-
- /**
- * 7.6.1 Generative Constructors: It is a compile-time error if an
- * initializing formal is used by a function other than a non-redirecting
- * generative constructor.
- */
- static const CompileTimeErrorCode FIELD_INITIALIZER_OUTSIDE_CONSTRUCTOR =
- const CompileTimeErrorCode('FIELD_INITIALIZER_OUTSIDE_CONSTRUCTOR',
- "Initializing formal fields can only be used in constructors");
-
- /**
- * 7.6.1 Generative Constructors: A generative constructor may be redirecting,
- * in which case its only action is to invoke another generative constructor.
- *
- * 7.6.1 Generative Constructors: It is a compile-time error if an
- * initializing formal is used by a function other than a non-redirecting
- * generative constructor.
- */
- static const CompileTimeErrorCode FIELD_INITIALIZER_REDIRECTING_CONSTRUCTOR =
- const CompileTimeErrorCode('FIELD_INITIALIZER_REDIRECTING_CONSTRUCTOR',
- "The redirecting constructor cannot have a field initializer");
-
- /**
- * 7.2 Getters: It is a compile-time error if a class has both a getter and a
- * method with the same name.
- *
- * Parameters:
- * 0: the conflicting name of the getter and method
- */
- static const CompileTimeErrorCode GETTER_AND_METHOD_WITH_SAME_NAME =
- const CompileTimeErrorCode('GETTER_AND_METHOD_WITH_SAME_NAME',
- "'{0}' cannot be used to name a getter, there is already a method with the same name");
-
- /**
- * 7.10 Superinterfaces: It is a compile-time error if the implements clause
- * of a class <i>C</i> specifies a malformed type or deferred type as a
- * superinterface.
- *
- * Parameters:
- * 0: the name of the type that cannot be extended
- *
- * See [EXTENDS_DEFERRED_CLASS], and [MIXIN_DEFERRED_CLASS].
- */
- static const CompileTimeErrorCode IMPLEMENTS_DEFERRED_CLASS =
- const CompileTimeErrorCode('IMPLEMENTS_DEFERRED_CLASS',
- "This class cannot implement the deferred class '{0}'");
-
- /**
- * 12.2 Null: It is a compile-time error for a class to attempt to extend or
- * implement Null.
- *
- * 12.3 Numbers: It is a compile-time error for a class to attempt to extend
- * or implement int.
- *
- * 12.3 Numbers: It is a compile-time error for a class to attempt to extend
- * or implement double.
- *
- * 12.3 Numbers: It is a compile-time error for any type other than the types
- * int and double to
- * attempt to extend or implement num.
- *
- * 12.4 Booleans: It is a compile-time error for a class to attempt to extend
- * or implement bool.
- *
- * 12.5 Strings: It is a compile-time error for a class to attempt to extend
- * or implement String.
- *
- * Parameters:
- * 0: the name of the type that cannot be implemented
- *
- * See [EXTENDS_DISALLOWED_CLASS].
- */
- static const CompileTimeErrorCode IMPLEMENTS_DISALLOWED_CLASS =
- const CompileTimeErrorCode(
- 'IMPLEMENTS_DISALLOWED_CLASS', "Classes cannot implement '{0}'");
-
- /**
- * 7.10 Superinterfaces: It is a compile-time error if the implements clause
- * of a class includes type dynamic.
- */
- static const CompileTimeErrorCode IMPLEMENTS_DYNAMIC =
- const CompileTimeErrorCode(
- 'IMPLEMENTS_DYNAMIC', "Classes cannot implement 'dynamic'");
-
- /**
- * Enum proposal: It is a compile-time error to subclass, mix-in or implement
- * an enum.
- */
- static const CompileTimeErrorCode IMPLEMENTS_ENUM =
- const CompileTimeErrorCode(
- 'IMPLEMENTS_ENUM', "Classes cannot implement an enum");
-
- /**
- * 7.10 Superinterfaces: It is a compile-time error if the implements clause
- * of a class <i>C</i> includes a type expression that does not denote a class
- * available in the lexical scope of <i>C</i>.
- *
- * Parameters:
- * 0: the name of the interface that was not found
- */
- static const CompileTimeErrorCode IMPLEMENTS_NON_CLASS =
- const CompileTimeErrorCode(
- 'IMPLEMENTS_NON_CLASS', "Classes can only implement other classes");
-
- /**
- * 7.10 Superinterfaces: It is a compile-time error if a type <i>T</i> appears
- * more than once in the implements clause of a class.
- *
- * Parameters:
- * 0: the name of the class that is implemented more than once
- */
- static const CompileTimeErrorCode IMPLEMENTS_REPEATED =
- const CompileTimeErrorCode(
- 'IMPLEMENTS_REPEATED', "'{0}' can only be implemented once");
-
- /**
- * 7.10 Superinterfaces: It is a compile-time error if the superclass of a
- * class <i>C</i> appears in the implements clause of <i>C</i>.
- *
- * Parameters:
- * 0: the name of the class that appears in both "extends" and "implements"
- * clauses
- */
- static const CompileTimeErrorCode IMPLEMENTS_SUPER_CLASS =
- const CompileTimeErrorCode('IMPLEMENTS_SUPER_CLASS',
- "'{0}' cannot be used in both 'extends' and 'implements' clauses");
-
- /**
- * 7.6.1 Generative Constructors: Note that <b>this</b> is not in scope on the
- * right hand side of an initializer.
- *
- * 12.10 This: It is a compile-time error if this appears in a top-level
- * function or variable initializer, in a factory constructor, or in a static
- * method or variable initializer, or in the initializer of an instance
- * variable.
- *
- * Parameters:
- * 0: the name of the type in question
- */
- static const CompileTimeErrorCode IMPLICIT_THIS_REFERENCE_IN_INITIALIZER =
- const CompileTimeErrorCode('IMPLICIT_THIS_REFERENCE_IN_INITIALIZER',
- "Only static members can be accessed in initializers");
-
- /**
- * SDK implementation libraries can be imported only by other SDK libraries.
- *
- * Parameters:
- * 0: the uri pointing to a library
- */
- static const CompileTimeErrorCode IMPORT_INTERNAL_LIBRARY =
- const CompileTimeErrorCode('IMPORT_INTERNAL_LIBRARY',
- "The library '{0}' is internal and cannot be imported");
-
- /**
- * 14.1 Imports: It is a compile-time error if the specified URI of an
- * immediate import does not refer to a library declaration.
- *
- * Parameters:
- * 0: the uri pointing to a non-library declaration
- *
- * See [StaticWarningCode.IMPORT_OF_NON_LIBRARY].
- */
- static const CompileTimeErrorCode IMPORT_OF_NON_LIBRARY =
- const CompileTimeErrorCode('IMPORT_OF_NON_LIBRARY',
- "The imported library '{0}' must not have a part-of directive");
-
- /**
- * 13.9 Switch: It is a compile-time error if values of the expressions
- * <i>e<sub>k</sub></i> are not instances of the same class <i>C</i>, for all
- * <i>1 <= k <= n</i>.
- *
- * Parameters:
- * 0: the expression source code that is the unexpected type
- * 1: the name of the expected type
- */
- static const CompileTimeErrorCode INCONSISTENT_CASE_EXPRESSION_TYPES =
- const CompileTimeErrorCode('INCONSISTENT_CASE_EXPRESSION_TYPES',
- "Case expressions must have the same types, '{0}' is not a '{1}'");
-
- /**
- * 7.6.1 Generative Constructors: Let <i>k</i> be a generative constructor. It
- * is a compile-time error if <i>k</i>'s initializer list contains an
- * initializer for a variable that is not an instance variable declared in the
- * immediately surrounding class.
- *
- * Parameters:
- * 0: the name of the initializing formal that is not an instance variable in
- * the immediately enclosing class
- *
- * See [INITIALIZING_FORMAL_FOR_NON_EXISTENT_FIELD].
- */
- static const CompileTimeErrorCode INITIALIZER_FOR_NON_EXISTENT_FIELD =
- const CompileTimeErrorCode('INITIALIZER_FOR_NON_EXISTENT_FIELD',
- "'{0}' is not a variable in the enclosing class");
-
- /**
- * 7.6.1 Generative Constructors: Let <i>k</i> be a generative constructor. It
- * is a compile-time error if <i>k</i>'s initializer list contains an
- * initializer for a variable that is not an instance variable declared in the
- * immediately surrounding class.
- *
- * Parameters:
- * 0: the name of the initializing formal that is a static variable in the
- * immediately enclosing class
- *
- * See [INITIALIZING_FORMAL_FOR_STATIC_FIELD].
- */
- static const CompileTimeErrorCode INITIALIZER_FOR_STATIC_FIELD =
- const CompileTimeErrorCode('INITIALIZER_FOR_STATIC_FIELD',
- "'{0}' is a static variable in the enclosing class, variables initialized in a constructor cannot be static");
-
- /**
- * 7.6.1 Generative Constructors: An initializing formal has the form
- * <i>this.id</i>. It is a compile-time error if <i>id</i> is not the name of
- * an instance variable of the immediately enclosing class.
- *
- * Parameters:
- * 0: the name of the initializing formal that is not an instance variable in
- * the immediately enclosing class
- *
- * See [INITIALIZING_FORMAL_FOR_STATIC_FIELD], and
- * [INITIALIZER_FOR_NON_EXISTENT_FIELD].
- */
- static const CompileTimeErrorCode INITIALIZING_FORMAL_FOR_NON_EXISTENT_FIELD =
- const CompileTimeErrorCode('INITIALIZING_FORMAL_FOR_NON_EXISTENT_FIELD',
- "'{0}' is not a variable in the enclosing class");
-
- /**
- * 7.6.1 Generative Constructors: An initializing formal has the form
- * <i>this.id</i>. It is a compile-time error if <i>id</i> is not the name of
- * an instance variable of the immediately enclosing class.
- *
- * Parameters:
- * 0: the name of the initializing formal that is a static variable in the
- * immediately enclosing class
- *
- * See [INITIALIZER_FOR_STATIC_FIELD].
- */
- static const CompileTimeErrorCode INITIALIZING_FORMAL_FOR_STATIC_FIELD =
- const CompileTimeErrorCode('INITIALIZING_FORMAL_FOR_STATIC_FIELD',
- "'{0}' is a static field in the enclosing class, fields initialized in a constructor cannot be static");
-
- /**
- * 12.30 Identifier Reference: Otherwise, e is equivalent to the property
- * extraction <b>this</b>.<i>id</i>.
- */
- static const CompileTimeErrorCode INSTANCE_MEMBER_ACCESS_FROM_FACTORY =
- const CompileTimeErrorCode('INSTANCE_MEMBER_ACCESS_FROM_FACTORY',
- "Instance members cannot be accessed from a factory constructor");
-
- /**
- * 12.30 Identifier Reference: Otherwise, e is equivalent to the property
- * extraction <b>this</b>.<i>id</i>.
- */
- static const CompileTimeErrorCode INSTANCE_MEMBER_ACCESS_FROM_STATIC =
- const CompileTimeErrorCode('INSTANCE_MEMBER_ACCESS_FROM_STATIC',
- "Instance members cannot be accessed from a static method");
-
- /**
- * Enum proposal: It is also a compile-time error to explicitly instantiate an
- * enum via 'new' or 'const' or to access its private fields.
- */
- static const CompileTimeErrorCode INSTANTIATE_ENUM =
- const CompileTimeErrorCode(
- 'INSTANTIATE_ENUM', "Enums cannot be instantiated");
-
- /**
- * 11 Metadata: Metadata consists of a series of annotations, each of which
- * begin with the character @, followed by a constant expression that must be
- * either a reference to a compile-time constant variable, or a call to a
- * constant constructor.
- */
- static const CompileTimeErrorCode INVALID_ANNOTATION = const CompileTimeErrorCode(
- 'INVALID_ANNOTATION',
- "Annotation can be only constant variable or constant constructor invocation");
-
- /**
- * 11 Metadata: Metadata consists of a series of annotations, each of which
- * begin with the character @, followed by a constant expression that must be
- * either a reference to a compile-time constant variable, or a call to a
- * constant constructor.
- *
- * 12.1 Constants: A qualified reference to a static constant variable that is
- * not qualified by a deferred prefix.
- */
- static const CompileTimeErrorCode INVALID_ANNOTATION_FROM_DEFERRED_LIBRARY =
- const CompileTimeErrorCode('INVALID_ANNOTATION_FROM_DEFERRED_LIBRARY',
- "Constant values from a deferred library cannot be used as annotations");
-
- /**
- * 15.31 Identifier Reference: It is a compile-time error if any of the
- * identifiers async, await or yield is used as an identifier in a function
- * body marked with either async, async* or sync*.
- */
- static const CompileTimeErrorCode INVALID_IDENTIFIER_IN_ASYNC =
- const CompileTimeErrorCode('INVALID_IDENTIFIER_IN_ASYNC',
- "The identifier '{0}' cannot be used in a function marked with async, async* or sync*");
-
- /**
- * 9. Functions: It is a compile-time error if an async, async* or sync*
- * modifier is attached to the body of a setter or constructor.
- */
- static const CompileTimeErrorCode INVALID_MODIFIER_ON_CONSTRUCTOR =
- const CompileTimeErrorCode('INVALID_MODIFIER_ON_CONSTRUCTOR',
- "The modifier '{0}' cannot be applied to the body of a constructor");
-
- /**
- * 9. Functions: It is a compile-time error if an async, async* or sync*
- * modifier is attached to the body of a setter or constructor.
- */
- static const CompileTimeErrorCode INVALID_MODIFIER_ON_SETTER =
- const CompileTimeErrorCode('INVALID_MODIFIER_ON_SETTER',
- "The modifier '{0}' cannot be applied to the body of a setter");
-
- /**
- * TODO(brianwilkerson) Remove this when we have decided on how to report
- * errors in compile-time constants. Until then, this acts as a placeholder
- * for more informative errors.
- *
- * See TODOs in ConstantVisitor
- */
- static const CompileTimeErrorCode INVALID_CONSTANT =
- const CompileTimeErrorCode('INVALID_CONSTANT', "Invalid constant value");
-
- /**
- * 7.6 Constructors: It is a compile-time error if the name of a constructor
- * is not a constructor name.
- */
- static const CompileTimeErrorCode INVALID_CONSTRUCTOR_NAME =
- const CompileTimeErrorCode(
- 'INVALID_CONSTRUCTOR_NAME', "Invalid constructor name");
-
- /**
- * 7.6.2 Factories: It is a compile-time error if <i>M</i> is not the name of
- * the immediately enclosing class.
- */
- static const CompileTimeErrorCode INVALID_FACTORY_NAME_NOT_A_CLASS =
- const CompileTimeErrorCode('INVALID_FACTORY_NAME_NOT_A_CLASS',
- "The name of the immediately enclosing class expected");
-
- /**
- * 12.10 This: It is a compile-time error if this appears in a top-level
- * function or variable initializer, in a factory constructor, or in a static
- * method or variable initializer, or in the initializer of an instance
- * variable.
- */
- static const CompileTimeErrorCode INVALID_REFERENCE_TO_THIS =
- const CompileTimeErrorCode('INVALID_REFERENCE_TO_THIS',
- "Invalid reference to 'this' expression");
-
- /**
- * 12.6 Lists: It is a compile time error if the type argument of a constant
- * list literal includes a type parameter.
- *
- * Parameters:
- * 0: the name of the type parameter
- */
- static const CompileTimeErrorCode INVALID_TYPE_ARGUMENT_IN_CONST_LIST =
- const CompileTimeErrorCode('INVALID_TYPE_ARGUMENT_IN_CONST_LIST',
- "Constant list literals cannot include a type parameter as a type argument, such as '{0}'");
-
- /**
- * 12.7 Maps: It is a compile time error if the type arguments of a constant
- * map literal include a type parameter.
- *
- * Parameters:
- * 0: the name of the type parameter
- */
- static const CompileTimeErrorCode INVALID_TYPE_ARGUMENT_IN_CONST_MAP =
- const CompileTimeErrorCode('INVALID_TYPE_ARGUMENT_IN_CONST_MAP',
- "Constant map literals cannot include a type parameter as a type argument, such as '{0}'");
-
- /**
- * 14.2 Exports: It is a compile-time error if the compilation unit found at
- * the specified URI is not a library declaration.
- *
- * 14.1 Imports: It is a compile-time error if the compilation unit found at
- * the specified URI is not a library declaration.
- *
- * 14.3 Parts: It is a compile time error if the contents of the URI are not a
- * valid part declaration.
- *
- * Parameters:
- * 0: the URI that is invalid
- *
- * See [URI_DOES_NOT_EXIST].
- */
- static const CompileTimeErrorCode INVALID_URI =
- const CompileTimeErrorCode('INVALID_URI', "Invalid URI syntax: '{0}'");
-
- /**
- * 13.13 Break: It is a compile-time error if no such statement
- * <i>s<sub>E</sub></i> exists within the innermost function in which
- * <i>s<sub>b</sub></i> occurs.
- *
- * 13.14 Continue: It is a compile-time error if no such statement or case
- * clause <i>s<sub>E</sub></i> exists within the innermost function in which
- * <i>s<sub>c</sub></i> occurs.
- *
- * Parameters:
- * 0: the name of the unresolvable label
- */
- static const CompileTimeErrorCode LABEL_IN_OUTER_SCOPE =
- const CompileTimeErrorCode('LABEL_IN_OUTER_SCOPE',
- "Cannot reference label '{0}' declared in an outer method");
-
- /**
- * 13.13 Break: It is a compile-time error if no such statement
- * <i>s<sub>E</sub></i> exists within the innermost function in which
- * <i>s<sub>b</sub></i> occurs.
- *
- * 13.14 Continue: It is a compile-time error if no such statement or case
- * clause <i>s<sub>E</sub></i> exists within the innermost function in which
- * <i>s<sub>c</sub></i> occurs.
- *
- * Parameters:
- * 0: the name of the unresolvable label
- */
- static const CompileTimeErrorCode LABEL_UNDEFINED =
- const CompileTimeErrorCode(
- 'LABEL_UNDEFINED', "Cannot reference undefined label '{0}'");
-
- /**
- * 7 Classes: It is a compile time error if a class <i>C</i> declares a member
- * with the same name as <i>C</i>.
- */
- static const CompileTimeErrorCode MEMBER_WITH_CLASS_NAME =
- const CompileTimeErrorCode('MEMBER_WITH_CLASS_NAME',
- "Class members cannot have the same name as the enclosing class");
-
- /**
- * 7.2 Getters: It is a compile-time error if a class has both a getter and a
- * method with the same name.
- *
- * Parameters:
- * 0: the conflicting name of the getter and method
- */
- static const CompileTimeErrorCode METHOD_AND_GETTER_WITH_SAME_NAME =
- const CompileTimeErrorCode('METHOD_AND_GETTER_WITH_SAME_NAME',
- "'{0}' cannot be used to name a method, there is already a getter with the same name");
-
- /**
- * 12.1 Constants: A constant expression is ... a constant list literal.
- */
- static const CompileTimeErrorCode MISSING_CONST_IN_LIST_LITERAL =
- const CompileTimeErrorCode('MISSING_CONST_IN_LIST_LITERAL',
- "List literals must be prefixed with 'const' when used as a constant expression");
-
- /**
- * 12.1 Constants: A constant expression is ... a constant map literal.
- */
- static const CompileTimeErrorCode MISSING_CONST_IN_MAP_LITERAL =
- const CompileTimeErrorCode('MISSING_CONST_IN_MAP_LITERAL',
- "Map literals must be prefixed with 'const' when used as a constant expression");
-
- /**
- * 9 Mixins: It is a compile-time error if a declared or derived mixin
- * explicitly declares a constructor.
- *
- * Parameters:
- * 0: the name of the mixin that is invalid
- */
- static const CompileTimeErrorCode MIXIN_DECLARES_CONSTRUCTOR =
- const CompileTimeErrorCode('MIXIN_DECLARES_CONSTRUCTOR',
- "The class '{0}' cannot be used as a mixin because it declares a constructor");
-
- /**
- * 9.1 Mixin Application: It is a compile-time error if the with clause of a
- * mixin application <i>C</i> includes a deferred type expression.
- *
- * Parameters:
- * 0: the name of the type that cannot be extended
- *
- * See [EXTENDS_DEFERRED_CLASS], and [IMPLEMENTS_DEFERRED_CLASS].
- */
- static const CompileTimeErrorCode MIXIN_DEFERRED_CLASS =
- const CompileTimeErrorCode('MIXIN_DEFERRED_CLASS',
- "This class cannot mixin the deferred class '{0}'");
-
- /**
- * Not yet in the spec, but consistent with VM behavior. It is a
- * compile-time error if all of the constructors of a mixin's base class have
- * at least one optional parameter (since only constructors that lack
- * optional parameters can be forwarded to the mixin). See
- * https://code.google.com/p/dart/issues/detail?id=15101#c4
- */
- static const CompileTimeErrorCode MIXIN_HAS_NO_CONSTRUCTORS =
- const CompileTimeErrorCode(
- 'MIXIN_HAS_NO_CONSTRUCTORS',
- "This mixin application is invalid because all of the constructors "
- "in the base class '{0}' have optional parameters.");
-
- /**
- * 9 Mixins: It is a compile-time error if a mixin is derived from a class
- * whose superclass is not Object.
- *
- * Parameters:
- * 0: the name of the mixin that is invalid
- */
- static const CompileTimeErrorCode MIXIN_INHERITS_FROM_NOT_OBJECT =
- const CompileTimeErrorCode('MIXIN_INHERITS_FROM_NOT_OBJECT',
- "The class '{0}' cannot be used as a mixin because it extends a class other than Object");
-
- /**
- * 12.2 Null: It is a compile-time error for a class to attempt to extend or
- * implement Null.
- *
- * 12.3 Numbers: It is a compile-time error for a class to attempt to extend
- * or implement int.
- *
- * 12.3 Numbers: It is a compile-time error for a class to attempt to extend
- * or implement double.
- *
- * 12.3 Numbers: It is a compile-time error for any type other than the types
- * int and double to attempt to extend or implement num.
- *
- * 12.4 Booleans: It is a compile-time error for a class to attempt to extend
- * or implement bool.
- *
- * 12.5 Strings: It is a compile-time error for a class to attempt to extend
- * or implement String.
- *
- * Parameters:
- * 0: the name of the type that cannot be extended
- *
- * See [IMPLEMENTS_DISALLOWED_CLASS].
- */
- static const CompileTimeErrorCode MIXIN_OF_DISALLOWED_CLASS =
- const CompileTimeErrorCode(
- 'MIXIN_OF_DISALLOWED_CLASS', "Classes cannot mixin '{0}'");
-
- /**
- * Enum proposal: It is a compile-time error to subclass, mix-in or implement
- * an enum.
- */
- static const CompileTimeErrorCode MIXIN_OF_ENUM = const CompileTimeErrorCode(
- 'MIXIN_OF_ENUM', "Classes cannot mixin an enum");
-
- /**
- * 9.1 Mixin Application: It is a compile-time error if <i>M</i> does not
- * denote a class or mixin available in the immediately enclosing scope.
- */
- static const CompileTimeErrorCode MIXIN_OF_NON_CLASS =
- const CompileTimeErrorCode(
- 'MIXIN_OF_NON_CLASS', "Classes can only mixin other classes");
-
- /**
- * 9 Mixins: It is a compile-time error if a declared or derived mixin refers
- * to super.
- */
- static const CompileTimeErrorCode MIXIN_REFERENCES_SUPER =
- const CompileTimeErrorCode('MIXIN_REFERENCES_SUPER',
- "The class '{0}' cannot be used as a mixin because it references 'super'");
-
- /**
- * 9.1 Mixin Application: It is a compile-time error if <i>S</i> does not
- * denote a class available in the immediately enclosing scope.
- */
- static const CompileTimeErrorCode MIXIN_WITH_NON_CLASS_SUPERCLASS =
- const CompileTimeErrorCode('MIXIN_WITH_NON_CLASS_SUPERCLASS',
- "Mixin can only be applied to class");
-
- /**
- * 7.6.1 Generative Constructors: A generative constructor may be redirecting,
- * in which case its only action is to invoke another generative constructor.
- */
- static const CompileTimeErrorCode
- MULTIPLE_REDIRECTING_CONSTRUCTOR_INVOCATIONS = const CompileTimeErrorCode(
- 'MULTIPLE_REDIRECTING_CONSTRUCTOR_INVOCATIONS',
- "Constructor may have at most one 'this' redirection");
-
- /**
- * 7.6.1 Generative Constructors: Let <i>k</i> be a generative constructor.
- * Then <i>k</i> may include at most one superinitializer in its initializer
- * list or a compile time error occurs.
- */
- static const CompileTimeErrorCode MULTIPLE_SUPER_INITIALIZERS =
- const CompileTimeErrorCode('MULTIPLE_SUPER_INITIALIZERS',
- "Constructor may have at most one 'super' initializer");
-
- /**
- * 11 Metadata: Metadata consists of a series of annotations, each of which
- * begin with the character @, followed by a constant expression that must be
- * either a reference to a compile-time constant variable, or a call to a
- * constant constructor.
- */
- static const CompileTimeErrorCode NO_ANNOTATION_CONSTRUCTOR_ARGUMENTS =
- const CompileTimeErrorCode('NO_ANNOTATION_CONSTRUCTOR_ARGUMENTS',
- "Annotation creation must have arguments");
-
- /**
- * 7.6.1 Generative Constructors: If no superinitializer is provided, an
- * implicit superinitializer of the form <b>super</b>() is added at the end of
- * <i>k</i>'s initializer list, unless the enclosing class is class
- * <i>Object</i>.
- *
- * 7.6.1 Generative constructors. It is a compile-time error if class <i>S</i>
- * does not declare a generative constructor named <i>S</i> (respectively
- * <i>S.id</i>)
- */
- static const CompileTimeErrorCode NO_DEFAULT_SUPER_CONSTRUCTOR_EXPLICIT =
- const CompileTimeErrorCode('NO_DEFAULT_SUPER_CONSTRUCTOR_EXPLICIT',
- "The class '{0}' does not have a default constructor");
-
- /**
- * 7.6 Constructors: Iff no constructor is specified for a class <i>C</i>, it
- * implicitly has a default constructor C() : <b>super<b>() {}, unless
- * <i>C</i> is class <i>Object</i>.
- *
- * 7.6.1 Generative constructors. It is a compile-time error if class <i>S</i>
- * does not declare a generative constructor named <i>S</i> (respectively
- * <i>S.id</i>)
- */
- static const CompileTimeErrorCode NO_DEFAULT_SUPER_CONSTRUCTOR_IMPLICIT =
- const CompileTimeErrorCode('NO_DEFAULT_SUPER_CONSTRUCTOR_IMPLICIT',
- "The class '{0}' does not have a default constructor");
-
- /**
- * 13.2 Expression Statements: It is a compile-time error if a non-constant
- * map literal that has no explicit type arguments appears in a place where a
- * statement is expected.
- */
- static const CompileTimeErrorCode NON_CONST_MAP_AS_EXPRESSION_STATEMENT =
- const CompileTimeErrorCode('NON_CONST_MAP_AS_EXPRESSION_STATEMENT',
- "A non-constant map literal without type arguments cannot be used as an expression statement");
-
- /**
- * 13.9 Switch: Given a switch statement of the form <i>switch (e) {
- * label<sub>11</sub> … label<sub>1j1</sub> case e<sub>1</sub>:
- * s<sub>1</sub> … label<sub>n1</sub> … label<sub>njn</sub> case
- * e<sub>n</sub>: s<sub>n</sub> default: s<sub>n+1</sub>}</i> or the form
- * <i>switch (e) { label<sub>11</sub> … label<sub>1j1</sub> case
- * e<sub>1</sub>: s<sub>1</sub> … label<sub>n1</sub> …
- * label<sub>njn</sub> case e<sub>n</sub>: s<sub>n</sub>}</i>, it is a
- * compile-time error if the expressions <i>e<sub>k</sub></i> are not
- * compile-time constants, for all <i>1 <= k <= n</i>.
- */
- static const CompileTimeErrorCode NON_CONSTANT_CASE_EXPRESSION =
- const CompileTimeErrorCode(
- 'NON_CONSTANT_CASE_EXPRESSION', "Case expressions must be constant");
-
- /**
- * 13.9 Switch: Given a switch statement of the form <i>switch (e) {
- * label<sub>11</sub> … label<sub>1j1</sub> case e<sub>1</sub>:
- * s<sub>1</sub> … label<sub>n1</sub> … label<sub>njn</sub> case
- * e<sub>n</sub>: s<sub>n</sub> default: s<sub>n+1</sub>}</i> or the form
- * <i>switch (e) { label<sub>11</sub> … label<sub>1j1</sub> case
- * e<sub>1</sub>: s<sub>1</sub> … label<sub>n1</sub> …
- * label<sub>njn</sub> case e<sub>n</sub>: s<sub>n</sub>}</i>, it is a
- * compile-time error if the expressions <i>e<sub>k</sub></i> are not
- * compile-time constants, for all <i>1 <= k <= n</i>.
- *
- * 12.1 Constants: A qualified reference to a static constant variable that is
- * not qualified by a deferred prefix.
- */
- static const CompileTimeErrorCode
- NON_CONSTANT_CASE_EXPRESSION_FROM_DEFERRED_LIBRARY =
- const CompileTimeErrorCode(
- 'NON_CONSTANT_CASE_EXPRESSION_FROM_DEFERRED_LIBRARY',
- "Constant values from a deferred library cannot be used as a case expression");
-
- /**
- * 6.2.2 Optional Formals: It is a compile-time error if the default value of
- * an optional parameter is not a compile-time constant.
- */
- static const CompileTimeErrorCode NON_CONSTANT_DEFAULT_VALUE =
- const CompileTimeErrorCode('NON_CONSTANT_DEFAULT_VALUE',
- "Default values of an optional parameter must be constant");
-
- /**
- * 6.2.2 Optional Formals: It is a compile-time error if the default value of
- * an optional parameter is not a compile-time constant.
- *
- * 12.1 Constants: A qualified reference to a static constant variable that is
- * not qualified by a deferred prefix.
- */
- static const CompileTimeErrorCode
- NON_CONSTANT_DEFAULT_VALUE_FROM_DEFERRED_LIBRARY =
- const CompileTimeErrorCode(
- 'NON_CONSTANT_DEFAULT_VALUE_FROM_DEFERRED_LIBRARY',
- "Constant values from a deferred library cannot be used as a default parameter value");
-
- /**
- * 12.6 Lists: It is a compile time error if an element of a constant list
- * literal is not a compile-time constant.
- */
- static const CompileTimeErrorCode NON_CONSTANT_LIST_ELEMENT =
- const CompileTimeErrorCode('NON_CONSTANT_LIST_ELEMENT',
- "'const' lists must have all constant values");
-
- /**
- * 12.6 Lists: It is a compile time error if an element of a constant list
- * literal is not a compile-time constant.
- *
- * 12.1 Constants: A qualified reference to a static constant variable that is
- * not qualified by a deferred prefix.
- */
- static const CompileTimeErrorCode
- NON_CONSTANT_LIST_ELEMENT_FROM_DEFERRED_LIBRARY =
- const CompileTimeErrorCode(
- 'NON_CONSTANT_LIST_ELEMENT_FROM_DEFERRED_LIBRARY',
- "Constant values from a deferred library cannot be used as values in a 'const' list");
-
- /**
- * 12.7 Maps: It is a compile time error if either a key or a value of an
- * entry in a constant map literal is not a compile-time constant.
- */
- static const CompileTimeErrorCode NON_CONSTANT_MAP_KEY =
- const CompileTimeErrorCode(
- 'NON_CONSTANT_MAP_KEY', "The keys in a map must be constant");
-
- /**
- * 12.7 Maps: It is a compile time error if either a key or a value of an
- * entry in a constant map literal is not a compile-time constant.
- *
- * 12.1 Constants: A qualified reference to a static constant variable that is
- * not qualified by a deferred prefix.
- */
- static const CompileTimeErrorCode NON_CONSTANT_MAP_KEY_FROM_DEFERRED_LIBRARY =
- const CompileTimeErrorCode('NON_CONSTANT_MAP_KEY_FROM_DEFERRED_LIBRARY',
- "Constant values from a deferred library cannot be used as keys in a map");
-
- /**
- * 12.7 Maps: It is a compile time error if either a key or a value of an
- * entry in a constant map literal is not a compile-time constant.
- */
- static const CompileTimeErrorCode NON_CONSTANT_MAP_VALUE =
- const CompileTimeErrorCode('NON_CONSTANT_MAP_VALUE',
- "The values in a 'const' map must be constant");
-
- /**
- * 12.7 Maps: It is a compile time error if either a key or a value of an
- * entry in a constant map literal is not a compile-time constant.
- *
- * 12.1 Constants: A qualified reference to a static constant variable that is
- * not qualified by a deferred prefix.
- */
- static const CompileTimeErrorCode
- NON_CONSTANT_MAP_VALUE_FROM_DEFERRED_LIBRARY = const CompileTimeErrorCode(
- 'NON_CONSTANT_MAP_VALUE_FROM_DEFERRED_LIBRARY',
- "Constant values from a deferred library cannot be used as values in a 'const' map");
-
- /**
- * 11 Metadata: Metadata consists of a series of annotations, each of which
- * begin with the character @, followed by a constant expression that must be
- * either a reference to a compile-time constant variable, or a call to a
- * constant constructor.
- *
- * "From deferred library" case is covered by
- * [CompileTimeErrorCode.INVALID_ANNOTATION_FROM_DEFERRED_LIBRARY].
- */
- static const CompileTimeErrorCode NON_CONSTANT_ANNOTATION_CONSTRUCTOR =
- const CompileTimeErrorCode('NON_CONSTANT_ANNOTATION_CONSTRUCTOR',
- "Annotation creation can use only 'const' constructor");
-
- /**
- * 7.6.3 Constant Constructors: Any expression that appears within the
- * initializer list of a constant constructor must be a potentially constant
- * expression, or a compile-time error occurs.
- */
- static const CompileTimeErrorCode NON_CONSTANT_VALUE_IN_INITIALIZER =
- const CompileTimeErrorCode('NON_CONSTANT_VALUE_IN_INITIALIZER',
- "Initializer expressions in constant constructors must be constants");
-
- /**
- * 7.6.3 Constant Constructors: Any expression that appears within the
- * initializer list of a constant constructor must be a potentially constant
- * expression, or a compile-time error occurs.
- *
- * 12.1 Constants: A qualified reference to a static constant variable that is
- * not qualified by a deferred prefix.
- */
- static const CompileTimeErrorCode
- NON_CONSTANT_VALUE_IN_INITIALIZER_FROM_DEFERRED_LIBRARY =
- const CompileTimeErrorCode(
- 'NON_CONSTANT_VALUE_IN_INITIALIZER_FROM_DEFERRED_LIBRARY',
- "Constant values from a deferred library cannot be used as constant initializers");
-
- /**
- * 12.14.2 Binding Actuals to Formals: It is a static warning if <i>m < h</i>
- * or if <i>m > n</i>.
- *
- * 12.11.2 Const: It is a compile-time error if evaluation of a constant
- * object results in an uncaught exception being thrown.
- *
- * Parameters:
- * 0: the expected number of required arguments
- * 1: the actual number of positional arguments given
- */
- static const CompileTimeErrorCode NOT_ENOUGH_REQUIRED_ARGUMENTS =
- const CompileTimeErrorCode('NOT_ENOUGH_REQUIRED_ARGUMENTS',
- "{0} required argument(s) expected, but {1} found");
-
- /**
- * 7.6.1 Generative Constructors: Let <i>C</i> be the class in which the
- * superinitializer appears and let <i>S</i> be the superclass of <i>C</i>.
- * Let <i>k</i> be a generative constructor. It is a compile-time error if
- * class <i>S</i> does not declare a generative constructor named <i>S</i>
- * (respectively <i>S.id</i>)
- */
- static const CompileTimeErrorCode NON_GENERATIVE_CONSTRUCTOR =
- const CompileTimeErrorCode('NON_GENERATIVE_CONSTRUCTOR',
- "The generative constructor '{0}' expected, but factory found");
-
- /**
- * 7.9 Superclasses: It is a compile-time error to specify an extends clause
- * for class Object.
- */
- static const CompileTimeErrorCode OBJECT_CANNOT_EXTEND_ANOTHER_CLASS =
- const CompileTimeErrorCode('OBJECT_CANNOT_EXTEND_ANOTHER_CLASS', "");
-
- /**
- * 7.1.1 Operators: It is a compile-time error to declare an optional
- * parameter in an operator.
- */
- static const CompileTimeErrorCode OPTIONAL_PARAMETER_IN_OPERATOR =
- const CompileTimeErrorCode('OPTIONAL_PARAMETER_IN_OPERATOR',
- "Optional parameters are not allowed when defining an operator");
-
- /**
- * 14.3 Parts: It is a compile time error if the contents of the URI are not a
- * valid part declaration.
- *
- * Parameters:
- * 0: the uri pointing to a non-library declaration
- */
- static const CompileTimeErrorCode PART_OF_NON_PART =
- const CompileTimeErrorCode('PART_OF_NON_PART',
- "The included part '{0}' must have a part-of directive");
-
- /**
- * 14.1 Imports: It is a compile-time error if the current library declares a
- * top-level member named <i>p</i>.
- */
- static const CompileTimeErrorCode PREFIX_COLLIDES_WITH_TOP_LEVEL_MEMBER =
- const CompileTimeErrorCode('PREFIX_COLLIDES_WITH_TOP_LEVEL_MEMBER',
- "The name '{0}' is already used as an import prefix and cannot be used to name a top-level element");
-
- /**
- * 16.32 Identifier Reference: If d is a prefix p, a compile-time error
- * occurs unless the token immediately following d is '.'.
- */
- static const CompileTimeErrorCode PREFIX_IDENTIFIER_NOT_FOLLOWED_BY_DOT =
- const CompileTimeErrorCode('PREFIX_IDENTIFIER_NOT_FOLLOWED_BY_DOT',
- "The name '{0}' refers to an import prefix, so it must be followed by '.'");
-
- /**
- * 6.2.2 Optional Formals: It is a compile-time error if the name of a named
- * optional parameter begins with an '_' character.
- */
- static const CompileTimeErrorCode PRIVATE_OPTIONAL_PARAMETER =
- const CompileTimeErrorCode('PRIVATE_OPTIONAL_PARAMETER',
- "Named optional parameters cannot start with an underscore");
-
- /**
- * 12.1 Constants: It is a compile-time error if the value of a compile-time
- * constant expression depends on itself.
- */
- static const CompileTimeErrorCode RECURSIVE_COMPILE_TIME_CONSTANT =
- const CompileTimeErrorCode('RECURSIVE_COMPILE_TIME_CONSTANT',
- "Compile-time constant expression depends on itself");
-
- /**
- * 7.6.1 Generative Constructors: A generative constructor may be redirecting,
- * in which case its only action is to invoke another generative constructor.
- *
- * TODO(scheglov) review this later, there are no explicit "it is a
- * compile-time error" in specification. But it was added to the co19 and
- * there is same error for factories.
- *
- * https://code.google.com/p/dart/issues/detail?id=954
- */
- static const CompileTimeErrorCode RECURSIVE_CONSTRUCTOR_REDIRECT =
- const CompileTimeErrorCode('RECURSIVE_CONSTRUCTOR_REDIRECT',
- "Cycle in redirecting generative constructors");
-
- /**
- * 7.6.2 Factories: It is a compile-time error if a redirecting factory
- * constructor redirects to itself, either directly or indirectly via a
- * sequence of redirections.
- */
- static const CompileTimeErrorCode RECURSIVE_FACTORY_REDIRECT =
- const CompileTimeErrorCode('RECURSIVE_FACTORY_REDIRECT',
- "Cycle in redirecting factory constructors");
-
- /**
- * 7.10 Superinterfaces: It is a compile-time error if the interface of a
- * class <i>C</i> is a superinterface of itself.
- *
- * 8.1 Superinterfaces: It is a compile-time error if an interface is a
- * superinterface of itself.
- *
- * 7.9 Superclasses: It is a compile-time error if a class <i>C</i> is a
- * superclass of itself.
- *
- * Parameters:
- * 0: the name of the class that implements itself recursively
- * 1: a string representation of the implements loop
- */
- static const CompileTimeErrorCode RECURSIVE_INTERFACE_INHERITANCE =
- const CompileTimeErrorCode('RECURSIVE_INTERFACE_INHERITANCE',
- "'{0}' cannot be a superinterface of itself: {1}");
-
- /**
- * 7.10 Superinterfaces: It is a compile-time error if the interface of a
- * class <i>C</i> is a superinterface of itself.
- *
- * 8.1 Superinterfaces: It is a compile-time error if an interface is a
- * superinterface of itself.
- *
- * 7.9 Superclasses: It is a compile-time error if a class <i>C</i> is a
- * superclass of itself.
- *
- * Parameters:
- * 0: the name of the class that implements itself recursively
- */
- static const CompileTimeErrorCode
- RECURSIVE_INTERFACE_INHERITANCE_BASE_CASE_EXTENDS =
- const CompileTimeErrorCode(
- 'RECURSIVE_INTERFACE_INHERITANCE_BASE_CASE_EXTENDS',
- "'{0}' cannot extend itself");
-
- /**
- * 7.10 Superinterfaces: It is a compile-time error if the interface of a
- * class <i>C</i> is a superinterface of itself.
- *
- * 8.1 Superinterfaces: It is a compile-time error if an interface is a
- * superinterface of itself.
- *
- * 7.9 Superclasses: It is a compile-time error if a class <i>C</i> is a
- * superclass of itself.
- *
- * Parameters:
- * 0: the name of the class that implements itself recursively
- */
- static const CompileTimeErrorCode
- RECURSIVE_INTERFACE_INHERITANCE_BASE_CASE_IMPLEMENTS =
- const CompileTimeErrorCode(
- 'RECURSIVE_INTERFACE_INHERITANCE_BASE_CASE_IMPLEMENTS',
- "'{0}' cannot implement itself");
-
- /**
- * 7.10 Superinterfaces: It is a compile-time error if the interface of a
- * class <i>C</i> is a superinterface of itself.
- *
- * 8.1 Superinterfaces: It is a compile-time error if an interface is a
- * superinterface of itself.
- *
- * 7.9 Superclasses: It is a compile-time error if a class <i>C</i> is a
- * superclass of itself.
- *
- * Parameters:
- * 0: the name of the class that implements itself recursively
- */
- static const CompileTimeErrorCode
- RECURSIVE_INTERFACE_INHERITANCE_BASE_CASE_WITH =
- const CompileTimeErrorCode(
- 'RECURSIVE_INTERFACE_INHERITANCE_BASE_CASE_WITH',
- "'{0}' cannot use itself as a mixin");
-
- /**
- * 7.6.2 Factories: It is a compile-time error if <i>k</i> is prefixed with
- * the const modifier but <i>k'</i> is not a constant constructor.
- */
- static const CompileTimeErrorCode REDIRECT_TO_MISSING_CONSTRUCTOR =
- const CompileTimeErrorCode('REDIRECT_TO_MISSING_CONSTRUCTOR',
- "The constructor '{0}' could not be found in '{1}'");
-
- /**
- * 7.6.2 Factories: It is a compile-time error if <i>k</i> is prefixed with
- * the const modifier but <i>k'</i> is not a constant constructor.
- */
- static const CompileTimeErrorCode REDIRECT_TO_NON_CLASS =
- const CompileTimeErrorCode('REDIRECT_TO_NON_CLASS',
- "The name '{0}' is not a type and cannot be used in a redirected constructor");
-
- /**
- * 7.6.2 Factories: It is a compile-time error if <i>k</i> is prefixed with
- * the const modifier but <i>k'</i> is not a constant constructor.
- */
- static const CompileTimeErrorCode REDIRECT_TO_NON_CONST_CONSTRUCTOR =
- const CompileTimeErrorCode('REDIRECT_TO_NON_CONST_CONSTRUCTOR',
- "Constant factory constructor cannot delegate to a non-constant constructor");
-
- /**
- * 7.6.1 Generative constructors: A generative constructor may be
- * <i>redirecting</i>, in which case its only action is to invoke another
- * generative constructor.
- */
- static const CompileTimeErrorCode REDIRECT_GENERATIVE_TO_MISSING_CONSTRUCTOR =
- const CompileTimeErrorCode('REDIRECT_GENERATIVE_TO_MISSING_CONSTRUCTOR',
- "The constructor '{0}' could not be found in '{1}'");
-
- /**
- * 7.6.1 Generative constructors: A generative constructor may be
- * <i>redirecting</i>, in which case its only action is to invoke another
- * generative constructor.
- */
- static const CompileTimeErrorCode
- REDIRECT_GENERATIVE_TO_NON_GENERATIVE_CONSTRUCTOR =
- const CompileTimeErrorCode(
- 'REDIRECT_GENERATIVE_TO_NON_GENERATIVE_CONSTRUCTOR',
- "Generative constructor cannot redirect to a factory constructor");
-
- /**
- * 5 Variables: A local variable may only be referenced at a source code
- * location that is after its initializer, if any, is complete, or a
- * compile-time error occurs.
- */
- static const CompileTimeErrorCode REFERENCED_BEFORE_DECLARATION =
- const CompileTimeErrorCode('REFERENCED_BEFORE_DECLARATION',
- "Local variable '{0}' cannot be referenced before it is declared");
-
- /**
- * 12.8.1 Rethrow: It is a compile-time error if an expression of the form
- * <i>rethrow;</i> is not enclosed within a on-catch clause.
- */
- static const CompileTimeErrorCode RETHROW_OUTSIDE_CATCH =
- shared_messages.RETHROW_OUTSIDE_CATCH;
-
- /**
- * 13.12 Return: It is a compile-time error if a return statement of the form
- * <i>return e;</i> appears in a generative constructor.
- */
- static const CompileTimeErrorCode RETURN_IN_GENERATIVE_CONSTRUCTOR =
- shared_messages.RETURN_IN_GENERATIVE_CONSTRUCTOR;
-
- /**
- * 13.12 Return: It is a compile-time error if a return statement of the form
- * <i>return e;</i> appears in a generator function.
- */
- static const CompileTimeErrorCode RETURN_IN_GENERATOR =
- shared_messages.RETURN_IN_GENERATOR;
-
- /**
- * 14.1 Imports: It is a compile-time error if a prefix used in a deferred
- * import is used in another import clause.
- */
- static const CompileTimeErrorCode SHARED_DEFERRED_PREFIX =
- const CompileTimeErrorCode('SHARED_DEFERRED_PREFIX',
- "The prefix of a deferred import cannot be used in other import directives");
-
- /**
- * 12.15.4 Super Invocation: A super method invocation <i>i</i> has the form
- * <i>super.m(a<sub>1</sub>, …, a<sub>n</sub>, x<sub>n+1</sub>:
- * a<sub>n+1</sub>, … x<sub>n+k</sub>: a<sub>n+k</sub>)</i>. It is a
- * compile-time error if a super method invocation occurs in a top-level
- * function or variable initializer, in an instance variable initializer or
- * initializer list, in class Object, in a factory constructor, or in a static
- * method or variable initializer.
- */
- static const CompileTimeErrorCode SUPER_IN_INVALID_CONTEXT =
- const CompileTimeErrorCode(
- 'SUPER_IN_INVALID_CONTEXT', "Invalid context for 'super' invocation");
-
- /**
- * 7.6.1 Generative Constructors: A generative constructor may be redirecting,
- * in which case its only action is to invoke another generative constructor.
- */
- static const CompileTimeErrorCode SUPER_IN_REDIRECTING_CONSTRUCTOR =
- const CompileTimeErrorCode('SUPER_IN_REDIRECTING_CONSTRUCTOR',
- "The redirecting constructor cannot have a 'super' initializer");
-
- /**
- * 7.6.1 Generative Constructors: Let <i>k</i> be a generative constructor. It
- * is a compile-time error if a generative constructor of class Object
- * includes a superinitializer.
- */
- static const CompileTimeErrorCode SUPER_INITIALIZER_IN_OBJECT =
- const CompileTimeErrorCode('SUPER_INITIALIZER_IN_OBJECT', "");
-
- /**
- * 12.11 Instance Creation: It is a static type warning if any of the type
- * arguments to a constructor of a generic type <i>G</i> invoked by a new
- * expression or a constant object expression are not subtypes of the bounds
- * of the corresponding formal type parameters of <i>G</i>.
- *
- * 12.11.1 New: If T is malformed a dynamic error occurs. In checked mode, if
- * T is mal-bounded a dynamic error occurs.
- *
- * 12.1 Constants: It is a compile-time error if evaluation of a compile-time
- * constant would raise an exception.
- *
- * Parameters:
- * 0: the name of the type used in the instance creation that should be
- * limited by the bound as specified in the class declaration
- * 1: the name of the bounding type
- *
- * See [StaticTypeWarningCode.TYPE_ARGUMENT_NOT_MATCHING_BOUNDS].
- */
- static const CompileTimeErrorCode TYPE_ARGUMENT_NOT_MATCHING_BOUNDS =
- const CompileTimeErrorCode(
- 'TYPE_ARGUMENT_NOT_MATCHING_BOUNDS', "'{0}' does not extend '{1}'");
-
- /**
- * 15.3.1 Typedef: Any self reference, either directly, or recursively via
- * another typedef, is a compile time error.
- */
- static const CompileTimeErrorCode TYPE_ALIAS_CANNOT_REFERENCE_ITSELF =
- const CompileTimeErrorCode('TYPE_ALIAS_CANNOT_REFERENCE_ITSELF',
- "Type alias cannot reference itself directly or recursively via another typedef");
-
- /**
- * 12.11.2 Const: It is a compile-time error if <i>T</i> is not a class
- * accessible in the current scope, optionally followed by type arguments.
- */
- static const CompileTimeErrorCode UNDEFINED_CLASS =
- const CompileTimeErrorCode('UNDEFINED_CLASS', "Undefined class '{0}'");
-
- /**
- * 7.6.1 Generative Constructors: Let <i>C</i> be the class in which the
- * superinitializer appears and let <i>S</i> be the superclass of <i>C</i>.
- * Let <i>k</i> be a generative constructor. It is a compile-time error if
- * class <i>S</i> does not declare a generative constructor named <i>S</i>
- * (respectively <i>S.id</i>)
- */
- static const CompileTimeErrorCode UNDEFINED_CONSTRUCTOR_IN_INITIALIZER =
- const CompileTimeErrorCode('UNDEFINED_CONSTRUCTOR_IN_INITIALIZER',
- "The class '{0}' does not have a generative constructor '{1}'");
-
- /**
- * 7.6.1 Generative Constructors: Let <i>C</i> be the class in which the
- * superinitializer appears and let <i>S</i> be the superclass of <i>C</i>.
- * Let <i>k</i> be a generative constructor. It is a compile-time error if
- * class <i>S</i> does not declare a generative constructor named <i>S</i>
- * (respectively <i>S.id</i>)
- */
- static const CompileTimeErrorCode
- UNDEFINED_CONSTRUCTOR_IN_INITIALIZER_DEFAULT = const CompileTimeErrorCode(
- 'UNDEFINED_CONSTRUCTOR_IN_INITIALIZER_DEFAULT',
- "The class '{0}' does not have a default generative constructor");
-
- /**
- * 12.14.2 Binding Actuals to Formals: Furthermore, each <i>q<sub>i</sub></i>,
- * <i>1<=i<=l</i>, must have a corresponding named parameter in the set
- * {<i>p<sub>n+1</sub></i> ... <i>p<sub>n+k</sub></i>} or a static warning
- * occurs.
- *
- * 12.11.2 Const: It is a compile-time error if evaluation of a constant
- * object results in an uncaught exception being thrown.
- *
- * Parameters:
- * 0: the name of the requested named parameter
- */
- static const CompileTimeErrorCode UNDEFINED_NAMED_PARAMETER =
- const CompileTimeErrorCode('UNDEFINED_NAMED_PARAMETER',
- "The named parameter '{0}' is not defined");
-
- /**
- * 14.2 Exports: It is a compile-time error if the compilation unit found at
- * the specified URI is not a library declaration.
- *
- * 14.1 Imports: It is a compile-time error if the compilation unit found at
- * the specified URI is not a library declaration.
- *
- * 14.3 Parts: It is a compile time error if the contents of the URI are not a
- * valid part declaration.
- *
- * Parameters:
- * 0: the URI pointing to a non-existent file
- *
- * See [INVALID_URI], [URI_HAS_NOT_BEEN_GENERATED].
- */
- static const CompileTimeErrorCode URI_DOES_NOT_EXIST =
- const CompileTimeErrorCode(
- 'URI_DOES_NOT_EXIST', "Target of URI does not exist: '{0}'");
-
- /**
- * Just like [URI_DOES_NOT_EXIST], but used when the URI refers to a file that
- * is expected to be generated.
- *
- * Parameters:
- * 0: the URI pointing to a non-existent file
- *
- * See [INVALID_URI], [URI_DOES_NOT_EXIST].
- */
- static const CompileTimeErrorCode URI_HAS_NOT_BEEN_GENERATED =
- const CompileTimeErrorCode('URI_HAS_NOT_BEEN_GENERATED',
- "Target of URI has not been generated: '{0}'");
-
- /**
- * 14.1 Imports: It is a compile-time error if <i>x</i> is not a compile-time
- * constant, or if <i>x</i> involves string interpolation.
- *
- * 14.3 Parts: It is a compile-time error if <i>s</i> is not a compile-time
- * constant, or if <i>s</i> involves string interpolation.
- *
- * 14.5 URIs: It is a compile-time error if the string literal <i>x</i> that
- * describes a URI is not a compile-time constant, or if <i>x</i> involves
- * string interpolation.
- */
- static const CompileTimeErrorCode URI_WITH_INTERPOLATION =
- const CompileTimeErrorCode(
- 'URI_WITH_INTERPOLATION', "URIs cannot use string interpolation");
-
- /**
- * 7.1.1 Operators: It is a compile-time error if the arity of the
- * user-declared operator []= is not 2. It is a compile time error if the
- * arity of a user-declared operator with one of the names: <, >, <=,
- * >=, ==, +, /, ~/, *, %, |, ^, &, <<, >>, [] is not 1. It is
- * a compile time error if the arity of the user-declared operator - is not 0
- * or 1. It is a compile time error if the arity of the user-declared operator
- * ~ is not 0.
- *
- * Parameters:
- * 0: the name of the declared operator
- * 1: the number of parameters expected
- * 2: the number of parameters found in the operator declaration
- */
- static const CompileTimeErrorCode WRONG_NUMBER_OF_PARAMETERS_FOR_OPERATOR =
- const CompileTimeErrorCode('WRONG_NUMBER_OF_PARAMETERS_FOR_OPERATOR',
- "Operator '{0}' should declare exactly {1} parameter(s), but {2} found");
-
- /**
- * 7.1.1 Operators: It is a compile time error if the arity of the
- * user-declared operator - is not 0 or 1.
- *
- * Parameters:
- * 0: the number of parameters found in the operator declaration
- */
- static const CompileTimeErrorCode
- WRONG_NUMBER_OF_PARAMETERS_FOR_OPERATOR_MINUS =
- const CompileTimeErrorCode(
- 'WRONG_NUMBER_OF_PARAMETERS_FOR_OPERATOR_MINUS',
- "Operator '-' should declare 0 or 1 parameter, but {0} found");
-
- /**
- * 7.3 Setters: It is a compile-time error if a setter's formal parameter list
- * does not include exactly one required formal parameter <i>p</i>.
- */
- static const CompileTimeErrorCode WRONG_NUMBER_OF_PARAMETERS_FOR_SETTER =
- const CompileTimeErrorCode('WRONG_NUMBER_OF_PARAMETERS_FOR_SETTER',
- "Setters should declare exactly one required parameter");
-
- /**
- * ?? Yield: It is a compile-time error if a yield statement appears in a
- * function that is not a generator function.
- */
- static const CompileTimeErrorCode YIELD_EACH_IN_NON_GENERATOR =
- const CompileTimeErrorCode('YIELD_EACH_IN_NON_GENERATOR',
- "Yield-each statements must be in a generator function (one marked with either 'async*' or 'sync*')");
-
- /**
- * ?? Yield: It is a compile-time error if a yield statement appears in a
- * function that is not a generator function.
- */
- static const CompileTimeErrorCode YIELD_IN_NON_GENERATOR =
- const CompileTimeErrorCode('YIELD_IN_NON_GENERATOR',
- "Yield statements must be in a generator function (one marked with either 'async*' or 'sync*')");
-
- /**
- * Initialize a newly created error code to have the given [name]. The message
- * associated with the error will be created from the given [message]
- * template. The correction associated with the error will be created from the
- * given [correction] template.
- */
- const CompileTimeErrorCode(String name, String message, [String correction])
- : super(name, message, correction);
-
- @override
- ErrorSeverity get errorSeverity => ErrorType.COMPILE_TIME_ERROR.severity;
-
- @override
- ErrorType get type => ErrorType.COMPILE_TIME_ERROR;
-}
-
-/**
- * An error code associated with an [AnalysisError].
- *
- * Generally, we want to provide messages that consist of three sentences. From
- * the user's perspective these sentences should explain:
- * 1. what is wrong,
- * 2. why is it wrong, and
- * 3. how do I fix it.
- * However, we combine the first two in the [message] and the last in the
- * [correction].
- */
-abstract class ErrorCode {
- /**
- * Engine error code values.
- */
- static const List<ErrorCode> values = const [
- //
- // Manually generated. FWIW, this get's you most of the way there:
- //
- // > grep 'static const .*Code' (error.dart|parser|scanner.dart)
- // | awk '{print $3"."$4","}'
- //
- // error.dart:
- //
- AnalysisOptionsErrorCode.PARSE_ERROR,
- AnalysisOptionsWarningCode.UNSUPPORTED_OPTION_WITH_LEGAL_VALUES,
- AnalysisOptionsWarningCode.UNSUPPORTED_OPTION_WITH_LEGAL_VALUE,
- AnalysisOptionsWarningCode.UNSUPPORTED_VALUE,
- AnalysisOptionsWarningCode.UNRECOGNIZED_ERROR_CODE,
- CheckedModeCompileTimeErrorCode.CONST_CONSTRUCTOR_FIELD_TYPE_MISMATCH,
- CheckedModeCompileTimeErrorCode.CONST_CONSTRUCTOR_PARAM_TYPE_MISMATCH,
- CheckedModeCompileTimeErrorCode.CONST_FIELD_INITIALIZER_NOT_ASSIGNABLE,
- CheckedModeCompileTimeErrorCode.LIST_ELEMENT_TYPE_NOT_ASSIGNABLE,
- CheckedModeCompileTimeErrorCode.MAP_KEY_TYPE_NOT_ASSIGNABLE,
- CheckedModeCompileTimeErrorCode.MAP_VALUE_TYPE_NOT_ASSIGNABLE,
- CheckedModeCompileTimeErrorCode.VARIABLE_TYPE_MISMATCH,
- CompileTimeErrorCode.ACCESS_PRIVATE_ENUM_FIELD,
- CompileTimeErrorCode.AMBIGUOUS_EXPORT,
- CompileTimeErrorCode.ANNOTATION_WITH_NON_CLASS,
- CompileTimeErrorCode.ARGUMENT_DEFINITION_TEST_NON_PARAMETER,
- CompileTimeErrorCode.ASYNC_FOR_IN_WRONG_CONTEXT,
- CompileTimeErrorCode.AWAIT_IN_WRONG_CONTEXT,
- CompileTimeErrorCode.BUILT_IN_IDENTIFIER_AS_TYPE,
- CompileTimeErrorCode.BUILT_IN_IDENTIFIER_AS_TYPE_NAME,
- CompileTimeErrorCode.BUILT_IN_IDENTIFIER_AS_TYPEDEF_NAME,
- CompileTimeErrorCode.BUILT_IN_IDENTIFIER_AS_TYPE_PARAMETER_NAME,
- CompileTimeErrorCode.CASE_EXPRESSION_TYPE_IMPLEMENTS_EQUALS,
- CompileTimeErrorCode.COMPILE_TIME_CONSTANT_RAISES_EXCEPTION,
- CompileTimeErrorCode.CONFLICTING_GETTER_AND_METHOD,
- CompileTimeErrorCode.CONFLICTING_METHOD_AND_GETTER,
- CompileTimeErrorCode.CONFLICTING_CONSTRUCTOR_NAME_AND_FIELD,
- CompileTimeErrorCode.CONFLICTING_CONSTRUCTOR_NAME_AND_METHOD,
- CompileTimeErrorCode.CONFLICTING_TYPE_VARIABLE_AND_CLASS,
- CompileTimeErrorCode.CONFLICTING_TYPE_VARIABLE_AND_MEMBER,
- CompileTimeErrorCode.CONST_CONSTRUCTOR_THROWS_EXCEPTION,
- CompileTimeErrorCode.CONST_CONSTRUCTOR_WITH_FIELD_INITIALIZED_BY_NON_CONST,
- CompileTimeErrorCode.CONST_CONSTRUCTOR_WITH_MIXIN,
- CompileTimeErrorCode.CONST_CONSTRUCTOR_WITH_NON_CONST_SUPER,
- CompileTimeErrorCode.CONST_CONSTRUCTOR_WITH_NON_FINAL_FIELD,
- CompileTimeErrorCode.CONST_DEFERRED_CLASS,
- CompileTimeErrorCode.CONST_FORMAL_PARAMETER,
- CompileTimeErrorCode.CONST_INITIALIZED_WITH_NON_CONSTANT_VALUE,
- CompileTimeErrorCode
- .CONST_INITIALIZED_WITH_NON_CONSTANT_VALUE_FROM_DEFERRED_LIBRARY,
- CompileTimeErrorCode.CONST_INSTANCE_FIELD,
- CompileTimeErrorCode.CONST_MAP_KEY_EXPRESSION_TYPE_IMPLEMENTS_EQUALS,
- CompileTimeErrorCode.CONST_NOT_INITIALIZED,
- CompileTimeErrorCode.CONST_EVAL_TYPE_BOOL,
- CompileTimeErrorCode.CONST_EVAL_TYPE_BOOL_NUM_STRING,
- CompileTimeErrorCode.CONST_EVAL_TYPE_INT,
- CompileTimeErrorCode.CONST_EVAL_TYPE_NUM,
- CompileTimeErrorCode.CONST_EVAL_THROWS_EXCEPTION,
- CompileTimeErrorCode.CONST_EVAL_THROWS_IDBZE,
- CompileTimeErrorCode.CONST_WITH_INVALID_TYPE_PARAMETERS,
- CompileTimeErrorCode.CONST_WITH_NON_CONST,
- CompileTimeErrorCode.CONST_WITH_NON_CONSTANT_ARGUMENT,
- CompileTimeErrorCode.CONST_WITH_NON_TYPE,
- CompileTimeErrorCode.CONST_WITH_TYPE_PARAMETERS,
- CompileTimeErrorCode.CONST_WITH_UNDEFINED_CONSTRUCTOR,
- CompileTimeErrorCode.CONST_WITH_UNDEFINED_CONSTRUCTOR_DEFAULT,
- CompileTimeErrorCode.DEFAULT_VALUE_IN_FUNCTION_TYPE_ALIAS,
- CompileTimeErrorCode.DEFAULT_VALUE_IN_FUNCTION_TYPED_PARAMETER,
- CompileTimeErrorCode.DEFAULT_VALUE_IN_REDIRECTING_FACTORY_CONSTRUCTOR,
- CompileTimeErrorCode.DUPLICATE_CONSTRUCTOR_DEFAULT,
- CompileTimeErrorCode.DUPLICATE_CONSTRUCTOR_NAME,
- CompileTimeErrorCode.DUPLICATE_DEFINITION,
- CompileTimeErrorCode.DUPLICATE_DEFINITION_INHERITANCE,
- CompileTimeErrorCode.DUPLICATE_NAMED_ARGUMENT,
- CompileTimeErrorCode.EXPORT_INTERNAL_LIBRARY,
- CompileTimeErrorCode.EXPORT_OF_NON_LIBRARY,
- CompileTimeErrorCode.EXTENDS_ENUM,
- CompileTimeErrorCode.EXTENDS_NON_CLASS,
- CompileTimeErrorCode.EXTENDS_DISALLOWED_CLASS,
- CompileTimeErrorCode.EXTENDS_DEFERRED_CLASS,
- CompileTimeErrorCode.EXTRA_ARGUMENT_TO_ASSERT,
- CompileTimeErrorCode.EXTRA_POSITIONAL_ARGUMENTS,
- CompileTimeErrorCode.FIELD_INITIALIZED_BY_MULTIPLE_INITIALIZERS,
- CompileTimeErrorCode.FIELD_INITIALIZED_IN_PARAMETER_AND_INITIALIZER,
- CompileTimeErrorCode.FINAL_INITIALIZED_MULTIPLE_TIMES,
- CompileTimeErrorCode.FIELD_INITIALIZER_FACTORY_CONSTRUCTOR,
- CompileTimeErrorCode.FIELD_INITIALIZER_OUTSIDE_CONSTRUCTOR,
- CompileTimeErrorCode.FIELD_INITIALIZER_REDIRECTING_CONSTRUCTOR,
- CompileTimeErrorCode.GETTER_AND_METHOD_WITH_SAME_NAME,
- CompileTimeErrorCode.IMPLEMENTS_DEFERRED_CLASS,
- CompileTimeErrorCode.IMPLEMENTS_DISALLOWED_CLASS,
- CompileTimeErrorCode.IMPLEMENTS_DYNAMIC,
- CompileTimeErrorCode.IMPLEMENTS_ENUM,
- CompileTimeErrorCode.IMPLEMENTS_NON_CLASS,
- CompileTimeErrorCode.IMPLEMENTS_REPEATED,
- CompileTimeErrorCode.IMPLEMENTS_SUPER_CLASS,
- CompileTimeErrorCode.IMPLICIT_THIS_REFERENCE_IN_INITIALIZER,
- CompileTimeErrorCode.IMPORT_INTERNAL_LIBRARY,
- CompileTimeErrorCode.IMPORT_OF_NON_LIBRARY,
- CompileTimeErrorCode.INCONSISTENT_CASE_EXPRESSION_TYPES,
- CompileTimeErrorCode.INITIALIZER_FOR_NON_EXISTENT_FIELD,
- CompileTimeErrorCode.INITIALIZER_FOR_STATIC_FIELD,
- CompileTimeErrorCode.INITIALIZING_FORMAL_FOR_NON_EXISTENT_FIELD,
- CompileTimeErrorCode.INITIALIZING_FORMAL_FOR_STATIC_FIELD,
- CompileTimeErrorCode.INSTANCE_MEMBER_ACCESS_FROM_FACTORY,
- CompileTimeErrorCode.INSTANCE_MEMBER_ACCESS_FROM_STATIC,
- CompileTimeErrorCode.INSTANTIATE_ENUM,
- CompileTimeErrorCode.INVALID_ANNOTATION,
- CompileTimeErrorCode.INVALID_ANNOTATION_FROM_DEFERRED_LIBRARY,
- CompileTimeErrorCode.INVALID_IDENTIFIER_IN_ASYNC,
- CompileTimeErrorCode.INVALID_MODIFIER_ON_CONSTRUCTOR,
- CompileTimeErrorCode.INVALID_MODIFIER_ON_SETTER,
- CompileTimeErrorCode.INVALID_CONSTANT,
- CompileTimeErrorCode.INVALID_CONSTRUCTOR_NAME,
- CompileTimeErrorCode.INVALID_FACTORY_NAME_NOT_A_CLASS,
- CompileTimeErrorCode.INVALID_REFERENCE_TO_THIS,
- CompileTimeErrorCode.INVALID_TYPE_ARGUMENT_IN_CONST_LIST,
- CompileTimeErrorCode.INVALID_TYPE_ARGUMENT_IN_CONST_MAP,
- CompileTimeErrorCode.INVALID_URI,
- CompileTimeErrorCode.LABEL_IN_OUTER_SCOPE,
- CompileTimeErrorCode.LABEL_UNDEFINED,
- CompileTimeErrorCode.MEMBER_WITH_CLASS_NAME,
- CompileTimeErrorCode.METHOD_AND_GETTER_WITH_SAME_NAME,
- CompileTimeErrorCode.MISSING_CONST_IN_LIST_LITERAL,
- CompileTimeErrorCode.MISSING_CONST_IN_MAP_LITERAL,
- CompileTimeErrorCode.MIXIN_DECLARES_CONSTRUCTOR,
- CompileTimeErrorCode.MIXIN_DEFERRED_CLASS,
- CompileTimeErrorCode.MIXIN_HAS_NO_CONSTRUCTORS,
- CompileTimeErrorCode.MIXIN_INHERITS_FROM_NOT_OBJECT,
- CompileTimeErrorCode.MIXIN_OF_DISALLOWED_CLASS,
- CompileTimeErrorCode.MIXIN_OF_ENUM,
- CompileTimeErrorCode.MIXIN_OF_NON_CLASS,
- CompileTimeErrorCode.MIXIN_REFERENCES_SUPER,
- CompileTimeErrorCode.MIXIN_WITH_NON_CLASS_SUPERCLASS,
- CompileTimeErrorCode.MULTIPLE_REDIRECTING_CONSTRUCTOR_INVOCATIONS,
- CompileTimeErrorCode.MULTIPLE_SUPER_INITIALIZERS,
- CompileTimeErrorCode.NO_ANNOTATION_CONSTRUCTOR_ARGUMENTS,
- CompileTimeErrorCode.NO_DEFAULT_SUPER_CONSTRUCTOR_EXPLICIT,
- CompileTimeErrorCode.NO_DEFAULT_SUPER_CONSTRUCTOR_IMPLICIT,
- CompileTimeErrorCode.NON_CONST_MAP_AS_EXPRESSION_STATEMENT,
- CompileTimeErrorCode.NON_CONSTANT_CASE_EXPRESSION,
- CompileTimeErrorCode.NON_CONSTANT_CASE_EXPRESSION_FROM_DEFERRED_LIBRARY,
- CompileTimeErrorCode.NON_CONSTANT_DEFAULT_VALUE,
- CompileTimeErrorCode.NON_CONSTANT_DEFAULT_VALUE_FROM_DEFERRED_LIBRARY,
- CompileTimeErrorCode.NON_CONSTANT_LIST_ELEMENT,
- CompileTimeErrorCode.NON_CONSTANT_LIST_ELEMENT_FROM_DEFERRED_LIBRARY,
- CompileTimeErrorCode.NON_CONSTANT_MAP_KEY,
- CompileTimeErrorCode.NON_CONSTANT_MAP_KEY_FROM_DEFERRED_LIBRARY,
- CompileTimeErrorCode.NON_CONSTANT_MAP_VALUE,
- CompileTimeErrorCode.NON_CONSTANT_MAP_VALUE_FROM_DEFERRED_LIBRARY,
- CompileTimeErrorCode.NON_CONSTANT_ANNOTATION_CONSTRUCTOR,
- CompileTimeErrorCode.NON_CONSTANT_VALUE_IN_INITIALIZER,
- CompileTimeErrorCode
- .NON_CONSTANT_VALUE_IN_INITIALIZER_FROM_DEFERRED_LIBRARY,
- CompileTimeErrorCode.NOT_ENOUGH_REQUIRED_ARGUMENTS,
- CompileTimeErrorCode.NON_GENERATIVE_CONSTRUCTOR,
- CompileTimeErrorCode.OBJECT_CANNOT_EXTEND_ANOTHER_CLASS,
- CompileTimeErrorCode.OPTIONAL_PARAMETER_IN_OPERATOR,
- CompileTimeErrorCode.PART_OF_NON_PART,
- CompileTimeErrorCode.PREFIX_COLLIDES_WITH_TOP_LEVEL_MEMBER,
- CompileTimeErrorCode.PREFIX_IDENTIFIER_NOT_FOLLOWED_BY_DOT,
- CompileTimeErrorCode.PRIVATE_OPTIONAL_PARAMETER,
- CompileTimeErrorCode.RECURSIVE_COMPILE_TIME_CONSTANT,
- CompileTimeErrorCode.RECURSIVE_CONSTRUCTOR_REDIRECT,
- CompileTimeErrorCode.RECURSIVE_FACTORY_REDIRECT,
- CompileTimeErrorCode.RECURSIVE_INTERFACE_INHERITANCE,
- CompileTimeErrorCode.RECURSIVE_INTERFACE_INHERITANCE_BASE_CASE_EXTENDS,
- CompileTimeErrorCode.RECURSIVE_INTERFACE_INHERITANCE_BASE_CASE_IMPLEMENTS,
- CompileTimeErrorCode.RECURSIVE_INTERFACE_INHERITANCE_BASE_CASE_WITH,
- CompileTimeErrorCode.REDIRECT_TO_MISSING_CONSTRUCTOR,
- CompileTimeErrorCode.REDIRECT_TO_NON_CLASS,
- CompileTimeErrorCode.REDIRECT_TO_NON_CONST_CONSTRUCTOR,
- CompileTimeErrorCode.REDIRECT_GENERATIVE_TO_MISSING_CONSTRUCTOR,
- CompileTimeErrorCode.REDIRECT_GENERATIVE_TO_NON_GENERATIVE_CONSTRUCTOR,
- CompileTimeErrorCode.REFERENCED_BEFORE_DECLARATION,
- CompileTimeErrorCode.RETHROW_OUTSIDE_CATCH,
- CompileTimeErrorCode.RETURN_IN_GENERATIVE_CONSTRUCTOR,
- CompileTimeErrorCode.RETURN_IN_GENERATOR,
- CompileTimeErrorCode.SHARED_DEFERRED_PREFIX,
- CompileTimeErrorCode.SUPER_IN_INVALID_CONTEXT,
- CompileTimeErrorCode.SUPER_IN_REDIRECTING_CONSTRUCTOR,
- CompileTimeErrorCode.SUPER_INITIALIZER_IN_OBJECT,
- CompileTimeErrorCode.TYPE_ARGUMENT_NOT_MATCHING_BOUNDS,
- CompileTimeErrorCode.TYPE_ALIAS_CANNOT_REFERENCE_ITSELF,
- CompileTimeErrorCode.UNDEFINED_CLASS,
- CompileTimeErrorCode.UNDEFINED_CONSTRUCTOR_IN_INITIALIZER,
- CompileTimeErrorCode.UNDEFINED_CONSTRUCTOR_IN_INITIALIZER_DEFAULT,
- CompileTimeErrorCode.UNDEFINED_NAMED_PARAMETER,
- CompileTimeErrorCode.URI_DOES_NOT_EXIST,
- CompileTimeErrorCode.URI_WITH_INTERPOLATION,
- CompileTimeErrorCode.WRONG_NUMBER_OF_PARAMETERS_FOR_OPERATOR,
- CompileTimeErrorCode.WRONG_NUMBER_OF_PARAMETERS_FOR_OPERATOR_MINUS,
- CompileTimeErrorCode.WRONG_NUMBER_OF_PARAMETERS_FOR_SETTER,
- CompileTimeErrorCode.YIELD_EACH_IN_NON_GENERATOR,
- CompileTimeErrorCode.YIELD_IN_NON_GENERATOR,
- HintCode.ARGUMENT_TYPE_NOT_ASSIGNABLE,
- HintCode.CAN_BE_NULL_AFTER_NULL_AWARE,
- HintCode.DEAD_CODE,
- HintCode.DEAD_CODE_CATCH_FOLLOWING_CATCH,
- HintCode.DEAD_CODE_ON_CATCH_SUBTYPE,
- HintCode.DEPRECATED_MEMBER_USE,
- HintCode.DUPLICATE_IMPORT,
- HintCode.DIVISION_OPTIMIZATION,
- HintCode.INVALID_FACTORY_ANNOTATION,
- HintCode.INVALID_FACTORY_METHOD_DECL,
- HintCode.INVALID_FACTORY_METHOD_IMPL,
- HintCode.IS_DOUBLE,
- HintCode.IS_INT,
- HintCode.IS_NOT_DOUBLE,
- HintCode.IS_NOT_INT,
- HintCode.IMPORT_DEFERRED_LIBRARY_WITH_LOAD_FUNCTION,
- HintCode.INVALID_ASSIGNMENT,
- HintCode.INVALID_USE_OF_PROTECTED_MEMBER,
- HintCode.MISSING_JS_LIB_ANNOTATION,
- HintCode.MISSING_REQUIRED_PARAM,
- HintCode.MISSING_REQUIRED_PARAM_WITH_DETAILS,
- HintCode.MISSING_RETURN,
- HintCode.NULL_AWARE_IN_CONDITION,
- HintCode.OVERRIDE_ON_NON_OVERRIDING_GETTER,
- HintCode.OVERRIDE_ON_NON_OVERRIDING_FIELD,
- HintCode.OVERRIDE_ON_NON_OVERRIDING_METHOD,
- HintCode.OVERRIDE_ON_NON_OVERRIDING_SETTER,
- HintCode.OVERRIDE_EQUALS_BUT_NOT_HASH_CODE,
- HintCode.TYPE_CHECK_IS_NOT_NULL,
- HintCode.TYPE_CHECK_IS_NULL,
- HintCode.UNDEFINED_GETTER,
- HintCode.UNDEFINED_HIDDEN_NAME,
- HintCode.UNDEFINED_METHOD,
- HintCode.UNDEFINED_OPERATOR,
- HintCode.UNDEFINED_SETTER,
- HintCode.UNDEFINED_SHOWN_NAME,
- HintCode.UNNECESSARY_CAST,
- HintCode.UNNECESSARY_NO_SUCH_METHOD,
- HintCode.UNNECESSARY_TYPE_CHECK_FALSE,
- HintCode.UNNECESSARY_TYPE_CHECK_TRUE,
- HintCode.UNUSED_ELEMENT,
- HintCode.UNUSED_FIELD,
- HintCode.UNUSED_IMPORT,
- HintCode.UNUSED_CATCH_CLAUSE,
- HintCode.UNUSED_CATCH_STACK,
- HintCode.UNUSED_LOCAL_VARIABLE,
- HintCode.UNUSED_SHOWN_NAME,
- HintCode.USE_OF_VOID_RESULT,
- HintCode.FILE_IMPORT_INSIDE_LIB_REFERENCES_FILE_OUTSIDE,
- HintCode.FILE_IMPORT_OUTSIDE_LIB_REFERENCES_FILE_INSIDE,
- HintCode.PACKAGE_IMPORT_CONTAINS_DOT_DOT,
- HtmlErrorCode.PARSE_ERROR,
- HtmlWarningCode.INVALID_URI,
- HtmlWarningCode.URI_DOES_NOT_EXIST,
- StaticTypeWarningCode.EXPECTED_ONE_LIST_TYPE_ARGUMENTS,
- StaticTypeWarningCode.EXPECTED_TWO_MAP_TYPE_ARGUMENTS,
- StaticTypeWarningCode.ILLEGAL_ASYNC_GENERATOR_RETURN_TYPE,
- StaticTypeWarningCode.ILLEGAL_ASYNC_RETURN_TYPE,
- StaticTypeWarningCode.ILLEGAL_SYNC_GENERATOR_RETURN_TYPE,
- StaticTypeWarningCode.INACCESSIBLE_SETTER,
- StaticTypeWarningCode.INCONSISTENT_METHOD_INHERITANCE,
- StaticTypeWarningCode.INSTANCE_ACCESS_TO_STATIC_MEMBER,
- StaticTypeWarningCode.INVALID_ASSIGNMENT,
- StaticTypeWarningCode.INVOCATION_OF_NON_FUNCTION,
- StaticTypeWarningCode.INVOCATION_OF_NON_FUNCTION_EXPRESSION,
- StaticTypeWarningCode.NON_BOOL_CONDITION,
- StaticTypeWarningCode.NON_BOOL_EXPRESSION,
- StaticTypeWarningCode.NON_BOOL_NEGATION_EXPRESSION,
- StaticTypeWarningCode.NON_BOOL_OPERAND,
- StaticTypeWarningCode.NON_NULLABLE_FIELD_NOT_INITIALIZED,
- StaticTypeWarningCode.NON_TYPE_AS_TYPE_ARGUMENT,
- StaticTypeWarningCode.RETURN_OF_INVALID_TYPE,
- StaticTypeWarningCode.TYPE_ARGUMENT_NOT_MATCHING_BOUNDS,
- StaticTypeWarningCode.TYPE_PARAMETER_SUPERTYPE_OF_ITS_BOUND,
- StaticTypeWarningCode.UNDEFINED_ENUM_CONSTANT,
- StaticTypeWarningCode.UNDEFINED_FUNCTION,
- StaticTypeWarningCode.UNDEFINED_GETTER,
- StaticTypeWarningCode.UNDEFINED_METHOD,
- StaticTypeWarningCode.UNDEFINED_METHOD_WITH_CONSTRUCTOR,
- StaticTypeWarningCode.UNDEFINED_OPERATOR,
- StaticTypeWarningCode.UNDEFINED_SETTER,
- StaticTypeWarningCode.UNDEFINED_SUPER_GETTER,
- StaticTypeWarningCode.UNDEFINED_SUPER_METHOD,
- StaticTypeWarningCode.UNDEFINED_SUPER_OPERATOR,
- StaticTypeWarningCode.UNDEFINED_SUPER_SETTER,
- StaticTypeWarningCode.UNQUALIFIED_REFERENCE_TO_NON_LOCAL_STATIC_MEMBER,
- StaticTypeWarningCode.WRONG_NUMBER_OF_TYPE_ARGUMENTS,
- StaticTypeWarningCode.YIELD_OF_INVALID_TYPE,
- StaticTypeWarningCode.FOR_IN_OF_INVALID_TYPE,
- StaticTypeWarningCode.FOR_IN_OF_INVALID_ELEMENT_TYPE,
- StaticWarningCode.AMBIGUOUS_IMPORT,
- StaticWarningCode.ARGUMENT_TYPE_NOT_ASSIGNABLE,
- StaticWarningCode.ASSIGNMENT_TO_CONST,
- StaticWarningCode.ASSIGNMENT_TO_FINAL,
- StaticWarningCode.ASSIGNMENT_TO_FINAL_NO_SETTER,
- StaticWarningCode.ASSIGNMENT_TO_FUNCTION,
- StaticWarningCode.ASSIGNMENT_TO_METHOD,
- StaticWarningCode.ASSIGNMENT_TO_TYPE,
- StaticWarningCode.CASE_BLOCK_NOT_TERMINATED,
- StaticWarningCode.CAST_TO_NON_TYPE,
- StaticWarningCode.CONCRETE_CLASS_WITH_ABSTRACT_MEMBER,
- StaticWarningCode.CONFLICTING_DART_IMPORT,
- StaticWarningCode.CONFLICTING_INSTANCE_GETTER_AND_SUPERCLASS_MEMBER,
- StaticWarningCode.CONFLICTING_INSTANCE_METHOD_SETTER,
- StaticWarningCode.CONFLICTING_INSTANCE_METHOD_SETTER2,
- StaticWarningCode.CONFLICTING_INSTANCE_SETTER_AND_SUPERCLASS_MEMBER,
- StaticWarningCode.CONFLICTING_STATIC_GETTER_AND_INSTANCE_SETTER,
- StaticWarningCode.CONFLICTING_STATIC_SETTER_AND_INSTANCE_MEMBER,
- StaticWarningCode.CONST_WITH_ABSTRACT_CLASS,
- StaticWarningCode.EQUAL_KEYS_IN_MAP,
- StaticWarningCode.EXPORT_DUPLICATED_LIBRARY_NAMED,
- StaticWarningCode.EXTRA_POSITIONAL_ARGUMENTS,
- StaticWarningCode.FIELD_INITIALIZED_IN_INITIALIZER_AND_DECLARATION,
- StaticWarningCode.FINAL_INITIALIZED_IN_DECLARATION_AND_CONSTRUCTOR,
- StaticWarningCode.FIELD_INITIALIZER_NOT_ASSIGNABLE,
- StaticWarningCode.FIELD_INITIALIZING_FORMAL_NOT_ASSIGNABLE,
- StaticWarningCode.FINAL_NOT_INITIALIZED,
- StaticWarningCode.FINAL_NOT_INITIALIZED_CONSTRUCTOR_1,
- StaticWarningCode.FINAL_NOT_INITIALIZED_CONSTRUCTOR_2,
- StaticWarningCode.FINAL_NOT_INITIALIZED_CONSTRUCTOR_3_PLUS,
- StaticWarningCode.FUNCTION_WITHOUT_CALL,
- StaticWarningCode.IMPORT_DUPLICATED_LIBRARY_NAMED,
- StaticWarningCode.IMPORT_OF_NON_LIBRARY,
- StaticWarningCode.INCONSISTENT_METHOD_INHERITANCE_GETTER_AND_METHOD,
- StaticWarningCode.INSTANCE_METHOD_NAME_COLLIDES_WITH_SUPERCLASS_STATIC,
- StaticWarningCode.INVALID_GETTER_OVERRIDE_RETURN_TYPE,
- StaticWarningCode.INVALID_METHOD_OVERRIDE_NAMED_PARAM_TYPE,
- StaticWarningCode.INVALID_METHOD_OVERRIDE_TYPE_PARAMETERS,
- StaticWarningCode.INVALID_METHOD_OVERRIDE_TYPE_PARAMETER_BOUND,
- StaticWarningCode.INVALID_METHOD_OVERRIDE_NORMAL_PARAM_TYPE,
- StaticWarningCode.INVALID_METHOD_OVERRIDE_OPTIONAL_PARAM_TYPE,
- StaticWarningCode.INVALID_METHOD_OVERRIDE_RETURN_TYPE,
- StaticWarningCode.INVALID_OVERRIDE_DIFFERENT_DEFAULT_VALUES_NAMED,
- StaticWarningCode.INVALID_OVERRIDE_DIFFERENT_DEFAULT_VALUES_POSITIONAL,
- StaticWarningCode.INVALID_OVERRIDE_NAMED,
- StaticWarningCode.INVALID_OVERRIDE_POSITIONAL,
- StaticWarningCode.INVALID_OVERRIDE_REQUIRED,
- StaticWarningCode.INVALID_SETTER_OVERRIDE_NORMAL_PARAM_TYPE,
- StaticWarningCode.LIST_ELEMENT_TYPE_NOT_ASSIGNABLE,
- StaticWarningCode.MAP_KEY_TYPE_NOT_ASSIGNABLE,
- StaticWarningCode.MAP_VALUE_TYPE_NOT_ASSIGNABLE,
- StaticWarningCode.MISMATCHED_GETTER_AND_SETTER_TYPES,
- StaticWarningCode.MISMATCHED_GETTER_AND_SETTER_TYPES_FROM_SUPERTYPE,
- StaticWarningCode.MIXED_RETURN_TYPES,
- StaticWarningCode.NEW_WITH_ABSTRACT_CLASS,
- StaticWarningCode.NEW_WITH_INVALID_TYPE_PARAMETERS,
- StaticWarningCode.NEW_WITH_NON_TYPE,
- StaticWarningCode.NEW_WITH_UNDEFINED_CONSTRUCTOR,
- StaticWarningCode.NEW_WITH_UNDEFINED_CONSTRUCTOR_DEFAULT,
- StaticWarningCode.NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER_FIVE_PLUS,
- StaticWarningCode.NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER_FOUR,
- StaticWarningCode.NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER_ONE,
- StaticWarningCode.NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER_THREE,
- StaticWarningCode.NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER_TWO,
- StaticWarningCode.NON_TYPE_IN_CATCH_CLAUSE,
- StaticWarningCode.NON_VOID_RETURN_FOR_OPERATOR,
- StaticWarningCode.NON_VOID_RETURN_FOR_SETTER,
- StaticWarningCode.NOT_A_TYPE,
- StaticWarningCode.NOT_ENOUGH_REQUIRED_ARGUMENTS,
- StaticWarningCode.PART_OF_DIFFERENT_LIBRARY,
- StaticWarningCode.REDIRECT_TO_INVALID_FUNCTION_TYPE,
- StaticWarningCode.REDIRECT_TO_INVALID_RETURN_TYPE,
- StaticWarningCode.REDIRECT_TO_MISSING_CONSTRUCTOR,
- StaticWarningCode.REDIRECT_TO_NON_CLASS,
- StaticWarningCode.RETURN_WITHOUT_VALUE,
- StaticWarningCode.STATIC_ACCESS_TO_INSTANCE_MEMBER,
- StaticWarningCode.SWITCH_EXPRESSION_NOT_ASSIGNABLE,
- StaticWarningCode.TYPE_ANNOTATION_DEFERRED_CLASS,
- StaticWarningCode.TYPE_TEST_WITH_NON_TYPE,
- StaticWarningCode.TYPE_TEST_WITH_UNDEFINED_NAME,
- StaticWarningCode.TYPE_PARAMETER_REFERENCED_BY_STATIC,
- StaticWarningCode.UNDEFINED_CLASS,
- StaticWarningCode.UNDEFINED_CLASS_BOOLEAN,
- StaticWarningCode.UNDEFINED_GETTER,
- StaticWarningCode.UNDEFINED_IDENTIFIER,
- StaticWarningCode.UNDEFINED_NAMED_PARAMETER,
- StaticWarningCode.UNDEFINED_SETTER,
- StaticWarningCode.UNDEFINED_STATIC_METHOD_OR_GETTER,
- StaticWarningCode.UNDEFINED_SUPER_GETTER,
- StaticWarningCode.UNDEFINED_SUPER_SETTER,
- StaticWarningCode.VOID_RETURN_FOR_GETTER,
- StaticWarningCode.MISSING_ENUM_CONSTANT_IN_SWITCH,
- StrongModeCode.ASSIGNMENT_CAST,
- StrongModeCode.DOWN_CAST_COMPOSITE,
- StrongModeCode.DOWN_CAST_IMPLICIT,
- StrongModeCode.DYNAMIC_CAST,
- StrongModeCode.DYNAMIC_INVOKE,
- StrongModeCode.IMPLICIT_DYNAMIC_FIELD,
- StrongModeCode.IMPLICIT_DYNAMIC_FUNCTION,
- StrongModeCode.IMPLICIT_DYNAMIC_INVOKE,
- StrongModeCode.IMPLICIT_DYNAMIC_LIST_LITERAL,
- StrongModeCode.IMPLICIT_DYNAMIC_MAP_LITERAL,
- StrongModeCode.IMPLICIT_DYNAMIC_METHOD,
- StrongModeCode.IMPLICIT_DYNAMIC_PARAMETER,
- StrongModeCode.IMPLICIT_DYNAMIC_RETURN,
- StrongModeCode.IMPLICIT_DYNAMIC_TYPE,
- StrongModeCode.IMPLICIT_DYNAMIC_VARIABLE,
- StrongModeCode.INFERRED_TYPE,
- StrongModeCode.INFERRED_TYPE_ALLOCATION,
- StrongModeCode.INFERRED_TYPE_CLOSURE,
- StrongModeCode.INFERRED_TYPE_LITERAL,
- StrongModeCode.INVALID_FIELD_OVERRIDE,
- StrongModeCode.INVALID_METHOD_OVERRIDE,
- StrongModeCode.INVALID_METHOD_OVERRIDE_FROM_BASE,
- StrongModeCode.INVALID_METHOD_OVERRIDE_FROM_MIXIN,
- StrongModeCode.INVALID_PARAMETER_DECLARATION,
- StrongModeCode.INVALID_SUPER_INVOCATION,
- StrongModeCode.NON_GROUND_TYPE_CHECK_INFO,
- StrongModeCode.STATIC_TYPE_ERROR,
- StrongModeCode.UNSAFE_BLOCK_CLOSURE_INFERENCE,
-
- TodoCode.TODO,
-
- //
- // parser.dart:
- //
- ParserErrorCode.ABSTRACT_CLASS_MEMBER,
- ParserErrorCode.ABSTRACT_ENUM,
- ParserErrorCode.ABSTRACT_STATIC_METHOD,
- ParserErrorCode.ABSTRACT_TOP_LEVEL_FUNCTION,
- ParserErrorCode.ABSTRACT_TOP_LEVEL_VARIABLE,
- ParserErrorCode.ABSTRACT_TYPEDEF,
- ParserErrorCode.ANNOTATION_ON_ENUM_CONSTANT,
- ParserErrorCode.ASYNC_KEYWORD_USED_AS_IDENTIFIER,
- ParserErrorCode.ASYNC_NOT_SUPPORTED,
- ParserErrorCode.BREAK_OUTSIDE_OF_LOOP,
- ParserErrorCode.CLASS_IN_CLASS,
- ParserErrorCode.COLON_IN_PLACE_OF_IN,
- ParserErrorCode.CONST_AND_FINAL,
- ParserErrorCode.CONST_AND_VAR,
- ParserErrorCode.CONST_CLASS,
- ParserErrorCode.CONST_CONSTRUCTOR_WITH_BODY,
- ParserErrorCode.CONST_ENUM,
- ParserErrorCode.CONST_FACTORY,
- ParserErrorCode.CONST_METHOD,
- ParserErrorCode.CONST_TYPEDEF,
- ParserErrorCode.CONSTRUCTOR_WITH_RETURN_TYPE,
- ParserErrorCode.CONTINUE_OUTSIDE_OF_LOOP,
- ParserErrorCode.CONTINUE_WITHOUT_LABEL_IN_CASE,
- ParserErrorCode.DEPRECATED_CLASS_TYPE_ALIAS,
- ParserErrorCode.DIRECTIVE_AFTER_DECLARATION,
- ParserErrorCode.DUPLICATE_LABEL_IN_SWITCH_STATEMENT,
- ParserErrorCode.DUPLICATED_MODIFIER,
- ParserErrorCode.EMPTY_ENUM_BODY,
- ParserErrorCode.ENUM_IN_CLASS,
- ParserErrorCode.EQUALITY_CANNOT_BE_EQUALITY_OPERAND,
- ParserErrorCode.EXPECTED_CASE_OR_DEFAULT,
- ParserErrorCode.EXPECTED_CLASS_MEMBER,
- ParserErrorCode.EXPECTED_EXECUTABLE,
- ParserErrorCode.EXPECTED_LIST_OR_MAP_LITERAL,
- ParserErrorCode.EXPECTED_STRING_LITERAL,
- ParserErrorCode.EXPECTED_TOKEN,
- ParserErrorCode.EXPECTED_TYPE_NAME,
- ParserErrorCode.EXPORT_DIRECTIVE_AFTER_PART_DIRECTIVE,
- ParserErrorCode.EXTERNAL_AFTER_CONST,
- ParserErrorCode.EXTERNAL_AFTER_FACTORY,
- ParserErrorCode.EXTERNAL_AFTER_STATIC,
- ParserErrorCode.EXTERNAL_CLASS,
- ParserErrorCode.EXTERNAL_CONSTRUCTOR_WITH_BODY,
- ParserErrorCode.EXTERNAL_ENUM,
- ParserErrorCode.EXTERNAL_FIELD,
- ParserErrorCode.EXTERNAL_GETTER_WITH_BODY,
- ParserErrorCode.EXTERNAL_METHOD_WITH_BODY,
- ParserErrorCode.EXTERNAL_OPERATOR_WITH_BODY,
- ParserErrorCode.EXTERNAL_SETTER_WITH_BODY,
- ParserErrorCode.EXTERNAL_TYPEDEF,
- ParserErrorCode.FACTORY_TOP_LEVEL_DECLARATION,
- ParserErrorCode.FACTORY_WITH_INITIALIZERS,
- ParserErrorCode.FACTORY_WITHOUT_BODY,
- ParserErrorCode.FIELD_INITIALIZER_OUTSIDE_CONSTRUCTOR,
- ParserErrorCode.FINAL_AND_VAR,
- ParserErrorCode.FINAL_CLASS,
- ParserErrorCode.FINAL_CONSTRUCTOR,
- ParserErrorCode.FINAL_ENUM,
- ParserErrorCode.FINAL_METHOD,
- ParserErrorCode.FINAL_TYPEDEF,
- ParserErrorCode.FUNCTION_TYPED_PARAMETER_VAR,
- ParserErrorCode.GETTER_IN_FUNCTION,
- ParserErrorCode.GETTER_WITH_PARAMETERS,
- ParserErrorCode.ILLEGAL_ASSIGNMENT_TO_NON_ASSIGNABLE,
- ParserErrorCode.IMPLEMENTS_BEFORE_EXTENDS,
- ParserErrorCode.IMPLEMENTS_BEFORE_WITH,
- ParserErrorCode.IMPORT_DIRECTIVE_AFTER_PART_DIRECTIVE,
- ParserErrorCode.INITIALIZED_VARIABLE_IN_FOR_EACH,
- ParserErrorCode.INVALID_AWAIT_IN_FOR,
- ParserErrorCode.INVALID_CODE_POINT,
- ParserErrorCode.INVALID_COMMENT_REFERENCE,
- ParserErrorCode.INVALID_HEX_ESCAPE,
- ParserErrorCode.INVALID_LITERAL_IN_CONFIGURATION,
- ParserErrorCode.INVALID_OPERATOR,
- ParserErrorCode.INVALID_OPERATOR_FOR_SUPER,
- ParserErrorCode.INVALID_STAR_AFTER_ASYNC,
- ParserErrorCode.INVALID_SYNC,
- ParserErrorCode.INVALID_UNICODE_ESCAPE,
- ParserErrorCode.LIBRARY_DIRECTIVE_NOT_FIRST,
- ParserErrorCode.LOCAL_FUNCTION_DECLARATION_MODIFIER,
- ParserErrorCode.MISSING_ASSIGNABLE_SELECTOR,
- ParserErrorCode.MISSING_ASSIGNMENT_IN_INITIALIZER,
- ParserErrorCode.MISSING_CATCH_OR_FINALLY,
- ParserErrorCode.MISSING_CLASS_BODY,
- ParserErrorCode.MISSING_CLOSING_PARENTHESIS,
- ParserErrorCode.MISSING_CONST_FINAL_VAR_OR_TYPE,
- ParserErrorCode.MISSING_ENUM_BODY,
- ParserErrorCode.MISSING_EXPRESSION_IN_INITIALIZER,
- ParserErrorCode.MISSING_EXPRESSION_IN_THROW,
- ParserErrorCode.MISSING_FUNCTION_BODY,
- ParserErrorCode.MISSING_FUNCTION_PARAMETERS,
- ParserErrorCode.MISSING_METHOD_PARAMETERS,
- ParserErrorCode.MISSING_GET,
- ParserErrorCode.MISSING_IDENTIFIER,
- ParserErrorCode.MISSING_INITIALIZER,
- ParserErrorCode.MISSING_KEYWORD_OPERATOR,
- ParserErrorCode.MISSING_NAME_IN_LIBRARY_DIRECTIVE,
- ParserErrorCode.MISSING_NAME_IN_PART_OF_DIRECTIVE,
- ParserErrorCode.MISSING_PREFIX_IN_DEFERRED_IMPORT,
- ParserErrorCode.MISSING_STAR_AFTER_SYNC,
- ParserErrorCode.MISSING_STATEMENT,
- ParserErrorCode.MISSING_TERMINATOR_FOR_PARAMETER_GROUP,
- ParserErrorCode.MISSING_TYPEDEF_PARAMETERS,
- ParserErrorCode.MISSING_VARIABLE_IN_FOR_EACH,
- ParserErrorCode.MIXED_PARAMETER_GROUPS,
- ParserErrorCode.MULTIPLE_EXTENDS_CLAUSES,
- ParserErrorCode.MULTIPLE_IMPLEMENTS_CLAUSES,
- ParserErrorCode.MULTIPLE_LIBRARY_DIRECTIVES,
- ParserErrorCode.MULTIPLE_NAMED_PARAMETER_GROUPS,
- ParserErrorCode.MULTIPLE_PART_OF_DIRECTIVES,
- ParserErrorCode.MULTIPLE_POSITIONAL_PARAMETER_GROUPS,
- ParserErrorCode.MULTIPLE_VARIABLES_IN_FOR_EACH,
- ParserErrorCode.MULTIPLE_WITH_CLAUSES,
- ParserErrorCode.NAMED_FUNCTION_EXPRESSION,
- ParserErrorCode.NAMED_PARAMETER_OUTSIDE_GROUP,
- ParserErrorCode.NATIVE_CLAUSE_IN_NON_SDK_CODE,
- ParserErrorCode.NATIVE_FUNCTION_BODY_IN_NON_SDK_CODE,
- ParserErrorCode.NON_CONSTRUCTOR_FACTORY,
- ParserErrorCode.NON_IDENTIFIER_LIBRARY_NAME,
- ParserErrorCode.NON_PART_OF_DIRECTIVE_IN_PART,
- ParserErrorCode.NON_STRING_LITERAL_AS_URI,
- ParserErrorCode.NON_USER_DEFINABLE_OPERATOR,
- ParserErrorCode.NORMAL_BEFORE_OPTIONAL_PARAMETERS,
- ParserErrorCode.POSITIONAL_AFTER_NAMED_ARGUMENT,
- ParserErrorCode.POSITIONAL_PARAMETER_OUTSIDE_GROUP,
- ParserErrorCode.REDIRECTING_CONSTRUCTOR_WITH_BODY,
- ParserErrorCode.REDIRECTION_IN_NON_FACTORY_CONSTRUCTOR,
- ParserErrorCode.SETTER_IN_FUNCTION,
- ParserErrorCode.STATIC_AFTER_CONST,
- ParserErrorCode.STATIC_AFTER_FINAL,
- ParserErrorCode.STATIC_AFTER_VAR,
- ParserErrorCode.STATIC_CONSTRUCTOR,
- ParserErrorCode.STATIC_GETTER_WITHOUT_BODY,
- ParserErrorCode.STATIC_OPERATOR,
- ParserErrorCode.STATIC_SETTER_WITHOUT_BODY,
- ParserErrorCode.STATIC_TOP_LEVEL_DECLARATION,
- ParserErrorCode.SWITCH_HAS_CASE_AFTER_DEFAULT_CASE,
- ParserErrorCode.SWITCH_HAS_MULTIPLE_DEFAULT_CASES,
- ParserErrorCode.TOP_LEVEL_OPERATOR,
- ParserErrorCode.TYPEDEF_IN_CLASS,
- ParserErrorCode.UNEXPECTED_TERMINATOR_FOR_PARAMETER_GROUP,
- ParserErrorCode.UNEXPECTED_TOKEN,
- ParserErrorCode.WITH_BEFORE_EXTENDS,
- ParserErrorCode.WITH_WITHOUT_EXTENDS,
- ParserErrorCode.WRONG_SEPARATOR_FOR_NAMED_PARAMETER,
- ParserErrorCode.WRONG_SEPARATOR_FOR_POSITIONAL_PARAMETER,
- ParserErrorCode.WRONG_TERMINATOR_FOR_PARAMETER_GROUP,
- ParserErrorCode.VAR_AND_TYPE,
- ParserErrorCode.VAR_AS_TYPE_NAME,
- ParserErrorCode.VAR_CLASS,
- ParserErrorCode.VAR_ENUM,
- ParserErrorCode.VAR_RETURN_TYPE,
- ParserErrorCode.VAR_TYPEDEF,
- ParserErrorCode.VOID_PARAMETER,
- ParserErrorCode.VOID_VARIABLE,
-
- //
- // scanner.dart:
- //
- ScannerErrorCode.ILLEGAL_CHARACTER,
- ScannerErrorCode.MISSING_DIGIT,
- ScannerErrorCode.MISSING_HEX_DIGIT,
- ScannerErrorCode.MISSING_QUOTE,
- ScannerErrorCode.UNABLE_GET_CONTENT,
- ScannerErrorCode.UNTERMINATED_MULTI_LINE_COMMENT,
- ScannerErrorCode.UNTERMINATED_STRING_LITERAL,
- ];
-
- /**
- * The lazy initialized map from [uniqueName] to the [ErrorCode] instance.
- */
- static HashMap<String, ErrorCode> _uniqueNameToCodeMap;
-
- /**
- * An empty list of error codes.
- */
- static const List<ErrorCode> EMPTY_LIST = const <ErrorCode>[];
-
- /**
- * The name of the error code.
- */
- final String name;
-
- /**
- * The template used to create the message to be displayed for this error. The
- * message should indicate what is wrong and why it is wrong.
- */
- final String message;
-
- /**
- * The template used to create the correction to be displayed for this error,
- * or `null` if there is no correction information for this error. The
- * correction should indicate how the user can fix the error.
- */
- final String correction;
-
- /**
- * Initialize a newly created error code to have the given [name]. The message
- * associated with the error will be created from the given [message]
- * template. The correction associated with the error will be created from the
- * given [correction] template.
- */
- const ErrorCode(this.name, this.message, [this.correction]);
-
- /**
- * The severity of the error.
- */
- ErrorSeverity get errorSeverity;
-
- /**
- * The type of the error.
- */
- ErrorType get type;
-
- /**
- * The unique name of this error code.
- */
- String get uniqueName => "$runtimeType.$name";
-
- @override
- String toString() => uniqueName;
-
- /**
- * Return the [ErrorCode] with the given [uniqueName], or `null` if not
- * found.
- */
- static ErrorCode byUniqueName(String uniqueName) {
- if (_uniqueNameToCodeMap == null) {
- _uniqueNameToCodeMap = new HashMap<String, ErrorCode>();
- for (ErrorCode errorCode in values) {
- _uniqueNameToCodeMap[errorCode.uniqueName] = errorCode;
- }
- }
- return _uniqueNameToCodeMap[uniqueName];
- }
-}
-
-/**
- * The properties that can be associated with an [AnalysisError].
- */
-class ErrorProperty<V> extends Enum<ErrorProperty> {
- /**
- * A property whose value is a list of [FieldElement]s that are final, but
- * not initialized by a constructor.
- */
- static const ErrorProperty<List<FieldElement>> NOT_INITIALIZED_FIELDS =
- const ErrorProperty<List<FieldElement>>('NOT_INITIALIZED_FIELDS', 0);
-
- /**
- * A property whose value is the name of the library that is used by all
- * of the "part of" directives, so should be used in the "library" directive.
- * Is `null` if there is no a single name used by all of the parts.
- */
- static const ErrorProperty<String> PARTS_LIBRARY_NAME =
- const ErrorProperty<String>('PARTS_LIBRARY_NAME', 1);
-
- /**
- * A property whose value is a list of [ExecutableElement] that should
- * be but are not implemented by a concrete class.
- */
- static const ErrorProperty<List<ExecutableElement>> UNIMPLEMENTED_METHODS =
- const ErrorProperty<List<ExecutableElement>>('UNIMPLEMENTED_METHODS', 2);
-
- static const List<ErrorProperty> values = const [
- NOT_INITIALIZED_FIELDS,
- PARTS_LIBRARY_NAME,
- UNIMPLEMENTED_METHODS
- ];
-
- const ErrorProperty(String name, int ordinal) : super(name, ordinal);
-}
-
-/**
- * An object used to create analysis errors and report then to an error
- * listener.
- */
-class ErrorReporter {
- /**
- * The error listener to which errors will be reported.
- */
- final AnalysisErrorListener _errorListener;
-
- /**
- * The default source to be used when reporting errors.
- */
- final Source _defaultSource;
-
- /**
- * The source to be used when reporting errors.
- */
- Source _source;
-
- /**
- * Initialize a newly created error reporter that will report errors to the
- * given [_errorListener]. Errors will be reported against the
- * [_defaultSource] unless another source is provided later.
- */
- ErrorReporter(this._errorListener, this._defaultSource) {
- if (_errorListener == null) {
- throw new ArgumentError("An error listener must be provided");
- } else if (_defaultSource == null) {
- throw new ArgumentError("A default source must be provided");
- }
- this._source = _defaultSource;
- }
-
- Source get source => _source;
-
- /**
- * Set the source to be used when reporting errors to the given [source].
- * Setting the source to `null` will cause the default source to be used.
- */
- void set source(Source source) {
- this._source = source ?? _defaultSource;
- }
-
- /**
- * Creates an error with properties with the given [errorCode] and
- * [arguments]. The [node] is used to compute the location of the error.
- */
- AnalysisErrorWithProperties newErrorWithProperties(
- ErrorCode errorCode, AstNode node, List<Object> arguments) =>
- new AnalysisErrorWithProperties(
- _source, node.offset, node.length, errorCode, arguments);
-
- /**
- * Report the given [error].
- */
- void reportError(AnalysisError error) {
- _errorListener.onError(error);
- }
-
- /**
- * Report an error with the given [errorCode] and [arguments]. The [element]
- * is used to compute the location of the error.
- */
- void reportErrorForElement(ErrorCode errorCode, Element element,
- [List<Object> arguments]) {
- int length = 0;
- if (element is ImportElement) {
- length = 6; // 'import'.length
- } else if (element is ExportElement) {
- length = 6; // 'export'.length
- } else {
- length = element.nameLength;
- }
- reportErrorForOffset(errorCode, element.nameOffset, length, arguments);
- }
-
- /**
- * Report an error with the given [errorCode] and [arguments].
- * The [node] is used to compute the location of the error.
- *
- * If the arguments contain the names of two or more types, the method
- * [reportTypeErrorForNode] should be used and the types
- * themselves (rather than their names) should be passed as arguments.
- */
- void reportErrorForNode(ErrorCode errorCode, AstNode node,
- [List<Object> arguments]) {
- reportErrorForOffset(errorCode, node.offset, node.length, arguments);
- }
-
- /**
- * Report an error with the given [errorCode] and [arguments]. The location of
- * the error is specified by the given [offset] and [length].
- */
- void reportErrorForOffset(ErrorCode errorCode, int offset, int length,
- [List<Object> arguments]) {
- _errorListener.onError(
- new AnalysisError(_source, offset, length, errorCode, arguments));
- }
-
- /**
- * Report an error with the given [errorCode] and [arguments]. The location of
- * the error is specified by the given [span].
- */
- void reportErrorForSpan(ErrorCode errorCode, SourceSpan span,
- [List<Object> arguments]) {
- reportErrorForOffset(errorCode, span.start.offset, span.length, arguments);
- }
-
- /**
- * Report an error with the given [errorCode] and [arguments]. The [token] is
- * used to compute the location of the error.
- */
- void reportErrorForToken(ErrorCode errorCode, Token token,
- [List<Object> arguments]) {
- reportErrorForOffset(errorCode, token.offset, token.length, arguments);
- }
-
- /**
- * Report an error with the given [errorCode] and [arguments]. The [node] is
- * used to compute the location of the error. The arguments are expected to
- * contain two or more types. Convert the types into strings by using the
- * display names of the types, unless there are two or more types with the
- * same names, in which case the extended display names of the types will be
- * used in order to clarify the message.
- *
- * If there are not two or more types in the argument list, the method
- * [reportErrorForNode] should be used instead.
- */
- void reportTypeErrorForNode(
- ErrorCode errorCode, AstNode node, List<Object> arguments) {
- _convertTypeNames(arguments);
- reportErrorForOffset(errorCode, node.offset, node.length, arguments);
- }
-
- /**
- * Given an array of [arguments] that is expected to contain two or more
- * types, convert the types into strings by using the display names of the
- * types, unless there are two or more types with the same names, in which
- * case the extended display names of the types will be used in order to
- * clarify the message.
- */
- void _convertTypeNames(List<Object> arguments) {
- String displayName(DartType type) {
- if (type is FunctionType) {
- String name = type.name;
- if (name != null && name.length > 0) {
- StringBuffer buffer = new StringBuffer();
- buffer.write(name);
- (type as TypeImpl).appendTo(buffer);
- return buffer.toString();
- }
- }
- return type.displayName;
- }
-
- if (_hasEqualTypeNames(arguments)) {
- int count = arguments.length;
- for (int i = 0; i < count; i++) {
- Object argument = arguments[i];
- if (argument is DartType) {
- Element element = argument.element;
- if (element == null) {
- arguments[i] = displayName(argument);
- } else {
- arguments[i] =
- element.getExtendedDisplayName(displayName(argument));
- }
- }
- }
- } else {
- int count = arguments.length;
- for (int i = 0; i < count; i++) {
- Object argument = arguments[i];
- if (argument is DartType) {
- arguments[i] = displayName(argument);
- }
- }
- }
- }
-
- /**
- * Return `true` if the given array of [arguments] contains two or more types
- * with the same display name.
- */
- bool _hasEqualTypeNames(List<Object> arguments) {
- int count = arguments.length;
- HashSet<String> typeNames = new HashSet<String>();
- for (int i = 0; i < count; i++) {
- Object argument = arguments[i];
- if (argument is DartType && !typeNames.add(argument.displayName)) {
- return true;
- }
- }
- return false;
- }
-}
-
-/**
- * The severity of an [ErrorCode].
- */
-class ErrorSeverity extends Enum<ErrorSeverity> {
- /**
- * The severity representing a non-error. This is never used for any error
- * code, but is useful for clients.
- */
- static const ErrorSeverity NONE = const ErrorSeverity('NONE', 0, " ", "none");
-
- /**
- * The severity representing an informational level analysis issue.
- */
- static const ErrorSeverity INFO = const ErrorSeverity('INFO', 1, "I", "info");
-
- /**
- * The severity representing a warning. Warnings can become errors if the `-Werror` command
- * line flag is specified.
- */
- static const ErrorSeverity WARNING =
- const ErrorSeverity('WARNING', 2, "W", "warning");
-
- /**
- * The severity representing an error.
- */
- static const ErrorSeverity ERROR =
- const ErrorSeverity('ERROR', 3, "E", "error");
-
- static const List<ErrorSeverity> values = const [NONE, INFO, WARNING, ERROR];
-
- /**
- * The name of the severity used when producing machine output.
- */
- final String machineCode;
-
- /**
- * The name of the severity used when producing readable output.
- */
- final String displayName;
-
- /**
- * Initialize a newly created severity with the given names.
- *
- * Parameters:
- * 0: the name of the severity used when producing machine output
- * 1: the name of the severity used when producing readable output
- */
- const ErrorSeverity(
- String name, int ordinal, this.machineCode, this.displayName)
- : super(name, ordinal);
-
- /**
- * Return the severity constant that represents the greatest severity.
- */
- ErrorSeverity max(ErrorSeverity severity) =>
- this.ordinal >= severity.ordinal ? this : severity;
-}
-
-/**
- * The type of an [ErrorCode].
- */
-class ErrorType extends Enum<ErrorType> {
- /**
- * Task (todo) comments in user code.
- */
- static const ErrorType TODO = const ErrorType('TODO', 0, ErrorSeverity.INFO);
-
- /**
- * Extra analysis run over the code to follow best practices, which are not in
- * the Dart Language Specification.
- */
- static const ErrorType HINT = const ErrorType('HINT', 1, ErrorSeverity.INFO);
-
- /**
- * Compile-time errors are errors that preclude execution. A compile time
- * error must be reported by a Dart compiler before the erroneous code is
- * executed.
- */
- static const ErrorType COMPILE_TIME_ERROR =
- const ErrorType('COMPILE_TIME_ERROR', 2, ErrorSeverity.ERROR);
-
- /**
- * Checked mode compile-time errors are errors that preclude execution in
- * checked mode.
- */
- static const ErrorType CHECKED_MODE_COMPILE_TIME_ERROR = const ErrorType(
- 'CHECKED_MODE_COMPILE_TIME_ERROR', 3, ErrorSeverity.ERROR);
-
- /**
- * Static warnings are those warnings reported by the static checker. They
- * have no effect on execution. Static warnings must be provided by Dart
- * compilers used during development.
- */
- static const ErrorType STATIC_WARNING =
- const ErrorType('STATIC_WARNING', 4, ErrorSeverity.WARNING);
-
- /**
- * Many, but not all, static warnings relate to types, in which case they are
- * known as static type warnings.
- */
- static const ErrorType STATIC_TYPE_WARNING =
- const ErrorType('STATIC_TYPE_WARNING', 5, ErrorSeverity.WARNING);
-
- /**
- * Syntactic errors are errors produced as a result of input that does not
- * conform to the grammar.
- */
- static const ErrorType SYNTACTIC_ERROR =
- const ErrorType('SYNTACTIC_ERROR', 6, ErrorSeverity.ERROR);
-
- /**
- * Lint warnings describe style and best practice recommendations that can be
- * used to formalize a project's style guidelines.
- */
- static const ErrorType LINT = const ErrorType('LINT', 7, ErrorSeverity.INFO);
-
- static const List<ErrorType> values = const [
- TODO,
- HINT,
- COMPILE_TIME_ERROR,
- CHECKED_MODE_COMPILE_TIME_ERROR,
- STATIC_WARNING,
- STATIC_TYPE_WARNING,
- SYNTACTIC_ERROR,
- LINT
- ];
-
- /**
- * The severity of this type of error.
- */
- final ErrorSeverity severity;
-
- /**
- * Initialize a newly created error type to have the given [name] and
- * [severity].
- */
- const ErrorType(String name, int ordinal, this.severity)
- : super(name, ordinal);
-
- String get displayName => name.toLowerCase().replaceAll('_', ' ');
-}
-
-/**
- * The hints and coding recommendations for best practices which are not
- * mentioned in the Dart Language Specification.
- */
-class HintCode extends ErrorCode {
- /**
- * This hint is generated anywhere where the
- * [StaticWarningCode.ARGUMENT_TYPE_NOT_ASSIGNABLE] would have been generated,
- * if we used propagated information for the warnings.
- *
- * Parameters:
- * 0: the name of the actual argument type
- * 1: the name of the expected type
- */
- static const HintCode ARGUMENT_TYPE_NOT_ASSIGNABLE =
- shared_messages.ARGUMENT_TYPE_NOT_ASSIGNABLE_HINT;
-
- /**
- * When the target expression uses '?.' operator, it can be `null`, so all the
- * subsequent invocations should also use '?.' operator.
- */
- static const HintCode CAN_BE_NULL_AFTER_NULL_AWARE = const HintCode(
- 'CAN_BE_NULL_AFTER_NULL_AWARE',
- "The expression uses '?.', so can be 'null'",
- "Replace the '.' with a '?.' in the invocation");
-
- /**
- * Dead code is code that is never reached, this can happen for instance if a
- * statement follows a return statement.
- */
- static const HintCode DEAD_CODE = const HintCode('DEAD_CODE', "Dead code");
-
- /**
- * Dead code is code that is never reached. This case covers cases where the
- * user has catch clauses after `catch (e)` or `on Object catch (e)`.
- */
- static const HintCode DEAD_CODE_CATCH_FOLLOWING_CATCH = const HintCode(
- 'DEAD_CODE_CATCH_FOLLOWING_CATCH',
- "Dead code, catch clauses after a 'catch (e)' or an 'on Object catch (e)' are never reached");
-
- /**
- * Dead code is code that is never reached. This case covers cases where the
- * user has an on-catch clause such as `on A catch (e)`, where a supertype of
- * `A` was already caught.
- *
- * Parameters:
- * 0: name of the subtype
- * 1: name of the supertype
- */
- static const HintCode DEAD_CODE_ON_CATCH_SUBTYPE = const HintCode(
- 'DEAD_CODE_ON_CATCH_SUBTYPE',
- "Dead code, this on-catch block will never be executed since '{0}' is a subtype of '{1}'");
-
- /**
- * Deprecated members should not be invoked or used.
- *
- * Parameters:
- * 0: the name of the member
- */
- static const HintCode DEPRECATED_MEMBER_USE =
- const HintCode('DEPRECATED_MEMBER_USE', "'{0}' is deprecated");
-
- /**
- * Duplicate imports.
- */
- static const HintCode DUPLICATE_IMPORT =
- const HintCode('DUPLICATE_IMPORT', "Duplicate import");
-
- /**
- * Hint to use the ~/ operator.
- */
- static const HintCode DIVISION_OPTIMIZATION = const HintCode(
- 'DIVISION_OPTIMIZATION',
- "The operator x ~/ y is more efficient than (x / y).toInt()");
-
- /**
- * Hint for the `x is double` type checks.
- */
- static const HintCode IS_DOUBLE = const HintCode('IS_DOUBLE',
- "When compiled to JS, this test might return true when the left hand side is an int");
-
- /**
- * Hint for the `x is int` type checks.
- */
- static const HintCode IS_INT = const HintCode('IS_INT',
- "When compiled to JS, this test might return true when the left hand side is a double");
-
- /**
- * Hint for the `x is! double` type checks.
- */
- static const HintCode IS_NOT_DOUBLE = const HintCode('IS_NOT_DOUBLE',
- "When compiled to JS, this test might return false when the left hand side is an int");
-
- /**
- * Hint for the `x is! int` type checks.
- */
- static const HintCode IS_NOT_INT = const HintCode('IS_NOT_INT',
- "When compiled to JS, this test might return false when the left hand side is a double");
-
- /**
- * Deferred libraries shouldn't define a top level function 'loadLibrary'.
- */
- static const HintCode IMPORT_DEFERRED_LIBRARY_WITH_LOAD_FUNCTION = const HintCode(
- 'IMPORT_DEFERRED_LIBRARY_WITH_LOAD_FUNCTION',
- "The library '{0}' defines a top-level function named 'loadLibrary' which is hidden by deferring this library");
-
- /**
- * This hint is generated anywhere where the
- * [StaticTypeWarningCode.INVALID_ASSIGNMENT] would have been generated, if we
- * used propagated information for the warnings.
- *
- * Parameters:
- * 0: the name of the right hand side type
- * 1: the name of the left hand side type
- */
- static const HintCode INVALID_ASSIGNMENT = const HintCode(
- 'INVALID_ASSIGNMENT',
- "A value of type '{0}' cannot be assigned to a variable of type '{1}'");
-
- /**
- * This hint is generated anywhere a @factory annotation is associated with
- * anything other than a method.
- */
- static const HintCode INVALID_FACTORY_ANNOTATION = const HintCode(
- 'INVALID_FACTORY_ANNOTATION',
- "Only methods can be annotated as factories.");
-
- /**
- * This hint is generated anywhere a @factory annotation is associated with
- * a method that does not declare a return type.
- */
- static const HintCode INVALID_FACTORY_METHOD_DECL = const HintCode(
- 'INVALID_FACTORY_METHOD_DECL',
- "Factory method '{0}' must have a return type.");
-
- /**
- * This hint is generated anywhere a @factory annotation is associated with
- * a non-abstract method that can return anything other than a newly allocated
- * object.
- *
- * Parameters:
- * 0: the name of the method
- */
- static const HintCode INVALID_FACTORY_METHOD_IMPL = const HintCode(
- 'INVALID_FACTORY_METHOD_IMPL',
- "Factory method '{0}' does not return a newly allocated object.");
-
- /**
- * This hint is generated anywhere where a member annotated with `@protected`
- * is used outside an instance member of a subclass.
- *
- * Parameters:
- * 0: the name of the member
- * 1: the name of the defining class
- */
- static const HintCode INVALID_USE_OF_PROTECTED_MEMBER = const HintCode(
- 'INVALID_USE_OF_PROTECTED_MEMBER',
- "The member '{0}' can only be used within instance members of subclasses of '{1}'");
-
- /**
- * Generate a hint for a constructor, function or method invocation where a
- * required parameter is missing.
- *
- * Parameters:
- * 0: the name of the parameter
- */
- static const HintCode MISSING_REQUIRED_PARAM = const HintCode(
- 'MISSING_REQUIRED_PARAM', "The parameter '{0}' is required.");
-
- /**
- * Generate a hint for a constructor, function or method invocation where a
- * required parameter is missing.
- *
- * Parameters:
- * 0: the name of the parameter
- * 1: message details
- */
- static const HintCode MISSING_REQUIRED_PARAM_WITH_DETAILS = const HintCode(
- 'MISSING_REQUIRED_PARAM_WITH_DETAILS',
- "The parameter '{0}' is required. {1}");
-
- /**
- * Generate a hint for an element that is annotated with `@JS(...)` whose
- * library declaration is not similarly annotated.
- */
- static const HintCode MISSING_JS_LIB_ANNOTATION = const HintCode(
- 'MISSING_JS_LIB_ANNOTATION',
- "The @JS() annotation can only be used if it is also declared on the library directive.");
-
- /**
- * Generate a hint for methods or functions that have a return type, but do
- * not have a non-void return statement on all branches. At the end of methods
- * or functions with no return, Dart implicitly returns `null`, avoiding these
- * implicit returns is considered a best practice.
- *
- * Parameters:
- * 0: the name of the declared return type
- */
- static const HintCode MISSING_RETURN = const HintCode(
- 'MISSING_RETURN',
- "This function declares a return type of '{0}', but does not end with a return statement",
- "Either add a return statement or change the return type to 'void'");
-
- /**
- * Generate a hint for methods that override methods annotated `@mustCallSuper`
- * that do not invoke the overridden super method.
- *
- * Parameters:
- * 0: the name of the class declaring the overriden method
- */
- static const HintCode MUST_CALL_SUPER = const HintCode(
- 'MUST_CALL_SUPER',
- "This method overrides a method annotated as @mustCall super in '{0}', "
- "but does invoke the overriden method");
-
- /**
- * A condition in a control flow statement could evaluate to `null` because it
- * uses the null-aware '?.' operator.
- */
- static const HintCode NULL_AWARE_IN_CONDITION = const HintCode(
- 'NULL_AWARE_IN_CONDITION',
- "The value of the '?.' operator can be 'null', which is not appropriate in a condition",
- "Replace the '?.' with a '.', testing the left-hand side for null if necessary");
-
- /**
- * A getter with the override annotation does not override an existing getter.
- */
- static const HintCode OVERRIDE_ON_NON_OVERRIDING_GETTER = const HintCode(
- 'OVERRIDE_ON_NON_OVERRIDING_GETTER',
- "Getter does not override an inherited getter");
-
- /**
- * A field with the override annotation does not override a getter or setter.
- */
- static const HintCode OVERRIDE_ON_NON_OVERRIDING_FIELD = const HintCode(
- 'OVERRIDE_ON_NON_OVERRIDING_FIELD',
- "Field does not override an inherited getter or setter");
-
- /**
- * A method with the override annotation does not override an existing method.
- */
- static const HintCode OVERRIDE_ON_NON_OVERRIDING_METHOD = const HintCode(
- 'OVERRIDE_ON_NON_OVERRIDING_METHOD',
- "Method does not override an inherited method");
-
- /**
- * A setter with the override annotation does not override an existing setter.
- */
- static const HintCode OVERRIDE_ON_NON_OVERRIDING_SETTER = const HintCode(
- 'OVERRIDE_ON_NON_OVERRIDING_SETTER',
- "Setter does not override an inherited setter");
-
- /**
- * Hint for classes that override equals, but not hashCode.
- *
- * Parameters:
- * 0: the name of the current class
- */
- static const HintCode OVERRIDE_EQUALS_BUT_NOT_HASH_CODE = const HintCode(
- 'OVERRIDE_EQUALS_BUT_NOT_HASH_CODE',
- "The class '{0}' overrides 'operator==', but not 'get hashCode'");
-
- /**
- * Type checks of the type `x is! Null` should be done with `x != null`.
- */
- static const HintCode TYPE_CHECK_IS_NOT_NULL = const HintCode(
- 'TYPE_CHECK_IS_NOT_NULL',
- "Tests for non-null should be done with '!= null'");
-
- /**
- * Type checks of the type `x is Null` should be done with `x == null`.
- */
- static const HintCode TYPE_CHECK_IS_NULL = const HintCode(
- 'TYPE_CHECK_IS_NULL', "Tests for null should be done with '== null'");
-
- /**
- * This hint is generated anywhere where the
- * [StaticTypeWarningCode.UNDEFINED_GETTER] or
- * [StaticWarningCode.UNDEFINED_GETTER] would have been generated, if we used
- * propagated information for the warnings.
- *
- * Parameters:
- * 0: the name of the getter
- * 1: the name of the enclosing type where the getter is being looked for
- */
- static const HintCode UNDEFINED_GETTER =
- shared_messages.UNDEFINED_GETTER_HINT;
-
- /**
- * An undefined name hidden in an import or export directive.
- */
- static const HintCode UNDEFINED_HIDDEN_NAME = const HintCode(
- 'UNDEFINED_HIDDEN_NAME',
- "The library '{0}' doesn't export a member with the hidden name '{1}'");
-
- /**
- * This hint is generated anywhere where the
- * [StaticTypeWarningCode.UNDEFINED_METHOD] would have been generated, if we
- * used propagated information for the warnings.
- *
- * Parameters:
- * 0: the name of the method that is undefined
- * 1: the resolved type name that the method lookup is happening on
- */
- static const HintCode UNDEFINED_METHOD =
- shared_messages.UNDEFINED_METHOD_HINT;
-
- /**
- * This hint is generated anywhere where the
- * [StaticTypeWarningCode.UNDEFINED_OPERATOR] would have been generated, if we
- * used propagated information for the warnings.
- *
- * Parameters:
- * 0: the name of the operator
- * 1: the name of the enclosing type where the operator is being looked for
- */
- static const HintCode UNDEFINED_OPERATOR =
- shared_messages.UNDEFINED_OPERATOR_HINT;
-
- /**
- * This hint is generated anywhere where the
- * [StaticTypeWarningCode.UNDEFINED_SETTER] or
- * [StaticWarningCode.UNDEFINED_SETTER] would have been generated, if we used
- * propagated information for the warnings.
- *
- * Parameters:
- * 0: the name of the setter
- * 1: the name of the enclosing type where the setter is being looked for
- */
- static const HintCode UNDEFINED_SETTER =
- shared_messages.UNDEFINED_SETTER_HINT;
-
- /**
- * An undefined name shown in an import or export directive.
- */
- static const HintCode UNDEFINED_SHOWN_NAME = const HintCode(
- 'UNDEFINED_SHOWN_NAME',
- "The library '{0}' doesn't export a member with the shown name '{1}'");
-
- /**
- * Unnecessary cast.
- */
- static const HintCode UNNECESSARY_CAST =
- const HintCode('UNNECESSARY_CAST', "Unnecessary cast");
-
- /**
- * Unnecessary `noSuchMethod` declaration.
- */
- static const HintCode UNNECESSARY_NO_SUCH_METHOD = const HintCode(
- 'UNNECESSARY_NO_SUCH_METHOD', "Unnecessary 'noSuchMethod' declaration");
-
- /**
- * Unnecessary type checks, the result is always true.
- */
- static const HintCode UNNECESSARY_TYPE_CHECK_FALSE = const HintCode(
- 'UNNECESSARY_TYPE_CHECK_FALSE',
- "Unnecessary type check, the result is always false");
-
- /**
- * Unnecessary type checks, the result is always false.
- */
- static const HintCode UNNECESSARY_TYPE_CHECK_TRUE = const HintCode(
- 'UNNECESSARY_TYPE_CHECK_TRUE',
- "Unnecessary type check, the result is always true");
-
- /**
- * See [Modifier.IS_USED_IN_LIBRARY].
- */
- static const HintCode UNUSED_ELEMENT =
- const HintCode('UNUSED_ELEMENT', "The {0} '{1}' is not used");
-
- /**
- * Unused fields are fields which are never read.
- */
- static const HintCode UNUSED_FIELD = const HintCode(
- 'UNUSED_FIELD', "The value of the field '{0}' is not used");
-
- /**
- * Unused imports are imports which are never used.
- */
- static const HintCode UNUSED_IMPORT =
- const HintCode('UNUSED_IMPORT', "Unused import");
-
- /**
- * Unused catch exception variables.
- */
- static const HintCode UNUSED_CATCH_CLAUSE = const HintCode(
- 'UNUSED_CATCH_CLAUSE',
- "The exception variable '{0}' is not used, so the 'catch' clause can be removed");
-
- /**
- * Unused catch stack trace variables.
- */
- static const HintCode UNUSED_CATCH_STACK = const HintCode(
- 'UNUSED_CATCH_STACK',
- "The stack trace variable '{0}' is not used and can be removed");
-
- /**
- * Unused local variables are local variables which are never read.
- */
- static const HintCode UNUSED_LOCAL_VARIABLE = const HintCode(
- 'UNUSED_LOCAL_VARIABLE',
- "The value of the local variable '{0}' is not used");
-
- /**
- * Unused shown names are names shown on imports which are never used.
- */
- static const HintCode UNUSED_SHOWN_NAME = const HintCode(
- 'UNUSED_SHOWN_NAME', "The name {0} is shown, but not used.");
-
- /**
- * Hint for cases where the source expects a method or function to return a
- * non-void result, but the method or function signature returns void.
- *
- * Parameters:
- * 0: the name of the method or function that returns void
- */
- static const HintCode USE_OF_VOID_RESULT = const HintCode(
- 'USE_OF_VOID_RESULT',
- "The result of '{0}' is being used, even though it is declared to be 'void'");
-
- /**
- * It is a bad practice for a source file in a package "lib" directory
- * hierarchy to traverse outside that directory hierarchy. For example, a
- * source file in the "lib" directory should not contain a directive such as
- * `import '../web/some.dart'` which references a file outside the lib
- * directory.
- */
- static const HintCode FILE_IMPORT_INSIDE_LIB_REFERENCES_FILE_OUTSIDE =
- const HintCode('FILE_IMPORT_INSIDE_LIB_REFERENCES_FILE_OUTSIDE',
- "A file in the 'lib' directory hierarchy should not reference a file outside that hierarchy");
-
- /**
- * It is a bad practice for a source file ouside a package "lib" directory
- * hierarchy to traverse into that directory hierarchy. For example, a source
- * file in the "web" directory should not contain a directive such as
- * `import '../lib/some.dart'` which references a file inside the lib
- * directory.
- */
- static const HintCode FILE_IMPORT_OUTSIDE_LIB_REFERENCES_FILE_INSIDE =
- const HintCode('FILE_IMPORT_OUTSIDE_LIB_REFERENCES_FILE_INSIDE',
- "A file outside the 'lib' directory hierarchy should not reference a file inside that hierarchy. Use a package: reference instead.");
-
- /**
- * It is a bad practice for a package import to reference anything outside the
- * given package, or more generally, it is bad practice for a package import
- * to contain a "..". For example, a source file should not contain a
- * directive such as `import 'package:foo/../some.dart'`.
- */
- static const HintCode PACKAGE_IMPORT_CONTAINS_DOT_DOT = const HintCode(
- 'PACKAGE_IMPORT_CONTAINS_DOT_DOT',
- "A package import should not contain '..'");
-
- /**
- * Initialize a newly created error code to have the given [name]. The message
- * associated with the error will be created from the given [message]
- * template. The correction associated with the error will be created from the
- * given [correction] template.
- */
- const HintCode(String name, String message, [String correction])
- : super(name, message, correction);
-
- @override
- ErrorSeverity get errorSeverity => ErrorType.HINT.severity;
-
- @override
- ErrorType get type => ErrorType.HINT;
-}
-
-/**
- * The error codes used for errors in HTML files. The convention for this
- * class is for the name of the error code to indicate the problem that caused
- * the error to be generated and for the error message to explain what is wrong
- * and, when appropriate, how the problem can be corrected.
- */
-class HtmlErrorCode extends ErrorCode {
- /**
- * An error code indicating that there is a syntactic error in the file.
- *
- * Parameters:
- * 0: the error message from the parse error
- */
- static const HtmlErrorCode PARSE_ERROR =
- const HtmlErrorCode('PARSE_ERROR', '{0}');
-
- /**
- * Initialize a newly created error code to have the given [name]. The message
- * associated with the error will be created from the given [message]
- * template. The correction associated with the error will be created from the
- * given [correction] template.
- */
- const HtmlErrorCode(String name, String message, [String correction])
- : super(name, message, correction);
-
- @override
- ErrorSeverity get errorSeverity => ErrorSeverity.ERROR;
-
- @override
- ErrorType get type => ErrorType.COMPILE_TIME_ERROR;
-}
-
-/**
- * The error codes used for warnings in HTML files. The convention for this
- * class is for the name of the error code to indicate the problem that caused
- * the error to be generated and for the error message to explain what is wrong
- * and, when appropriate, how the problem can be corrected.
- */
-class HtmlWarningCode extends ErrorCode {
- /**
- * An error code indicating that the value of the 'src' attribute of a Dart
- * script tag is not a valid URI.
- *
- * Parameters:
- * 0: the URI that is invalid
- */
- static const HtmlWarningCode INVALID_URI =
- const HtmlWarningCode('INVALID_URI', "Invalid URI syntax: '{0}'");
-
- /**
- * An error code indicating that the value of the 'src' attribute of a Dart
- * script tag references a file that does not exist.
- *
- * Parameters:
- * 0: the URI pointing to a non-existent file
- */
- static const HtmlWarningCode URI_DOES_NOT_EXIST = const HtmlWarningCode(
- 'URI_DOES_NOT_EXIST', "Target of URI does not exist: '{0}'");
-
- /**
- * Initialize a newly created error code to have the given [name]. The message
- * associated with the error will be created from the given [message]
- * template. The correction associated with the error will be created from the
- * given [correction] template.
- */
- const HtmlWarningCode(String name, String message, [String correction])
- : super(name, message, correction);
-
- @override
- ErrorSeverity get errorSeverity => ErrorSeverity.WARNING;
-
- @override
- ErrorType get type => ErrorType.STATIC_WARNING;
-}
-
-/**
- * Defines style and best practice recommendations.
- *
- * Unlike [HintCode]s, which are akin to traditional static warnings from a
- * compiler, lint recommendations focus on matters of style and practices that
- * might aggregated to define a project's style guide.
- */
-class LintCode extends ErrorCode {
- const LintCode(String name, String message, [String correction])
- : super(name, message, correction);
-
- @override
- ErrorSeverity get errorSeverity => ErrorSeverity.INFO;
-
- @override
- ErrorType get type => ErrorType.LINT;
-}
-
-/**
- * The error codes used for static type warnings. The convention for this class
- * is for the name of the error code to indicate the problem that caused the
- * error to be generated and for the error message to explain what is wrong and,
- * when appropriate, how the problem can be corrected.
- */
-class StaticTypeWarningCode extends ErrorCode {
- /**
- * 12.7 Lists: A fresh instance (7.6.1) <i>a</i>, of size <i>n</i>, whose
- * class implements the built-in class <i>List<E></i> is allocated.
- *
- * Parameters:
- * 0: the number of provided type arguments
- */
- static const StaticTypeWarningCode EXPECTED_ONE_LIST_TYPE_ARGUMENTS =
- const StaticTypeWarningCode('EXPECTED_ONE_LIST_TYPE_ARGUMENTS',
- "List literal requires exactly one type arguments or none, but {0} found");
-
- /**
- * 12.8 Maps: A fresh instance (7.6.1) <i>m</i>, of size <i>n</i>, whose class
- * implements the built-in class <i>Map<K, V></i> is allocated.
- *
- * Parameters:
- * 0: the number of provided type arguments
- */
- static const StaticTypeWarningCode EXPECTED_TWO_MAP_TYPE_ARGUMENTS =
- const StaticTypeWarningCode('EXPECTED_TWO_MAP_TYPE_ARGUMENTS',
- "Map literal requires exactly two type arguments or none, but {0} found");
-
- /**
- * 9 Functions: It is a static warning if the declared return type of a
- * function marked async* may not be assigned to Stream.
- */
- static const StaticTypeWarningCode ILLEGAL_ASYNC_GENERATOR_RETURN_TYPE =
- const StaticTypeWarningCode('ILLEGAL_ASYNC_GENERATOR_RETURN_TYPE',
- "Functions marked 'async*' must have a return type assignable to 'Stream'");
-
- /**
- * 9 Functions: It is a static warning if the declared return type of a
- * function marked async may not be assigned to Future.
- */
- static const StaticTypeWarningCode ILLEGAL_ASYNC_RETURN_TYPE =
- const StaticTypeWarningCode('ILLEGAL_ASYNC_RETURN_TYPE',
- "Functions marked 'async' must have a return type assignable to 'Future'");
-
- /**
- * 9 Functions: It is a static warning if the declared return type of a
- * function marked sync* may not be assigned to Iterable.
- */
- static const StaticTypeWarningCode ILLEGAL_SYNC_GENERATOR_RETURN_TYPE =
- const StaticTypeWarningCode('ILLEGAL_SYNC_GENERATOR_RETURN_TYPE',
- "Functions marked 'sync*' must have a return type assignable to 'Iterable'");
-
- /**
- * 12.18 Assignment: Let <i>T</i> be the static type of <i>e<sub>1</sub></i>.
- * It is a static type warning if <i>T</i> does not have an accessible
- * instance setter named <i>v=</i>.
- *
- * See [UNDEFINED_SETTER].
- */
- static const StaticTypeWarningCode INACCESSIBLE_SETTER =
- const StaticTypeWarningCode('INACCESSIBLE_SETTER', "");
-
- /**
- * 8.1.1 Inheritance and Overriding: However, if the above rules would cause
- * multiple members <i>m<sub>1</sub>, …, m<sub>k</sub></i> with the
- * same name <i>n</i> that would be inherited (because identically named
- * members existed in several superinterfaces) then at most one member is
- * inherited.
- *
- * If the static types <i>T<sub>1</sub>, …, T<sub>k</sub></i> of the
- * members <i>m<sub>1</sub>, …, m<sub>k</sub></i> are not identical,
- * then there must be a member <i>m<sub>x</sub></i> such that <i>T<sub>x</sub>
- * <: T<sub>i</sub>, 1 <= x <= k</i> for all <i>i, 1 <= i <=
- * k</i>, or a static type warning occurs. The member that is inherited is
- * <i>m<sub>x</sub></i>, if it exists; otherwise:
- * * Let <i>numberOfPositionals</i>(<i>f</i>) denote the number of positional
- * parameters of a function <i>f</i>, and let
- * <i>numberOfRequiredParams</i>(<i>f</i>) denote the number of required
- * parameters of a function <i>f</i>. Furthermore, let <i>s</i> denote the
- * set of all named parameters of the <i>m<sub>1</sub>, …,
- * m<sub>k</sub></i>. Then let
- * * <i>h = max(numberOfPositionals(m<sub>i</sub>)),</i>
- * * <i>r = min(numberOfRequiredParams(m<sub>i</sub>)), for all <i>i</i>, 1 <=
- * i <= k.</i> If <i>r <= h</i> then <i>I</i> has a method named <i>n</i>,
- * with <i>r</i> required parameters of type <b>dynamic</b>, <i>h</i>
- * positional parameters of type <b>dynamic</b>, named parameters <i>s</i>
- * of type <b>dynamic</b> and return type <b>dynamic</b>.
- * * Otherwise none of the members <i>m<sub>1</sub>, …,
- * m<sub>k</sub></i> is inherited.
- */
- static const StaticTypeWarningCode INCONSISTENT_METHOD_INHERITANCE =
- const StaticTypeWarningCode('INCONSISTENT_METHOD_INHERITANCE',
- "'{0}' is inherited by at least two interfaces inconsistently, from {1}");
-
- /**
- * 12.15.1 Ordinary Invocation: It is a static type warning if <i>T</i> does
- * not have an accessible (3.2) instance member named <i>m</i>.
- *
- * Parameters:
- * 0: the name of the static member
- *
- * See [UNQUALIFIED_REFERENCE_TO_NON_LOCAL_STATIC_MEMBER].
- */
- static const StaticTypeWarningCode INSTANCE_ACCESS_TO_STATIC_MEMBER =
- const StaticTypeWarningCode('INSTANCE_ACCESS_TO_STATIC_MEMBER',
- "Static member '{0}' cannot be accessed using instance access");
-
- /**
- * 12.18 Assignment: It is a static type warning if the static type of
- * <i>e</i> may not be assigned to the static type of <i>v</i>. The static
- * type of the expression <i>v = e</i> is the static type of <i>e</i>.
- *
- * 12.18 Assignment: It is a static type warning if the static type of
- * <i>e</i> may not be assigned to the static type of <i>C.v</i>. The static
- * type of the expression <i>C.v = e</i> is the static type of <i>e</i>.
- *
- * 12.18 Assignment: Let <i>T</i> be the static type of <i>e<sub>1</sub></i>.
- * It is a static type warning if the static type of <i>e<sub>2</sub></i> may
- * not be assigned to <i>T</i>.
- *
- * Parameters:
- * 0: the name of the right hand side type
- * 1: the name of the left hand side type
- */
- static const StaticTypeWarningCode INVALID_ASSIGNMENT =
- const StaticTypeWarningCode('INVALID_ASSIGNMENT',
- "A value of type '{0}' cannot be assigned to a variable of type '{1}'");
-
- /**
- * 12.15.1 Ordinary Invocation: An ordinary method invocation <i>i</i> has the
- * form <i>o.m(a<sub>1</sub>, …, a<sub>n</sub>, x<sub>n+1</sub>:
- * a<sub>n+1</sub>, … x<sub>n+k</sub>: a<sub>n+k</sub>)</i>.
- *
- * Let <i>T</i> be the static type of <i>o</i>. It is a static type warning if
- * <i>T</i> does not have an accessible instance member named <i>m</i>. If
- * <i>T.m</i> exists, it is a static warning if the type <i>F</i> of
- * <i>T.m</i> may not be assigned to a function type. If <i>T.m</i> does not
- * exist, or if <i>F</i> is not a function type, the static type of <i>i</i>
- * is dynamic.
- *
- * 12.15.3 Static Invocation: It is a static type warning if the type <i>F</i>
- * of <i>C.m</i> may not be assigned to a function type.
- *
- * 12.15.4 Super Invocation: A super method invocation <i>i</i> has the form
- * <i>super.m(a<sub>1</sub>, …, a<sub>n</sub>, x<sub>n+1</sub>:
- * a<sub>n+1</sub>, … x<sub>n+k</sub>: a<sub>n+k</sub>)</i>. If
- * <i>S.m</i> exists, it is a static warning if the type <i>F</i> of
- * <i>S.m</i> may not be assigned to a function type.
- *
- * Parameters:
- * 0: the name of the identifier that is not a function type
- */
- static const StaticTypeWarningCode INVOCATION_OF_NON_FUNCTION =
- const StaticTypeWarningCode(
- 'INVOCATION_OF_NON_FUNCTION', "'{0}' is not a method");
-
- /**
- * 12.14.4 Function Expression Invocation: A function expression invocation
- * <i>i</i> has the form <i>e<sub>f</sub>(a<sub>1</sub>, …,
- * a<sub>n</sub>, x<sub>n+1</sub>: a<sub>n+1</sub>, …, x<sub>n+k</sub>:
- * a<sub>n+k</sub>)</i>, where <i>e<sub>f</sub></i> is an expression.
- *
- * It is a static type warning if the static type <i>F</i> of
- * <i>e<sub>f</sub></i> may not be assigned to a function type.
- */
- static const StaticTypeWarningCode INVOCATION_OF_NON_FUNCTION_EXPRESSION =
- const StaticTypeWarningCode('INVOCATION_OF_NON_FUNCTION_EXPRESSION',
- "Cannot invoke a non-function");
-
- /**
- * 12.20 Conditional: It is a static type warning if the type of
- * <i>e<sub>1</sub></i> may not be assigned to bool.
- *
- * 13.5 If: It is a static type warning if the type of the expression <i>b</i>
- * may not be assigned to bool.
- *
- * 13.7 While: It is a static type warning if the type of <i>e</i> may not be
- * assigned to bool.
- *
- * 13.8 Do: It is a static type warning if the type of <i>e</i> cannot be
- * assigned to bool.
- */
- static const StaticTypeWarningCode NON_BOOL_CONDITION =
- const StaticTypeWarningCode(
- 'NON_BOOL_CONDITION', "Conditions must have a static type of 'bool'");
-
- /**
- * 13.15 Assert: It is a static type warning if the type of <i>e</i> may not
- * be assigned to either bool or () → bool
- */
- static const StaticTypeWarningCode NON_BOOL_EXPRESSION =
- const StaticTypeWarningCode('NON_BOOL_EXPRESSION',
- "Assertions must be on either a 'bool' or '() -> bool'");
-
- /**
- * 12.28 Unary Expressions: The expression !<i>e</i> is equivalent to the
- * expression <i>e</i>?<b>false<b> : <b>true</b>.
- *
- * 12.20 Conditional: It is a static type warning if the type of
- * <i>e<sub>1</sub></i> may not be assigned to bool.
- */
- static const StaticTypeWarningCode NON_BOOL_NEGATION_EXPRESSION =
- const StaticTypeWarningCode('NON_BOOL_NEGATION_EXPRESSION',
- "Negation argument must have a static type of 'bool'");
-
- /**
- * 12.21 Logical Boolean Expressions: It is a static type warning if the
- * static types of both of <i>e<sub>1</sub></i> and <i>e<sub>2</sub></i> may
- * not be assigned to bool.
- *
- * Parameters:
- * 0: the lexeme of the logical operator
- */
- static const StaticTypeWarningCode NON_BOOL_OPERAND =
- const StaticTypeWarningCode('NON_BOOL_OPERAND',
- "The operands of the '{0}' operator must be assignable to 'bool'");
-
- /**
- *
- */
- static const StaticTypeWarningCode NON_NULLABLE_FIELD_NOT_INITIALIZED =
- const StaticTypeWarningCode('NON_NULLABLE_FIELD_NOT_INITIALIZED',
- "Variable '{0}' of non-nullable type '{1}' must be initialized");
-
- /**
- * 15.8 Parameterized Types: It is a static type warning if <i>A<sub>i</sub>,
- * 1 <= i <= n</i> does not denote a type in the enclosing lexical scope.
- */
- static const StaticTypeWarningCode NON_TYPE_AS_TYPE_ARGUMENT =
- const StaticTypeWarningCode('NON_TYPE_AS_TYPE_ARGUMENT',
- "The name '{0}' is not a type and cannot be used as a parameterized type");
-
- /**
- * 13.11 Return: It is a static type warning if the type of <i>e</i> may not
- * be assigned to the declared return type of the immediately enclosing
- * function.
- *
- * Parameters:
- * 0: the return type as declared in the return statement
- * 1: the expected return type as defined by the method
- * 2: the name of the method
- */
- static const StaticTypeWarningCode RETURN_OF_INVALID_TYPE =
- shared_messages.RETURN_OF_INVALID_TYPE;
-
- /**
- * 12.11 Instance Creation: It is a static type warning if any of the type
- * arguments to a constructor of a generic type <i>G</i> invoked by a new
- * expression or a constant object expression are not subtypes of the bounds
- * of the corresponding formal type parameters of <i>G</i>.
- *
- * 15.8 Parameterized Types: If <i>S</i> is the static type of a member
- * <i>m</i> of <i>G</i>, then the static type of the member <i>m</i> of
- * <i>G<A<sub>1</sub>, …, A<sub>n</sub>></i> is <i>[A<sub>1</sub>,
- * …, A<sub>n</sub>/T<sub>1</sub>, …, T<sub>n</sub>]S</i> where
- * <i>T<sub>1</sub>, …, T<sub>n</sub></i> are the formal type
- * parameters of <i>G</i>. Let <i>B<sub>i</sub></i> be the bounds of
- * <i>T<sub>i</sub>, 1 <= i <= n</i>. It is a static type warning if
- * <i>A<sub>i</sub></i> is not a subtype of <i>[A<sub>1</sub>, …,
- * A<sub>n</sub>/T<sub>1</sub>, …, T<sub>n</sub>]B<sub>i</sub>, 1 <=
- * i <= n</i>.
- *
- * 7.6.2 Factories: It is a static type warning if any of the type arguments
- * to <i>k'</i> are not subtypes of the bounds of the corresponding formal
- * type parameters of type.
- *
- * Parameters:
- * 0: the name of the type used in the instance creation that should be
- * limited by the bound as specified in the class declaration
- * 1: the name of the bounding type
- *
- * See [TYPE_PARAMETER_SUPERTYPE_OF_ITS_BOUND].
- */
- static const StaticTypeWarningCode TYPE_ARGUMENT_NOT_MATCHING_BOUNDS =
- const StaticTypeWarningCode(
- 'TYPE_ARGUMENT_NOT_MATCHING_BOUNDS', "'{0}' does not extend '{1}'");
-
- /**
- * 10 Generics: It is a static type warning if a type parameter is a supertype
- * of its upper bound.
- *
- * Parameters:
- * 0: the name of the type parameter
- *
- * See [TYPE_ARGUMENT_NOT_MATCHING_BOUNDS].
- */
- static const StaticTypeWarningCode TYPE_PARAMETER_SUPERTYPE_OF_ITS_BOUND =
- const StaticTypeWarningCode('TYPE_PARAMETER_SUPERTYPE_OF_ITS_BOUND',
- "'{0}' cannot be a supertype of its upper bound");
-
- /**
- * 12.17 Getter Invocation: It is a static warning if there is no class
- * <i>C</i> in the enclosing lexical scope of <i>i</i>, or if <i>C</i> does
- * not declare, implicitly or explicitly, a getter named <i>m</i>.
- *
- * Parameters:
- * 0: the name of the enumeration constant that is not defined
- * 1: the name of the enumeration used to access the constant
- */
- static const StaticTypeWarningCode UNDEFINED_ENUM_CONSTANT =
- shared_messages.UNDEFINED_ENUM_CONSTANT;
-
- /**
- * 12.15.3 Unqualified Invocation: If there exists a lexically visible
- * declaration named <i>id</i>, let <i>f<sub>id</sub></i> be the innermost
- * such declaration. Then: [skip]. Otherwise, <i>f<sub>id</sub></i> is
- * considered equivalent to the ordinary method invocation
- * <b>this</b>.<i>id</i>(<i>a<sub>1</sub></i>, ..., <i>a<sub>n</sub></i>,
- * <i>x<sub>n+1</sub></i> : <i>a<sub>n+1</sub></i>, ...,
- * <i>x<sub>n+k</sub></i> : <i>a<sub>n+k</sub></i>).
- *
- * Parameters:
- * 0: the name of the method that is undefined
- */
- static const StaticTypeWarningCode UNDEFINED_FUNCTION =
- shared_messages.UNDEFINED_FUNCTION;
-
- /**
- * 12.17 Getter Invocation: Let <i>T</i> be the static type of <i>e</i>. It is
- * a static type warning if <i>T</i> does not have a getter named <i>m</i>.
- *
- * Parameters:
- * 0: the name of the getter
- * 1: the name of the enclosing type where the getter is being looked for
- */
- static const StaticTypeWarningCode UNDEFINED_GETTER =
- shared_messages.UNDEFINED_GETTER_STATIC_TYPE_WARNING;
-
- /**
- * 12.15.1 Ordinary Invocation: Let <i>T</i> be the static type of <i>o</i>.
- * It is a static type warning if <i>T</i> does not have an accessible
- * instance member named <i>m</i>.
- *
- * Parameters:
- * 0: the name of the method that is undefined
- * 1: the resolved type name that the method lookup is happening on
- */
- static const StaticTypeWarningCode UNDEFINED_METHOD =
- shared_messages.UNDEFINED_METHOD_STATIC_TYPE_WARNING;
-
- /**
- * 12.15.1 Ordinary Invocation: Let <i>T</i> be the static type of <i>o</i>.
- * It is a static type warning if <i>T</i> does not have an accessible
- * instance member named <i>m</i>.
- *
- * Parameters:
- * 0: the name of the method that is undefined
- * 1: the resolved type name that the method lookup is happening on
- */
- static const StaticTypeWarningCode UNDEFINED_METHOD_WITH_CONSTRUCTOR =
- shared_messages.UNDEFINED_METHOD_WITH_CONSTRUCTOR;
-
- /**
- * 12.18 Assignment: Evaluation of an assignment of the form
- * <i>e<sub>1</sub></i>[<i>e<sub>2</sub></i>] = <i>e<sub>3</sub></i> is
- * equivalent to the evaluation of the expression (a, i, e){a.[]=(i, e);
- * return e;} (<i>e<sub>1</sub></i>, <i>e<sub>2</sub></i>,
- * <i>e<sub>2</sub></i>).
- *
- * 12.29 Assignable Expressions: An assignable expression of the form
- * <i>e<sub>1</sub></i>[<i>e<sub>2</sub></i>] is evaluated as a method
- * invocation of the operator method [] on <i>e<sub>1</sub></i> with argument
- * <i>e<sub>2</sub></i>.
- *
- * 12.15.1 Ordinary Invocation: Let <i>T</i> be the static type of <i>o</i>.
- * It is a static type warning if <i>T</i> does not have an accessible
- * instance member named <i>m</i>.
- *
- * Parameters:
- * 0: the name of the operator
- * 1: the name of the enclosing type where the operator is being looked for
- */
- static const StaticTypeWarningCode UNDEFINED_OPERATOR =
- shared_messages.UNDEFINED_OPERATOR_STATIC_TYPE_WARNING;
-
- /**
- * 12.18 Assignment: Let <i>T</i> be the static type of <i>e<sub>1</sub></i>.
- * It is a static type warning if <i>T</i> does not have an accessible
- * instance setter named <i>v=</i>.
- *
- * Parameters:
- * 0: the name of the setter
- * 1: the name of the enclosing type where the setter is being looked for
- *
- * See [INACCESSIBLE_SETTER].
- */
- static const StaticTypeWarningCode UNDEFINED_SETTER =
- shared_messages.UNDEFINED_SETTER_STATIC_TYPE_WARNING;
-
- /**
- * 12.17 Getter Invocation: Let <i>T</i> be the static type of <i>e</i>. It is
- * a static type warning if <i>T</i> does not have a getter named <i>m</i>.
- *
- * Parameters:
- * 0: the name of the getter
- * 1: the name of the enclosing type where the getter is being looked for
- */
- static const StaticTypeWarningCode UNDEFINED_SUPER_GETTER =
- shared_messages.UNDEFINED_SUPER_GETTER_STATIC_TYPE_WARNING;
-
- /**
- * 12.15.4 Super Invocation: A super method invocation <i>i</i> has the form
- * <i>super.m(a<sub>1</sub>, …, a<sub>n</sub>, x<sub>n+1</sub>:
- * a<sub>n+1</sub>, … x<sub>n+k</sub>: a<sub>n+k</sub>)</i>. It is a
- * static type warning if <i>S</i> does not have an accessible instance member
- * named <i>m</i>.
- *
- * Parameters:
- * 0: the name of the method that is undefined
- * 1: the resolved type name that the method lookup is happening on
- */
- static const StaticTypeWarningCode UNDEFINED_SUPER_METHOD =
- shared_messages.UNDEFINED_SUPER_METHOD;
-
- /**
- * 12.18 Assignment: Evaluation of an assignment of the form
- * <i>e<sub>1</sub></i>[<i>e<sub>2</sub></i>] = <i>e<sub>3</sub></i> is
- * equivalent to the evaluation of the expression (a, i, e){a.[]=(i, e);
- * return e;} (<i>e<sub>1</sub></i>, <i>e<sub>2</sub></i>,
- * <i>e<sub>2</sub></i>).
- *
- * 12.29 Assignable Expressions: An assignable expression of the form
- * <i>e<sub>1</sub></i>[<i>e<sub>2</sub></i>] is evaluated as a method
- * invocation of the operator method [] on <i>e<sub>1</sub></i> with argument
- * <i>e<sub>2</sub></i>.
- *
- * 12.15.1 Ordinary Invocation: Let <i>T</i> be the static type of <i>o</i>.
- * It is a static type warning if <i>T</i> does not have an accessible
- * instance member named <i>m</i>.
- *
- * Parameters:
- * 0: the name of the operator
- * 1: the name of the enclosing type where the operator is being looked for
- */
- static const StaticTypeWarningCode UNDEFINED_SUPER_OPERATOR =
- shared_messages.UNDEFINED_SUPER_OPERATOR;
-
- /**
- * 12.18 Assignment: Let <i>T</i> be the static type of <i>e<sub>1</sub></i>.
- * It is a static type warning if <i>T</i> does not have an accessible
- * instance setter named <i>v=</i>.
- *
- * Parameters:
- * 0: the name of the setter
- * 1: the name of the enclosing type where the setter is being looked for
- *
- * See [INACCESSIBLE_SETTER].
- */
- static const StaticTypeWarningCode UNDEFINED_SUPER_SETTER =
- shared_messages.UNDEFINED_SUPER_SETTER_STATIC_TYPE_WARNING;
-
- /**
- * 12.15.1 Ordinary Invocation: It is a static type warning if <i>T</i> does
- * not have an accessible (3.2) instance member named <i>m</i>.
- *
- * This is a specialization of [INSTANCE_ACCESS_TO_STATIC_MEMBER] that is used
- * when we are able to find the name defined in a supertype. It exists to
- * provide a more informative error message.
- */
- static const StaticTypeWarningCode
- UNQUALIFIED_REFERENCE_TO_NON_LOCAL_STATIC_MEMBER =
- const StaticTypeWarningCode(
- 'UNQUALIFIED_REFERENCE_TO_NON_LOCAL_STATIC_MEMBER',
- "Static members from supertypes must be qualified by the name of the defining type");
-
- /**
- * 15.8 Parameterized Types: It is a static type warning if <i>G</i> is not a
- * generic type with exactly <i>n</i> type parameters.
- *
- * Parameters:
- * 0: the name of the type being referenced (<i>G</i>)
- * 1: the number of type parameters that were declared
- * 2: the number of type arguments provided
- *
- * See [CompileTimeErrorCode.CONST_WITH_INVALID_TYPE_PARAMETERS], and
- * [CompileTimeErrorCode.NEW_WITH_INVALID_TYPE_PARAMETERS].
- */
- static const StaticTypeWarningCode WRONG_NUMBER_OF_TYPE_ARGUMENTS =
- const StaticTypeWarningCode('WRONG_NUMBER_OF_TYPE_ARGUMENTS',
- "The type '{0}' is declared with {1} type parameters, but {2} type arguments were given");
-
- /**
- * 17.16.1 Yield: Let T be the static type of e [the expression to the right
- * of "yield"] and let f be the immediately enclosing function. It is a
- * static type warning if either:
- *
- * - the body of f is marked async* and the type Stream<T> may not be
- * assigned to the declared return type of f.
- *
- * - the body of f is marked sync* and the type Iterable<T> may not be
- * assigned to the declared return type of f.
- *
- * 17.16.2 Yield-Each: Let T be the static type of e [the expression to the
- * right of "yield*"] and let f be the immediately enclosing function. It is
- * a static type warning if T may not be assigned to the declared return type
- * of f. If f is synchronous it is a static type warning if T may not be
- * assigned to Iterable. If f is asynchronous it is a static type warning if
- * T may not be assigned to Stream.
- */
- static const StaticTypeWarningCode YIELD_OF_INVALID_TYPE =
- const StaticTypeWarningCode('YIELD_OF_INVALID_TYPE',
- "The type '{0}' implied by the 'yield' expression must be assignable to '{1}'");
-
- /**
- * 17.6.2 For-in. If the iterable expression does not implement Iterable,
- * this warning is reported.
- *
- * Parameters:
- * 0: The type of the iterable expression.
- * 1: The sequence type -- Iterable for `for` or Stream for `await for`.
- */
- static const StaticTypeWarningCode FOR_IN_OF_INVALID_TYPE =
- const StaticTypeWarningCode('FOR_IN_OF_INVALID_TYPE',
- "The type '{0}' used in the 'for' loop must implement {1}");
-
- /**
- * 17.6.2 For-in. It the iterable expression does not implement Iterable with
- * a type argument that can be assigned to the for-in variable's type, this
- * warning is reported.
- *
- * Parameters:
- * 0: The type of the iterable expression.
- * 1: The sequence type -- Iterable for `for` or Stream for `await for`.
- * 2: The loop variable type.
- */
- static const StaticTypeWarningCode FOR_IN_OF_INVALID_ELEMENT_TYPE =
- const StaticTypeWarningCode('FOR_IN_OF_INVALID_ELEMENT_TYPE',
- "The type '{0}' used in the 'for' loop must implement {1} with a type argument that can be assigned to '{2}'");
-
- /**
- * Initialize a newly created error code to have the given [name]. The message
- * associated with the error will be created from the given [message]
- * template. The correction associated with the error will be created from the
- * given [correction] template.
- */
- const StaticTypeWarningCode(String name, String message, [String correction])
- : super(name, message, correction);
-
- @override
- ErrorSeverity get errorSeverity => ErrorType.STATIC_TYPE_WARNING.severity;
-
- @override
- ErrorType get type => ErrorType.STATIC_TYPE_WARNING;
-}
-
-/**
- * The error codes used for static warnings. The convention for this class is
- * for the name of the error code to indicate the problem that caused the error
- * to be generated and for the error message to explain what is wrong and, when
- * appropriate, how the problem can be corrected.
- */
-class StaticWarningCode extends ErrorCode {
- /**
- * 14.1 Imports: If a name <i>N</i> is referenced by a library <i>L</i> and
- * <i>N</i> is introduced into the top level scope <i>L</i> by more than one
- * import then:
- * 1. A static warning occurs.
- * 2. If <i>N</i> is referenced as a function, getter or setter, a
- * <i>NoSuchMethodError</i> is raised.
- * 3. If <i>N</i> is referenced as a type, it is treated as a malformed type.
- *
- * Parameters:
- * 0: the name of the ambiguous type
- * 1: the name of the first library that the type is found
- * 2: the name of the second library that the type is found
- */
- static const StaticWarningCode AMBIGUOUS_IMPORT = const StaticWarningCode(
- 'AMBIGUOUS_IMPORT',
- "The name '{0}' is defined in the libraries {1}",
- "Consider using 'as prefix' for one of the import directives "
- "or hiding the name from all but one of the imports.");
-
- /**
- * 12.11.1 New: It is a static warning if the static type of <i>a<sub>i</sub>,
- * 1 <= i <= n+ k</i> may not be assigned to the type of the
- * corresponding formal parameter of the constructor <i>T.id</i> (respectively
- * <i>T</i>).
- *
- * 12.11.2 Const: It is a static warning if the static type of
- * <i>a<sub>i</sub>, 1 <= i <= n+ k</i> may not be assigned to the type
- * of the corresponding formal parameter of the constructor <i>T.id</i>
- * (respectively <i>T</i>).
- *
- * 12.14.2 Binding Actuals to Formals: Let <i>T<sub>i</sub></i> be the static
- * type of <i>a<sub>i</sub></i>, let <i>S<sub>i</sub></i> be the type of
- * <i>p<sub>i</sub>, 1 <= i <= n+k</i> and let <i>S<sub>q</sub></i> be
- * the type of the named parameter <i>q</i> of <i>f</i>. It is a static
- * warning if <i>T<sub>j</sub></i> may not be assigned to <i>S<sub>j</sub>, 1
- * <= j <= m</i>.
- *
- * 12.14.2 Binding Actuals to Formals: Furthermore, each <i>q<sub>i</sub>, 1
- * <= i <= l</i>, must have a corresponding named parameter in the set
- * <i>{p<sub>n+1</sub>, … p<sub>n+k</sub>}</i> or a static warning
- * occurs. It is a static warning if <i>T<sub>m+j</sub></i> may not be
- * assigned to <i>S<sub>r</sub></i>, where <i>r = q<sub>j</sub>, 1 <= j
- * <= l</i>.
- *
- * Parameters:
- * 0: the name of the actual argument type
- * 1: the name of the expected type
- */
- static const StaticWarningCode ARGUMENT_TYPE_NOT_ASSIGNABLE =
- shared_messages.ARGUMENT_TYPE_NOT_ASSIGNABLE_STATIC_WARNING;
-
- /**
- * 5 Variables: Attempting to assign to a final variable elsewhere will cause
- * a NoSuchMethodError to be thrown, because no setter is defined for it. The
- * assignment will also give rise to a static warning for the same reason.
- *
- * A constant variable is always implicitly final.
- */
- static const StaticWarningCode ASSIGNMENT_TO_CONST = const StaticWarningCode(
- 'ASSIGNMENT_TO_CONST', "Constant variables cannot be assigned a value");
-
- /**
- * 5 Variables: Attempting to assign to a final variable elsewhere will cause
- * a NoSuchMethodError to be thrown, because no setter is defined for it. The
- * assignment will also give rise to a static warning for the same reason.
- */
- static const StaticWarningCode ASSIGNMENT_TO_FINAL = const StaticWarningCode(
- 'ASSIGNMENT_TO_FINAL', "'{0}' cannot be used as a setter, it is final");
-
- /**
- * 5 Variables: Attempting to assign to a final variable elsewhere will cause
- * a NoSuchMethodError to be thrown, because no setter is defined for it. The
- * assignment will also give rise to a static warning for the same reason.
- */
- static const StaticWarningCode ASSIGNMENT_TO_FINAL_NO_SETTER =
- const StaticWarningCode('ASSIGNMENT_TO_FINAL_NO_SETTER',
- "No setter named '{0}' in class '{1}'");
-
- /**
- * 12.18 Assignment: It is as static warning if an assignment of the form
- * <i>v = e</i> occurs inside a top level or static function (be it function,
- * method, getter, or setter) or variable initializer and there is neither a
- * local variable declaration with name <i>v</i> nor setter declaration with
- * name <i>v=</i> in the lexical scope enclosing the assignment.
- */
- static const StaticWarningCode ASSIGNMENT_TO_FUNCTION =
- const StaticWarningCode(
- 'ASSIGNMENT_TO_FUNCTION', "Functions cannot be assigned a value");
-
- /**
- * 12.18 Assignment: Let <i>T</i> be the static type of <i>e<sub>1</sub></i>
- * It is a static type warning if <i>T</i> does not have an accessible
- * instance setter named <i>v=</i>.
- */
- static const StaticWarningCode ASSIGNMENT_TO_METHOD = const StaticWarningCode(
- 'ASSIGNMENT_TO_METHOD', "Methods cannot be assigned a value");
-
- /**
- * 12.18 Assignment: It is as static warning if an assignment of the form
- * <i>v = e</i> occurs inside a top level or static function (be it function,
- * method, getter, or setter) or variable initializer and there is neither a
- * local variable declaration with name <i>v</i> nor setter declaration with
- * name <i>v=</i> in the lexical scope enclosing the assignment.
- */
- static const StaticWarningCode ASSIGNMENT_TO_TYPE = const StaticWarningCode(
- 'ASSIGNMENT_TO_TYPE', "Types cannot be assigned a value");
-
- /**
- * 13.9 Switch: It is a static warning if the last statement of the statement
- * sequence <i>s<sub>k</sub></i> is not a break, continue, return or throw
- * statement.
- */
- static const StaticWarningCode CASE_BLOCK_NOT_TERMINATED =
- const StaticWarningCode('CASE_BLOCK_NOT_TERMINATED',
- "The last statement of the 'case' should be 'break', 'continue', 'return' or 'throw'");
-
- /**
- * 12.32 Type Cast: It is a static warning if <i>T</i> does not denote a type
- * available in the current lexical scope.
- */
- static const StaticWarningCode CAST_TO_NON_TYPE = const StaticWarningCode(
- 'CAST_TO_NON_TYPE',
- "The name '{0}' is not a type and cannot be used in an 'as' expression");
-
- /**
- * 7.4 Abstract Instance Members: It is a static warning if an abstract member
- * is declared or inherited in a concrete class.
- */
- static const StaticWarningCode CONCRETE_CLASS_WITH_ABSTRACT_MEMBER =
- const StaticWarningCode('CONCRETE_CLASS_WITH_ABSTRACT_MEMBER',
- "'{0}' must have a method body because '{1}' is not abstract");
-
- /**
- * 14.1 Imports: If a name <i>N</i> is referenced by a library <i>L</i> and
- * <i>N</i> would be introduced into the top level scope of <i>L</i> by an
- * import from a library whose URI begins with <i>dart:</i> and an import from
- * a library whose URI does not begin with <i>dart:</i>:
- * * The import from <i>dart:</i> is implicitly extended by a hide N clause.
- * * A static warning is issued.
- *
- * Parameters:
- * 0: the ambiguous name
- * 1: the name of the dart: library in which the element is found
- * 2: the name of the non-dart: library in which the element is found
- */
- static const StaticWarningCode CONFLICTING_DART_IMPORT =
- const StaticWarningCode('CONFLICTING_DART_IMPORT',
- "Element '{0}' from SDK library '{1}' is implicitly hidden by '{2}'");
-
- /**
- * 7.2 Getters: It is a static warning if a class <i>C</i> declares an
- * instance getter named <i>v</i> and an accessible static member named
- * <i>v</i> or <i>v=</i> is declared in a superclass of <i>C</i>.
- *
- * Parameters:
- * 0: the name of the super class declaring a static member
- */
- static const StaticWarningCode
- CONFLICTING_INSTANCE_GETTER_AND_SUPERCLASS_MEMBER =
- const StaticWarningCode(
- 'CONFLICTING_INSTANCE_GETTER_AND_SUPERCLASS_MEMBER',
- "Superclass '{0}' declares static member with the same name");
-
- /**
- * 7.1 Instance Methods: It is a static warning if a class <i>C</i> declares
- * an instance method named <i>n</i> and has a setter named <i>n=</i>.
- */
- static const StaticWarningCode CONFLICTING_INSTANCE_METHOD_SETTER =
- const StaticWarningCode('CONFLICTING_INSTANCE_METHOD_SETTER',
- "Class '{0}' declares instance method '{1}', but also has a setter with the same name from '{2}'");
-
- /**
- * 7.1 Instance Methods: It is a static warning if a class <i>C</i> declares
- * an instance method named <i>n</i> and has a setter named <i>n=</i>.
- */
- static const StaticWarningCode CONFLICTING_INSTANCE_METHOD_SETTER2 =
- const StaticWarningCode('CONFLICTING_INSTANCE_METHOD_SETTER2',
- "Class '{0}' declares the setter '{1}', but also has an instance method in the same class");
-
- /**
- * 7.3 Setters: It is a static warning if a class <i>C</i> declares an
- * instance setter named <i>v=</i> and an accessible static member named
- * <i>v=</i> or <i>v</i> is declared in a superclass of <i>C</i>.
- *
- * Parameters:
- * 0: the name of the super class declaring a static member
- */
- static const StaticWarningCode
- CONFLICTING_INSTANCE_SETTER_AND_SUPERCLASS_MEMBER =
- const StaticWarningCode(
- 'CONFLICTING_INSTANCE_SETTER_AND_SUPERCLASS_MEMBER',
- "Superclass '{0}' declares static member with the same name");
-
- /**
- * 7.2 Getters: It is a static warning if a class declares a static getter
- * named <i>v</i> and also has a non-static setter named <i>v=</i>.
- */
- static const StaticWarningCode CONFLICTING_STATIC_GETTER_AND_INSTANCE_SETTER =
- const StaticWarningCode('CONFLICTING_STATIC_GETTER_AND_INSTANCE_SETTER',
- "Class '{0}' declares non-static setter with the same name");
-
- /**
- * 7.3 Setters: It is a static warning if a class declares a static setter
- * named <i>v=</i> and also has a non-static member named <i>v</i>.
- */
- static const StaticWarningCode CONFLICTING_STATIC_SETTER_AND_INSTANCE_MEMBER =
- const StaticWarningCode('CONFLICTING_STATIC_SETTER_AND_INSTANCE_MEMBER',
- "Class '{0}' declares non-static member with the same name");
-
- /**
- * 12.11.2 Const: Given an instance creation expression of the form <i>const
- * q(a<sub>1</sub>, … a<sub>n</sub>)</i> it is a static warning if
- * <i>q</i> is the constructor of an abstract class but <i>q</i> is not a
- * factory constructor.
- */
- static const StaticWarningCode CONST_WITH_ABSTRACT_CLASS =
- const StaticWarningCode('CONST_WITH_ABSTRACT_CLASS',
- "Abstract classes cannot be created with a 'const' expression");
-
- /**
- * 12.7 Maps: It is a static warning if the values of any two keys in a map
- * literal are equal.
- */
- static const StaticWarningCode EQUAL_KEYS_IN_MAP = const StaticWarningCode(
- 'EQUAL_KEYS_IN_MAP', "Keys in a map cannot be equal");
-
- /**
- * 14.2 Exports: It is a static warning to export two different libraries with
- * the same name.
- *
- * Parameters:
- * 0: the uri pointing to a first library
- * 1: the uri pointing to a second library
- * 2:e the shared name of the exported libraries
- */
- static const StaticWarningCode EXPORT_DUPLICATED_LIBRARY_NAMED =
- const StaticWarningCode('EXPORT_DUPLICATED_LIBRARY_NAMED',
- "The exported libraries '{0}' and '{1}' cannot have the same name '{2}'");
-
- /**
- * 12.14.2 Binding Actuals to Formals: It is a static warning if <i>m <
- * h</i> or if <i>m > n</i>.
- *
- * Parameters:
- * 0: the maximum number of positional arguments
- * 1: the actual number of positional arguments given
- *
- * See [NOT_ENOUGH_REQUIRED_ARGUMENTS].
- */
- static const StaticWarningCode EXTRA_POSITIONAL_ARGUMENTS =
- const StaticWarningCode('EXTRA_POSITIONAL_ARGUMENTS',
- "{0} positional arguments expected, but {1} found");
-
- /**
- * 5. Variables: It is a static warning if a final instance variable that has
- * been initialized at its point of declaration is also initialized in a
- * constructor.
- */
- static const StaticWarningCode
- FIELD_INITIALIZED_IN_INITIALIZER_AND_DECLARATION =
- const StaticWarningCode(
- 'FIELD_INITIALIZED_IN_INITIALIZER_AND_DECLARATION',
- "Values cannot be set in the constructor if they are final, and have already been set");
-
- /**
- * 5. Variables: It is a static warning if a final instance variable that has
- * been initialized at its point of declaration is also initialized in a
- * constructor.
- *
- * Parameters:
- * 0: the name of the field in question
- */
- static const StaticWarningCode
- FINAL_INITIALIZED_IN_DECLARATION_AND_CONSTRUCTOR =
- const StaticWarningCode(
- 'FINAL_INITIALIZED_IN_DECLARATION_AND_CONSTRUCTOR',
- "'{0}' is final and was given a value when it was declared, so it cannot be set to a new value");
-
- /**
- * 7.6.1 Generative Constructors: Execution of an initializer of the form
- * <b>this</b>.<i>v</i> = <i>e</i> proceeds as follows: First, the expression
- * <i>e</i> is evaluated to an object <i>o</i>. Then, the instance variable
- * <i>v</i> of the object denoted by this is bound to <i>o</i>.
- *
- * 12.14.2 Binding Actuals to Formals: Let <i>T<sub>i</sub></i> be the static
- * type of <i>a<sub>i</sub></i>, let <i>S<sub>i</sub></i> be the type of
- * <i>p<sub>i</sub>, 1 <= i <= n+k</i> and let <i>S<sub>q</sub></i> be
- * the type of the named parameter <i>q</i> of <i>f</i>. It is a static
- * warning if <i>T<sub>j</sub></i> may not be assigned to <i>S<sub>j</sub>, 1
- * <= j <= m</i>.
- *
- * Parameters:
- * 0: the name of the type of the initializer expression
- * 1: the name of the type of the field
- */
- static const StaticWarningCode FIELD_INITIALIZER_NOT_ASSIGNABLE =
- const StaticWarningCode('FIELD_INITIALIZER_NOT_ASSIGNABLE',
- "The initializer type '{0}' cannot be assigned to the field type '{1}'");
-
- /**
- * 7.6.1 Generative Constructors: An initializing formal has the form
- * <i>this.id</i>. It is a static warning if the static type of <i>id</i> is
- * not assignable to <i>T<sub>id</sub></i>.
- *
- * Parameters:
- * 0: the name of the type of the field formal parameter
- * 1: the name of the type of the field
- */
- static const StaticWarningCode FIELD_INITIALIZING_FORMAL_NOT_ASSIGNABLE =
- const StaticWarningCode('FIELD_INITIALIZING_FORMAL_NOT_ASSIGNABLE',
- "The parameter type '{0}' is incompatable with the field type '{1}'");
-
- /**
- * 5 Variables: It is a static warning if a library, static or local variable
- * <i>v</i> is final and <i>v</i> is not initialized at its point of
- * declaration.
- *
- * Parameters:
- * 0: the name of the uninitialized final variable
- */
- static const StaticWarningCode FINAL_NOT_INITIALIZED =
- const StaticWarningCode('FINAL_NOT_INITIALIZED',
- "The final variable '{0}' must be initialized", null, false);
-
- /**
- * 7.6.1 Generative Constructors: Each final instance variable <i>f</i>
- * declared in the immediately enclosing class must have an initializer in
- * <i>k</i>'s initializer list unless it has already been initialized by one
- * of the following means:
- * * Initialization at the declaration of <i>f</i>.
- * * Initialization by means of an initializing formal of <i>k</i>.
- * or a static warning occurs.
- *
- * Parameters:
- * 0: the name of the uninitialized final variable
- */
- static const StaticWarningCode FINAL_NOT_INITIALIZED_CONSTRUCTOR_1 =
- const StaticWarningCode('FINAL_NOT_INITIALIZED_CONSTRUCTOR_1',
- "The final variable '{0}' must be initialized", null, false);
-
- /**
- * 7.6.1 Generative Constructors: Each final instance variable <i>f</i>
- * declared in the immediately enclosing class must have an initializer in
- * <i>k</i>'s initializer list unless it has already been initialized by one
- * of the following means:
- * * Initialization at the declaration of <i>f</i>.
- * * Initialization by means of an initializing formal of <i>k</i>.
- * or a static warning occurs.
- *
- * Parameters:
- * 0: the name of the uninitialized final variable
- * 1: the name of the uninitialized final variable
- */
- static const StaticWarningCode FINAL_NOT_INITIALIZED_CONSTRUCTOR_2 =
- const StaticWarningCode(
- 'FINAL_NOT_INITIALIZED_CONSTRUCTOR_2',
- "The final variables '{0}' and '{1}' must be initialized",
- null,
- false);
-
- /**
- * 7.6.1 Generative Constructors: Each final instance variable <i>f</i>
- * declared in the immediately enclosing class must have an initializer in
- * <i>k</i>'s initializer list unless it has already been initialized by one
- * of the following means:
- * * Initialization at the declaration of <i>f</i>.
- * * Initialization by means of an initializing formal of <i>k</i>.
- * or a static warning occurs.
- *
- * Parameters:
- * 0: the name of the uninitialized final variable
- * 1: the name of the uninitialized final variable
- * 2: the number of additional not initialized variables that aren't listed
- */
- static const StaticWarningCode FINAL_NOT_INITIALIZED_CONSTRUCTOR_3_PLUS =
- const StaticWarningCode(
- 'FINAL_NOT_INITIALIZED_CONSTRUCTOR_3',
- "The final variables '{0}', '{1}' and '{2}' more must be initialized",
- null,
- false);
-
- /**
- * 15.5 Function Types: It is a static warning if a concrete class implements
- * Function and does not have a concrete method named call().
- */
- static const StaticWarningCode FUNCTION_WITHOUT_CALL = const StaticWarningCode(
- 'FUNCTION_WITHOUT_CALL',
- "Concrete classes that implement Function must implement the method call()");
-
- /**
- * 14.1 Imports: It is a static warning to import two different libraries with
- * the same name.
- *
- * Parameters:
- * 0: the uri pointing to a first library
- * 1: the uri pointing to a second library
- * 2: the shared name of the imported libraries
- */
- static const StaticWarningCode IMPORT_DUPLICATED_LIBRARY_NAMED =
- const StaticWarningCode('IMPORT_DUPLICATED_LIBRARY_NAMED',
- "The imported libraries '{0}' and '{1}' cannot have the same name '{2}'");
-
- /**
- * 14.1 Imports: It is a static warning if the specified URI of a deferred
- * import does not refer to a library declaration.
- *
- * Parameters:
- * 0: the uri pointing to a non-library declaration
- *
- * See [CompileTimeErrorCode.IMPORT_OF_NON_LIBRARY].
- */
- static const StaticWarningCode IMPORT_OF_NON_LIBRARY =
- const StaticWarningCode('IMPORT_OF_NON_LIBRARY',
- "The imported library '{0}' must not have a part-of directive");
-
- /**
- * 8.1.1 Inheritance and Overriding: However, if the above rules would cause
- * multiple members <i>m<sub>1</sub>, …, m<sub>k</sub></i> with the
- * same name <i>n</i> that would be inherited (because identically named
- * members existed in several superinterfaces) then at most one member is
- * inherited.
- *
- * If some but not all of the <i>m<sub>i</sub>, 1 <= i <= k</i> are
- * getters none of the <i>m<sub>i</sub></i> are inherited, and a static
- * warning is issued.
- */
- static const StaticWarningCode
- INCONSISTENT_METHOD_INHERITANCE_GETTER_AND_METHOD =
- const StaticWarningCode(
- 'INCONSISTENT_METHOD_INHERITANCE_GETTER_AND_METHOD',
- "'{0}' is inherited as a getter and also a method");
-
- /**
- * 7.1 Instance Methods: It is a static warning if a class <i>C</i> declares
- * an instance method named <i>n</i> and an accessible static member named
- * <i>n</i> is declared in a superclass of <i>C</i>.
- *
- * Parameters:
- * 0: the name of the member with the name conflict
- * 1: the name of the enclosing class that has the static member
- */
- static const StaticWarningCode
- INSTANCE_METHOD_NAME_COLLIDES_WITH_SUPERCLASS_STATIC =
- const StaticWarningCode(
- 'INSTANCE_METHOD_NAME_COLLIDES_WITH_SUPERCLASS_STATIC',
- "'{0}' collides with a static member in the superclass '{1}'");
-
- /**
- * 7.2 Getters: It is a static warning if a getter <i>m1</i> overrides a
- * getter <i>m2</i> and the type of <i>m1</i> is not a subtype of the type of
- * <i>m2</i>.
- *
- * Parameters:
- * 0: the name of the actual return type
- * 1: the name of the expected return type, not assignable to the actual
- * return type
- * 2: the name of the class where the overridden getter is declared
- *
- * See [INVALID_METHOD_OVERRIDE_RETURN_TYPE].
- */
- static const StaticWarningCode INVALID_GETTER_OVERRIDE_RETURN_TYPE =
- const StaticWarningCode('INVALID_GETTER_OVERRIDE_RETURN_TYPE',
- "The return type '{0}' is not assignable to '{1}' as required by the getter it is overriding from '{2}'");
-
- /**
- * 7.1 Instance Methods: It is a static warning if an instance method
- * <i>m1</i> overrides an instance method <i>m2</i> and the type of <i>m1</i>
- * is not a subtype of the type of <i>m2</i>.
- *
- * Parameters:
- * 0: the name of the actual parameter type
- * 1: the name of the expected parameter type, not assignable to the actual
- * parameter type
- * 2: the name of the class where the overridden method is declared
- */
- static const StaticWarningCode INVALID_METHOD_OVERRIDE_NAMED_PARAM_TYPE =
- const StaticWarningCode('INVALID_METHOD_OVERRIDE_NAMED_PARAM_TYPE',
- "The parameter type '{0}' is not assignable to '{1}' as required by the method it is overriding from '{2}'");
-
- /**
- * Generic Method DEP: number of type parameters must match.
- * <https://github.com/leafpetersen/dep-generic-methods/blob/master/proposal.md#function-subtyping>
- *
- * Parameters:
- * 0: the number of type parameters in the method
- * 1: the number of type parameters in the overridden method
- * 2: the name of the class where the overridden method is declared
- */
- static const StaticWarningCode INVALID_METHOD_OVERRIDE_TYPE_PARAMETERS =
- const StaticWarningCode('INVALID_METHOD_OVERRIDE_TYPE_PARAMETERS',
- "The method has {0} type parameters, but it is overriding a method with {1} type parameters from '{2}'");
-
- /**
- * Generic Method DEP: bounds of type parameters must be compatible.
- * <https://github.com/leafpetersen/dep-generic-methods/blob/master/proposal.md#function-subtyping>
- *
- * Parameters:
- * 0: the type parameter name
- * 1: the type parameter bound
- * 2: the overridden type parameter name
- * 3: the overridden type parameter bound
- * 4: the name of the class where the overridden method is declared
- */
- static const StaticWarningCode INVALID_METHOD_OVERRIDE_TYPE_PARAMETER_BOUND =
- const StaticWarningCode('INVALID_METHOD_OVERRIDE_TYPE_PARAMETER_BOUND',
- "The type parameter '{0}' extends '{1}', but that is stricter than '{2}' extends '{3}' in the overridden method from '{4}'");
-
- /**
- * 7.1 Instance Methods: It is a static warning if an instance method
- * <i>m1</i> overrides an instance method <i>m2</i> and the type of <i>m1</i>
- * is not a subtype of the type of <i>m2</i>.
- *
- * Parameters:
- * 0: the name of the actual parameter type
- * 1: the name of the expected parameter type, not assignable to the actual
- * parameter type
- * 2: the name of the class where the overridden method is declared
- * See [INVALID_SETTER_OVERRIDE_NORMAL_PARAM_TYPE].
- */
- static const StaticWarningCode INVALID_METHOD_OVERRIDE_NORMAL_PARAM_TYPE =
- const StaticWarningCode('INVALID_METHOD_OVERRIDE_NORMAL_PARAM_TYPE',
- "The parameter type '{0}' is not assignable to '{1}' as required by the method it is overriding from '{2}'");
-
- /**
- * 7.1 Instance Methods: It is a static warning if an instance method
- * <i>m1</i> overrides an instance method <i>m2</i> and the type of <i>m1</i>
- * is not a subtype of the type of <i>m2</i>.
- *
- * Parameters:
- * 0: the name of the actual parameter type
- * 1: the name of the expected parameter type, not assignable to the actual
- * parameter type
- * 2: the name of the class where the overridden method is declared
- */
- static const StaticWarningCode INVALID_METHOD_OVERRIDE_OPTIONAL_PARAM_TYPE =
- const StaticWarningCode('INVALID_METHOD_OVERRIDE_OPTIONAL_PARAM_TYPE',
- "The parameter type '{0}' is not assignable to '{1}' as required by the method it is overriding from '{2}'");
-
- /**
- * 7.1 Instance Methods: It is a static warning if an instance method
- * <i>m1</i> overrides an instance method <i>m2</i> and the type of <i>m1</i>
- * is not a subtype of the type of <i>m2</i>.
- *
- * Parameters:
- * 0: the name of the actual return type
- * 1: the name of the expected return type, not assignable to the actual
- * return type
- * 2: the name of the class where the overridden method is declared
- *
- * See [INVALID_GETTER_OVERRIDE_RETURN_TYPE].
- */
- static const StaticWarningCode INVALID_METHOD_OVERRIDE_RETURN_TYPE =
- const StaticWarningCode('INVALID_METHOD_OVERRIDE_RETURN_TYPE',
- "The return type '{0}' is not assignable to '{1}' as required by the method it is overriding from '{2}'");
-
- /**
- * 7.1 Instance Methods: It is a static warning if an instance method
- * <i>m1</i> overrides an instance member <i>m2</i>, the signature of
- * <i>m2</i> explicitly specifies a default value for a formal parameter
- * <i>p</i> and the signature of <i>m1</i> specifies a different default value
- * for <i>p</i>.
- */
- static const StaticWarningCode
- INVALID_OVERRIDE_DIFFERENT_DEFAULT_VALUES_NAMED = const StaticWarningCode(
- 'INVALID_OVERRIDE_DIFFERENT_DEFAULT_VALUES_NAMED',
- "Parameters cannot override default values, this method overrides '{0}.{1}' where '{2}' has a different value");
-
- /**
- * 7.1 Instance Methods: It is a static warning if an instance method
- * <i>m1</i> overrides an instance member <i>m2</i>, the signature of
- * <i>m2</i> explicitly specifies a default value for a formal parameter
- * <i>p</i> and the signature of <i>m1</i> specifies a different default value
- * for <i>p</i>.
- */
- static const StaticWarningCode
- INVALID_OVERRIDE_DIFFERENT_DEFAULT_VALUES_POSITIONAL =
- const StaticWarningCode(
- 'INVALID_OVERRIDE_DIFFERENT_DEFAULT_VALUES_POSITIONAL',
- "Parameters cannot override default values, this method overrides '{0}.{1}' where this positional parameter has a different value");
-
- /**
- * 7.1 Instance Methods: It is a static warning if an instance method
- * <i>m1</i> overrides an instance member <i>m2</i> and <i>m1</i> does not
- * declare all the named parameters declared by <i>m2</i>.
- *
- * Parameters:
- * 0: the number of named parameters in the overridden member
- * 1: the signature of the overridden member
- * 2: the name of the class from the overridden method
- */
- static const StaticWarningCode INVALID_OVERRIDE_NAMED = const StaticWarningCode(
- 'INVALID_OVERRIDE_NAMED',
- "Missing the named parameter '{0}' to match the overridden method from '{1}' from '{2}'");
-
- /**
- * 7.1 Instance Methods: It is a static warning if an instance method
- * <i>m1</i> overrides an instance member <i>m2</i> and <i>m1</i> has fewer
- * positional parameters than <i>m2</i>.
- *
- * Parameters:
- * 0: the number of positional parameters in the overridden member
- * 1: the signature of the overridden member
- * 2: the name of the class from the overridden method
- */
- static const StaticWarningCode INVALID_OVERRIDE_POSITIONAL =
- const StaticWarningCode('INVALID_OVERRIDE_POSITIONAL',
- "Must have at least {0} parameters to match the overridden method '{1}' from '{2}'");
-
- /**
- * 7.1 Instance Methods: It is a static warning if an instance method
- * <i>m1</i> overrides an instance member <i>m2</i> and <i>m1</i> has a
- * greater number of required parameters than <i>m2</i>.
- *
- * Parameters:
- * 0: the number of required parameters in the overridden member
- * 1: the signature of the overridden member
- * 2: the name of the class from the overridden method
- */
- static const StaticWarningCode INVALID_OVERRIDE_REQUIRED =
- const StaticWarningCode('INVALID_OVERRIDE_REQUIRED',
- "Must have {0} required parameters or less to match the overridden method '{1}' from '{2}'");
-
- /**
- * 7.3 Setters: It is a static warning if a setter <i>m1</i> overrides a
- * setter <i>m2</i> and the type of <i>m1</i> is not a subtype of the type of
- * <i>m2</i>.
- *
- * Parameters:
- * 0: the name of the actual parameter type
- * 1: the name of the expected parameter type, not assignable to the actual
- * parameter type
- * 2: the name of the class where the overridden setter is declared
- *
- * See [INVALID_METHOD_OVERRIDE_NORMAL_PARAM_TYPE].
- */
- static const StaticWarningCode INVALID_SETTER_OVERRIDE_NORMAL_PARAM_TYPE =
- const StaticWarningCode('INVALID_SETTER_OVERRIDE_NORMAL_PARAM_TYPE',
- "The parameter type '{0}' is not assignable to '{1}' as required by the setter it is overriding from '{2}'");
-
- /**
- * 12.6 Lists: A run-time list literal <<i>E</i>> [<i>e<sub>1</sub></i>
- * … <i>e<sub>n</sub></i>] is evaluated as follows:
- * * The operator []= is invoked on <i>a</i> with first argument <i>i</i> and
- * second argument <i>o<sub>i+1</sub></i><i>, 1 <= i <= n</i>
- *
- * 12.14.2 Binding Actuals to Formals: Let <i>T<sub>i</sub></i> be the static
- * type of <i>a<sub>i</sub></i>, let <i>S<sub>i</sub></i> be the type of
- * <i>p<sub>i</sub>, 1 <= i <= n+k</i> and let <i>S<sub>q</sub></i> be
- * the type of the named parameter <i>q</i> of <i>f</i>. It is a static
- * warning if <i>T<sub>j</sub></i> may not be assigned to <i>S<sub>j</sub>, 1
- * <= j <= m</i>.
- */
- static const StaticWarningCode LIST_ELEMENT_TYPE_NOT_ASSIGNABLE =
- const StaticWarningCode('LIST_ELEMENT_TYPE_NOT_ASSIGNABLE',
- "The element type '{0}' cannot be assigned to the list type '{1}'");
-
- /**
- * 12.7 Map: A run-time map literal <<i>K</i>, <i>V</i>>
- * [<i>k<sub>1</sub></i> : <i>e<sub>1</sub></i> … <i>k<sub>n</sub></i>
- * : <i>e<sub>n</sub></i>] is evaluated as follows:
- * * The operator []= is invoked on <i>m</i> with first argument
- * <i>k<sub>i</sub></i> and second argument <i>e<sub>i</sub></i><i>, 1 <=
- * i <= n</i>
- *
- * 12.14.2 Binding Actuals to Formals: Let <i>T<sub>i</sub></i> be the static
- * type of <i>a<sub>i</sub></i>, let <i>S<sub>i</sub></i> be the type of
- * <i>p<sub>i</sub>, 1 <= i <= n+k</i> and let <i>S<sub>q</sub></i> be
- * the type of the named parameter <i>q</i> of <i>f</i>. It is a static
- * warning if <i>T<sub>j</sub></i> may not be assigned to <i>S<sub>j</sub>, 1
- * <= j <= m</i>.
- */
- static const StaticWarningCode MAP_KEY_TYPE_NOT_ASSIGNABLE =
- const StaticWarningCode('MAP_KEY_TYPE_NOT_ASSIGNABLE',
- "The element type '{0}' cannot be assigned to the map key type '{1}'");
-
- /**
- * 12.7 Map: A run-time map literal <<i>K</i>, <i>V</i>>
- * [<i>k<sub>1</sub></i> : <i>e<sub>1</sub></i> … <i>k<sub>n</sub></i>
- * : <i>e<sub>n</sub></i>] is evaluated as follows:
- * * The operator []= is invoked on <i>m</i> with first argument
- * <i>k<sub>i</sub></i> and second argument <i>e<sub>i</sub></i><i>, 1 <=
- * i <= n</i>
- *
- * 12.14.2 Binding Actuals to Formals: Let <i>T<sub>i</sub></i> be the static
- * type of <i>a<sub>i</sub></i>, let <i>S<sub>i</sub></i> be the type of
- * <i>p<sub>i</sub>, 1 <= i <= n+k</i> and let <i>S<sub>q</sub></i> be
- * the type of the named parameter <i>q</i> of <i>f</i>. It is a static
- * warning if <i>T<sub>j</sub></i> may not be assigned to <i>S<sub>j</sub>, 1
- * <= j <= m</i>.
- */
- static const StaticWarningCode MAP_VALUE_TYPE_NOT_ASSIGNABLE =
- const StaticWarningCode('MAP_VALUE_TYPE_NOT_ASSIGNABLE',
- "The element type '{0}' cannot be assigned to the map value type '{1}'");
-
- /**
- * 7.3 Setters: It is a static warning if a class has a setter named <i>v=</i>
- * with argument type <i>T</i> and a getter named <i>v</i> with return type
- * <i>S</i>, and <i>T</i> may not be assigned to <i>S</i>.
- */
- static const StaticWarningCode MISMATCHED_GETTER_AND_SETTER_TYPES =
- const StaticWarningCode(
- 'MISMATCHED_GETTER_AND_SETTER_TYPES',
- "The parameter type for setter '{0}' is '{1}' which is not assignable to its getter (of type '{2}')",
- null,
- false);
-
- /**
- * 7.3 Setters: It is a static warning if a class has a setter named <i>v=</i>
- * with argument type <i>T</i> and a getter named <i>v</i> with return type
- * <i>S</i>, and <i>T</i> may not be assigned to <i>S</i>.
- */
- static const StaticWarningCode
- MISMATCHED_GETTER_AND_SETTER_TYPES_FROM_SUPERTYPE =
- const StaticWarningCode(
- 'MISMATCHED_GETTER_AND_SETTER_TYPES_FROM_SUPERTYPE',
- "The parameter type for setter '{0}' is '{1}' which is not assignable to its getter (of type '{2}'), from superclass '{3}'",
- null,
- false);
-
- /**
- * 17.9 Switch: It is a static warning if all of the following conditions
- * hold:
- * * The switch statement does not have a 'default' clause.
- * * The static type of <i>e</i> is an enumerated typed with elements
- * <i>id<sub>1</sub></i>, …, <i>id<sub>n</sub></i>.
- * * The sets {<i>e<sub>1</sub></i>, …, <i>e<sub>k</sub></i>} and
- * {<i>id<sub>1</sub></i>, …, <i>id<sub>n</sub></i>} are not the
- * same.
- *
- * Parameters:
- * 0: the name of the constant that is missing
- */
- static const StaticWarningCode MISSING_ENUM_CONSTANT_IN_SWITCH =
- const StaticWarningCode(
- 'MISSING_ENUM_CONSTANT_IN_SWITCH',
- "Missing case clause for '{0}'",
- "Add a case clause for the missing constant or add a default clause.",
- false);
-
- /**
- * 13.12 Return: It is a static warning if a function contains both one or
- * more return statements of the form <i>return;</i> and one or more return
- * statements of the form <i>return e;</i>.
- */
- static const StaticWarningCode MIXED_RETURN_TYPES = const StaticWarningCode(
- 'MIXED_RETURN_TYPES',
- "Methods and functions cannot use return both with and without values",
- null,
- false);
-
- /**
- * 12.11.1 New: It is a static warning if <i>q</i> is a constructor of an
- * abstract class and <i>q</i> is not a factory constructor.
- */
- static const StaticWarningCode NEW_WITH_ABSTRACT_CLASS =
- const StaticWarningCode('NEW_WITH_ABSTRACT_CLASS',
- "Abstract classes cannot be created with a 'new' expression");
-
- /**
- * 15.8 Parameterized Types: Any use of a malbounded type gives rise to a
- * static warning.
- *
- * Parameters:
- * 0: the name of the type being referenced (<i>S</i>)
- * 1: the number of type parameters that were declared
- * 2: the number of type arguments provided
- *
- * See [CompileTimeErrorCode.CONST_WITH_INVALID_TYPE_PARAMETERS], and
- * [StaticTypeWarningCode.WRONG_NUMBER_OF_TYPE_ARGUMENTS].
- */
- static const StaticWarningCode NEW_WITH_INVALID_TYPE_PARAMETERS =
- const StaticWarningCode('NEW_WITH_INVALID_TYPE_PARAMETERS',
- "The type '{0}' is declared with {1} type parameters, but {2} type arguments were given");
-
- /**
- * 12.11.1 New: It is a static warning if <i>T</i> is not a class accessible
- * in the current scope, optionally followed by type arguments.
- *
- * Parameters:
- * 0: the name of the non-type element
- */
- static const StaticWarningCode NEW_WITH_NON_TYPE = const StaticWarningCode(
- 'NEW_WITH_NON_TYPE', "The name '{0}' is not a class");
-
- /**
- * 12.11.1 New: If <i>T</i> is a class or parameterized type accessible in the
- * current scope then:
- * 1. If <i>e</i> is of the form <i>new T.id(a<sub>1</sub>, …,
- * a<sub>n</sub>, x<sub>n+1</sub>: a<sub>n+1</sub>, …,
- * x<sub>n+k</sub>: a<sub>n+k</sub>)</i> it is a static warning if
- * <i>T.id</i> is not the name of a constructor declared by the type
- * <i>T</i>.
- * If <i>e</i> of the form <i>new T(a<sub>1</sub>, …, a<sub>n</sub>,
- * x<sub>n+1</sub>: a<sub>n+1</sub>, …, x<sub>n+k</sub>:
- * a<sub>n+kM/sub>)</i> it is a static warning if the type <i>T</i> does not
- * declare a constructor with the same name as the declaration of <i>T</i>.
- */
- static const StaticWarningCode NEW_WITH_UNDEFINED_CONSTRUCTOR =
- const StaticWarningCode('NEW_WITH_UNDEFINED_CONSTRUCTOR',
- "The class '{0}' does not have a constructor '{1}'");
-
- /**
- * 12.11.1 New: If <i>T</i> is a class or parameterized type accessible in the
- * current scope then:
- * 1. If <i>e</i> is of the form <i>new T.id(a<sub>1</sub>, …,
- * a<sub>n</sub>, x<sub>n+1</sub>: a<sub>n+1</sub>, …, x<sub>n+k</sub>:
- * a<sub>n+k</sub>)</i> it is a static warning if <i>T.id</i> is not the name
- * of a constructor declared by the type <i>T</i>. If <i>e</i> of the form
- * <i>new T(a<sub>1</sub>, …, a<sub>n</sub>, x<sub>n+1</sub>:
- * a<sub>n+1</sub>, …, x<sub>n+k</sub>: a<sub>n+kM/sub>)</i> it is a
- * static warning if the type <i>T</i> does not declare a constructor with the
- * same name as the declaration of <i>T</i>.
- */
- static const StaticWarningCode NEW_WITH_UNDEFINED_CONSTRUCTOR_DEFAULT =
- const StaticWarningCode('NEW_WITH_UNDEFINED_CONSTRUCTOR_DEFAULT',
- "The class '{0}' does not have a default constructor");
-
- /**
- * 7.9.1 Inheritance and Overriding: It is a static warning if a non-abstract
- * class inherits an abstract method.
- *
- * 7.10 Superinterfaces: Let <i>C</i> be a concrete class that does not
- * declare its own <i>noSuchMethod()</i> method. It is a static warning if the
- * implicit interface of <i>C</i> includes an instance member <i>m</i> of type
- * <i>F</i> and <i>C</i> does not declare or inherit a corresponding instance
- * member <i>m</i> of type <i>F'</i> such that <i>F' <: F</i>.
- *
- * 7.4 Abstract Instance Members: It is a static warning if an abstract member
- * is declared or inherited in a concrete class unless that member overrides a
- * concrete one.
- *
- * Parameters:
- * 0: the name of the first member
- * 1: the name of the second member
- * 2: the name of the third member
- * 3: the name of the fourth member
- * 4: the number of additional missing members that aren't listed
- */
- static const StaticWarningCode
- NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER_FIVE_PLUS =
- const StaticWarningCode(
- 'NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER_FIVE_PLUS',
- "Missing concrete implementation of {0}, {1}, {2}, {3} and {4} more");
-
- /**
- * 7.9.1 Inheritance and Overriding: It is a static warning if a non-abstract
- * class inherits an abstract method.
- *
- * 7.10 Superinterfaces: Let <i>C</i> be a concrete class that does not
- * declare its own <i>noSuchMethod()</i> method. It is a static warning if the
- * implicit interface of <i>C</i> includes an instance member <i>m</i> of type
- * <i>F</i> and <i>C</i> does not declare or inherit a corresponding instance
- * member <i>m</i> of type <i>F'</i> such that <i>F' <: F</i>.
- *
- * 7.4 Abstract Instance Members: It is a static warning if an abstract member
- * is declared or inherited in a concrete class unless that member overrides a
- * concrete one.
- *
- * Parameters:
- * 0: the name of the first member
- * 1: the name of the second member
- * 2: the name of the third member
- * 3: the name of the fourth member
- */
- static const StaticWarningCode
- NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER_FOUR =
- const StaticWarningCode(
- 'NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER_FOUR',
- "Missing concrete implementation of {0}, {1}, {2} and {3}");
-
- /**
- * 7.9.1 Inheritance and Overriding: It is a static warning if a non-abstract
- * class inherits an abstract method.
- *
- * 7.10 Superinterfaces: Let <i>C</i> be a concrete class that does not
- * declare its own <i>noSuchMethod()</i> method. It is a static warning if the
- * implicit interface of <i>C</i> includes an instance member <i>m</i> of type
- * <i>F</i> and <i>C</i> does not declare or inherit a corresponding instance
- * member <i>m</i> of type <i>F'</i> such that <i>F' <: F</i>.
- *
- * 7.4 Abstract Instance Members: It is a static warning if an abstract member
- * is declared or inherited in a concrete class unless that member overrides a
- * concrete one.
- *
- * Parameters:
- * 0: the name of the member
- */
- static const StaticWarningCode
- NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER_ONE = const StaticWarningCode(
- 'NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER_ONE',
- "Missing concrete implementation of {0}");
-
- /**
- * 7.9.1 Inheritance and Overriding: It is a static warning if a non-abstract
- * class inherits an abstract method.
- *
- * 7.10 Superinterfaces: Let <i>C</i> be a concrete class that does not
- * declare its own <i>noSuchMethod()</i> method. It is a static warning if the
- * implicit interface of <i>C</i> includes an instance member <i>m</i> of type
- * <i>F</i> and <i>C</i> does not declare or inherit a corresponding instance
- * member <i>m</i> of type <i>F'</i> such that <i>F' <: F</i>.
- *
- * 7.4 Abstract Instance Members: It is a static warning if an abstract member
- * is declared or inherited in a concrete class unless that member overrides a
- * concrete one.
- *
- * Parameters:
- * 0: the name of the first member
- * 1: the name of the second member
- * 2: the name of the third member
- */
- static const StaticWarningCode
- NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER_THREE =
- const StaticWarningCode(
- 'NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER_THREE',
- "Missing concrete implementation of {0}, {1} and {2}");
-
- /**
- * 7.9.1 Inheritance and Overriding: It is a static warning if a non-abstract
- * class inherits an abstract method.
- *
- * 7.10 Superinterfaces: Let <i>C</i> be a concrete class that does not
- * declare its own <i>noSuchMethod()</i> method. It is a static warning if the
- * implicit interface of <i>C</i> includes an instance member <i>m</i> of type
- * <i>F</i> and <i>C</i> does not declare or inherit a corresponding instance
- * member <i>m</i> of type <i>F'</i> such that <i>F' <: F</i>.
- *
- * 7.4 Abstract Instance Members: It is a static warning if an abstract member
- * is declared or inherited in a concrete class unless that member overrides a
- * concrete one.
- *
- * Parameters:
- * 0: the name of the first member
- * 1: the name of the second member
- */
- static const StaticWarningCode
- NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER_TWO = const StaticWarningCode(
- 'NON_ABSTRACT_CLASS_INHERITS_ABSTRACT_MEMBER_TWO',
- "Missing concrete implementation of {0} and {1}");
-
- /**
- * 13.11 Try: An on-catch clause of the form <i>on T catch (p<sub>1</sub>,
- * p<sub>2</sub>) s</i> or <i>on T s</i> matches an object <i>o</i> if the
- * type of <i>o</i> is a subtype of <i>T</i>. It is a static warning if
- * <i>T</i> does not denote a type available in the lexical scope of the
- * catch clause.
- *
- * Parameters:
- * 0: the name of the non-type element
- */
- static const StaticWarningCode NON_TYPE_IN_CATCH_CLAUSE =
- const StaticWarningCode('NON_TYPE_IN_CATCH_CLAUSE',
- "The name '{0}' is not a type and cannot be used in an on-catch clause");
-
- /**
- * 7.1.1 Operators: It is a static warning if the return type of the
- * user-declared operator []= is explicitly declared and not void.
- */
- static const StaticWarningCode NON_VOID_RETURN_FOR_OPERATOR =
- const StaticWarningCode('NON_VOID_RETURN_FOR_OPERATOR',
- "The return type of the operator []= must be 'void'", null, false);
-
- /**
- * 7.3 Setters: It is a static warning if a setter declares a return type
- * other than void.
- */
- static const StaticWarningCode NON_VOID_RETURN_FOR_SETTER =
- const StaticWarningCode('NON_VOID_RETURN_FOR_SETTER',
- "The return type of the setter must be 'void'", null, false);
-
- /**
- * 15.1 Static Types: A type <i>T</i> is malformed iff:
- * * <i>T</i> has the form <i>id</i> or the form <i>prefix.id</i>, and in the
- * enclosing lexical scope, the name <i>id</i> (respectively
- * <i>prefix.id</i>) does not denote a type.
- * * <i>T</i> denotes a type parameter in the enclosing lexical scope, but
- * occurs in the signature or body of a static member.
- * * <i>T</i> is a parameterized type of the form <i>G<S<sub>1</sub>, ..,
- * S<sub>n</sub>></i>,
- *
- * Any use of a malformed type gives rise to a static warning.
- *
- * Parameters:
- * 0: the name that is not a type
- */
- static const StaticWarningCode NOT_A_TYPE =
- const StaticWarningCode('NOT_A_TYPE', "{0} is not a type");
-
- /**
- * 12.14.2 Binding Actuals to Formals: It is a static warning if <i>m <
- * h</i> or if <i>m > n</i>.
- *
- * Parameters:
- * 0: the expected number of required arguments
- * 1: the actual number of positional arguments given
- *
- * See [EXTRA_POSITIONAL_ARGUMENTS].
- */
- static const StaticWarningCode NOT_ENOUGH_REQUIRED_ARGUMENTS =
- const StaticWarningCode('NOT_ENOUGH_REQUIRED_ARGUMENTS',
- "{0} required argument(s) expected, but {1} found");
-
- /**
- * 14.3 Parts: It is a static warning if the referenced part declaration
- * <i>p</i> names a library other than the current library as the library to
- * which <i>p</i> belongs.
- *
- * Parameters:
- * 0: the name of expected library name
- * 1: the non-matching actual library name from the "part of" declaration
- */
- static const StaticWarningCode PART_OF_DIFFERENT_LIBRARY =
- const StaticWarningCode('PART_OF_DIFFERENT_LIBRARY',
- "Expected this library to be part of '{0}', not '{1}'");
-
- /**
- * 7.6.2 Factories: It is a static warning if the function type of <i>k'</i>
- * is not a subtype of the type of <i>k</i>.
- *
- * Parameters:
- * 0: the name of the redirected constructor
- * 1: the name of the redirecting constructor
- */
- static const StaticWarningCode REDIRECT_TO_INVALID_FUNCTION_TYPE =
- const StaticWarningCode('REDIRECT_TO_INVALID_FUNCTION_TYPE',
- "The redirected constructor '{0}' has incompatible parameters with '{1}'");
-
- /**
- * 7.6.2 Factories: It is a static warning if the function type of <i>k'</i>
- * is not a subtype of the type of <i>k</i>.
- *
- * Parameters:
- * 0: the name of the redirected constructor return type
- * 1: the name of the redirecting constructor return type
- */
- static const StaticWarningCode REDIRECT_TO_INVALID_RETURN_TYPE =
- const StaticWarningCode('REDIRECT_TO_INVALID_RETURN_TYPE',
- "The return type '{0}' of the redirected constructor is not assignable to '{1}'");
-
- /**
- * 7.6.2 Factories: It is a static warning if type does not denote a class
- * accessible in the current scope; if type does denote such a class <i>C</i>
- * it is a static warning if the referenced constructor (be it <i>type</i> or
- * <i>type.id</i>) is not a constructor of <i>C</i>.
- */
- static const StaticWarningCode REDIRECT_TO_MISSING_CONSTRUCTOR =
- const StaticWarningCode('REDIRECT_TO_MISSING_CONSTRUCTOR',
- "The constructor '{0}' could not be found in '{1}'");
-
- /**
- * 7.6.2 Factories: It is a static warning if type does not denote a class
- * accessible in the current scope; if type does denote such a class <i>C</i>
- * it is a static warning if the referenced constructor (be it <i>type</i> or
- * <i>type.id</i>) is not a constructor of <i>C</i>.
- */
- static const StaticWarningCode REDIRECT_TO_NON_CLASS = const StaticWarningCode(
- 'REDIRECT_TO_NON_CLASS',
- "The name '{0}' is not a type and cannot be used in a redirected constructor");
-
- /**
- * 13.12 Return: Let <i>f</i> be the function immediately enclosing a return
- * statement of the form <i>return;</i> It is a static warning if both of the
- * following conditions hold:
- * * <i>f</i> is not a generative constructor.
- * * The return type of <i>f</i> may not be assigned to void.
- */
- static const StaticWarningCode RETURN_WITHOUT_VALUE = const StaticWarningCode(
- 'RETURN_WITHOUT_VALUE',
- "Missing return value after 'return'",
- null,
- false);
-
- /**
- * 12.16.3 Static Invocation: It is a static warning if <i>C</i> does not
- * declare a static method or getter <i>m</i>.
- *
- * Parameters:
- * 0: the name of the instance member
- */
- static const StaticWarningCode STATIC_ACCESS_TO_INSTANCE_MEMBER =
- const StaticWarningCode('STATIC_ACCESS_TO_INSTANCE_MEMBER',
- "Instance member '{0}' cannot be accessed using static access");
-
- /**
- * 13.9 Switch: It is a static warning if the type of <i>e</i> may not be
- * assigned to the type of <i>e<sub>k</sub></i>.
- */
- static const StaticWarningCode SWITCH_EXPRESSION_NOT_ASSIGNABLE =
- const StaticWarningCode('SWITCH_EXPRESSION_NOT_ASSIGNABLE',
- "Type '{0}' of the switch expression is not assignable to the type '{1}' of case expressions");
-
- /**
- * 15.1 Static Types: It is a static warning to use a deferred type in a type
- * annotation.
- *
- * Parameters:
- * 0: the name of the type that is deferred and being used in a type
- * annotation
- */
- static const StaticWarningCode TYPE_ANNOTATION_DEFERRED_CLASS =
- const StaticWarningCode('TYPE_ANNOTATION_DEFERRED_CLASS',
- "The deferred type '{0}' cannot be used in a declaration, cast or type test");
-
- /**
- * 12.31 Type Test: It is a static warning if <i>T</i> does not denote a type
- * available in the current lexical scope.
- */
- static const StaticWarningCode TYPE_TEST_WITH_NON_TYPE = const StaticWarningCode(
- 'TYPE_TEST_WITH_NON_TYPE',
- "The name '{0}' is not a type and cannot be used in an 'is' expression");
-
- /**
- * 12.31 Type Test: It is a static warning if <i>T</i> does not denote a type
- * available in the current lexical scope.
- */
- static const StaticWarningCode TYPE_TEST_WITH_UNDEFINED_NAME =
- const StaticWarningCode('TYPE_TEST_WITH_UNDEFINED_NAME',
- "The name '{0}' is not defined and cannot be used in an 'is' expression");
-
- /**
- * 10 Generics: However, a type parameter is considered to be a malformed type
- * when referenced by a static member.
- *
- * 15.1 Static Types: Any use of a malformed type gives rise to a static
- * warning. A malformed type is then interpreted as dynamic by the static type
- * checker and the runtime.
- */
- static const StaticWarningCode TYPE_PARAMETER_REFERENCED_BY_STATIC =
- const StaticWarningCode('TYPE_PARAMETER_REFERENCED_BY_STATIC',
- "Static members cannot reference type parameters of the class");
-
- /**
- * 12.16.3 Static Invocation: A static method invocation <i>i</i> has the form
- * <i>C.m(a<sub>1</sub>, …, a<sub>n</sub>, x<sub>n+1</sub>:
- * a<sub>n+1</sub>, … x<sub>n+k</sub>: a<sub>n+k</sub>)</i>. It is a
- * static warning if <i>C</i> does not denote a class in the current scope.
- *
- * Parameters:
- * 0: the name of the undefined class
- */
- static const StaticWarningCode UNDEFINED_CLASS =
- const StaticWarningCode('UNDEFINED_CLASS', "Undefined class '{0}'");
-
- /**
- * Same as [UNDEFINED_CLASS], but to catch using "boolean" instead of "bool".
- */
- static const StaticWarningCode UNDEFINED_CLASS_BOOLEAN =
- const StaticWarningCode('UNDEFINED_CLASS_BOOLEAN',
- "Undefined class 'boolean'; did you mean 'bool'?");
-
- /**
- * 12.17 Getter Invocation: It is a static warning if there is no class
- * <i>C</i> in the enclosing lexical scope of <i>i</i>, or if <i>C</i> does
- * not declare, implicitly or explicitly, a getter named <i>m</i>.
- *
- * Parameters:
- * 0: the name of the getter
- * 1: the name of the enclosing type where the getter is being looked for
- */
- static const StaticWarningCode UNDEFINED_GETTER =
- shared_messages.UNDEFINED_GETTER_STATIC_WARNING;
-
- /**
- * 12.30 Identifier Reference: It is as static warning if an identifier
- * expression of the form <i>id</i> occurs inside a top level or static
- * function (be it function, method, getter, or setter) or variable
- * initializer and there is no declaration <i>d</i> with name <i>id</i> in the
- * lexical scope enclosing the expression.
- *
- * Parameters:
- * 0: the name of the identifier
- */
- static const StaticWarningCode UNDEFINED_IDENTIFIER =
- const StaticWarningCode('UNDEFINED_IDENTIFIER', "Undefined name '{0}'");
-
- /**
- * If the identifier is 'await', be helpful about it.
- */
- static const StaticWarningCode UNDEFINED_IDENTIFIER_AWAIT =
- const StaticWarningCode('UNDEFINED_IDENTIFIER_AWAIT',
- "Undefined name 'await'; did you mean to add the 'async' marker to '{0}'?");
-
- /**
- * 12.14.2 Binding Actuals to Formals: Furthermore, each <i>q<sub>i</sub></i>,
- * <i>1<=i<=l</i>, must have a corresponding named parameter in the set
- * {<i>p<sub>n+1</sub></i> … <i>p<sub>n+k</sub></i>} or a static
- * warning occurs.
- *
- * Parameters:
- * 0: the name of the requested named parameter
- */
- static const StaticWarningCode UNDEFINED_NAMED_PARAMETER =
- const StaticWarningCode('UNDEFINED_NAMED_PARAMETER',
- "The named parameter '{0}' is not defined");
-
- /**
- * 12.18 Assignment: It is as static warning if an assignment of the form
- * <i>v = e</i> occurs inside a top level or static function (be it function,
- * method, getter, or setter) or variable initializer and there is no
- * declaration <i>d</i> with name <i>v=</i> in the lexical scope enclosing the
- * assignment.
- *
- * 12.18 Assignment: It is a static warning if there is no class <i>C</i> in
- * the enclosing lexical scope of the assignment, or if <i>C</i> does not
- * declare, implicitly or explicitly, a setter <i>v=</i>.
- *
- * Parameters:
- * 0: the name of the getter
- * 1: the name of the enclosing type where the setter is being looked for
- */
- static const StaticWarningCode UNDEFINED_SETTER =
- shared_messages.UNDEFINED_SETTER_STATIC_WARNING;
-
- /**
- * 12.16.3 Static Invocation: It is a static warning if <i>C</i> does not
- * declare a static method or getter <i>m</i>.
- *
- * Parameters:
- * 0: the name of the method
- * 1: the name of the enclosing type where the method is being looked for
- */
- static const StaticWarningCode UNDEFINED_STATIC_METHOD_OR_GETTER =
- const StaticWarningCode('UNDEFINED_STATIC_METHOD_OR_GETTER',
- "The static method, getter or setter '{0}' is not defined for the class '{1}'");
-
- /**
- * 12.17 Getter Invocation: It is a static warning if there is no class
- * <i>C</i> in the enclosing lexical scope of <i>i</i>, or if <i>C</i> does
- * not declare, implicitly or explicitly, a getter named <i>m</i>.
- *
- * Parameters:
- * 0: the name of the getter
- * 1: the name of the enclosing type where the getter is being looked for
- */
- static const StaticWarningCode UNDEFINED_SUPER_GETTER =
- shared_messages.UNDEFINED_SUPER_GETTER_STATIC_WARNING;
-
- /**
- * 12.18 Assignment: It is as static warning if an assignment of the form
- * <i>v = e</i> occurs inside a top level or static function (be it function,
- * method, getter, or setter) or variable initializer and there is no
- * declaration <i>d</i> with name <i>v=</i> in the lexical scope enclosing the
- * assignment.
- *
- * 12.18 Assignment: It is a static warning if there is no class <i>C</i> in
- * the enclosing lexical scope of the assignment, or if <i>C</i> does not
- * declare, implicitly or explicitly, a setter <i>v=</i>.
- *
- * Parameters:
- * 0: the name of the getter
- * 1: the name of the enclosing type where the setter is being looked for
- */
- static const StaticWarningCode UNDEFINED_SUPER_SETTER =
- shared_messages.UNDEFINED_SUPER_SETTER_STATIC_WARNING;
-
- /**
- * 7.2 Getters: It is a static warning if the return type of a getter is void.
- */
- static const StaticWarningCode VOID_RETURN_FOR_GETTER =
- const StaticWarningCode('VOID_RETURN_FOR_GETTER',
- "The return type of the getter must not be 'void'", null, false);
-
- /**
- * A flag indicating whether this warning is an error when running with strong
- * mode enabled.
- */
- final bool isStrongModeError;
-
- /**
- * Initialize a newly created error code to have the given [name]. The message
- * associated with the error will be created from the given [message]
- * template. The correction associated with the error will be created from the
- * given [correction] template.
- */
- const StaticWarningCode(String name, String message,
- [String correction, this.isStrongModeError = true])
- : super(name, message, correction);
-
- @override
- ErrorSeverity get errorSeverity => ErrorType.STATIC_WARNING.severity;
-
- @override
- ErrorType get type => ErrorType.STATIC_WARNING;
-}
-
-/**
- * This class has Strong Mode specific error codes.
- *
- * These error codes tend to use the same message across different severity
- * levels, so they are grouped for clarity.
- *
- * All of these error codes also use the "STRONG_MODE_" prefix in their name.
- */
-class StrongModeCode extends ErrorCode {
- static const String _implicitCastMessage =
- 'Unsound implicit cast from {0} to {1}';
-
- static const String _unsafeBlockClosureInferenceMessage =
- 'Unsafe use of block closure in a type-inferred variable outside a '
- 'function body. Workaround: add a type annotation for `{0}`. See '
- 'dartbug.com/26947';
-
- static const String _typeCheckMessage =
- 'Type check failed: {0} is not of type {1}';
-
- static const String _invalidOverrideMessage =
- 'The type of {0}.{1} ({2}) is not a '
- 'subtype of {3}.{1} ({4}).';
-
- /**
- * This is appended to the end of an error message about implicit dynamic.
- *
- * The idea is to make sure the user is aware that this error message is the
- * result of turning on a particular option, and they are free to turn it
- * back off.
- */
- static const String _implicitDynamicTip =
- ". Either add an explicit type like 'dynamic'"
- ", or enable implicit-dynamic in your Analyzer options.";
-
- static const String _inferredTypeMessage = '{0} has inferred type {1}';
-
- static const StrongModeCode DOWN_CAST_COMPOSITE = const StrongModeCode(
- ErrorType.STATIC_WARNING, 'DOWN_CAST_COMPOSITE', _implicitCastMessage);
-
- static const StrongModeCode DOWN_CAST_IMPLICIT = const StrongModeCode(
- ErrorType.HINT, 'DOWN_CAST_IMPLICIT', _implicitCastMessage);
-
- static const StrongModeCode DYNAMIC_CAST = const StrongModeCode(
- ErrorType.HINT, 'DYNAMIC_CAST', _implicitCastMessage);
-
- static const StrongModeCode ASSIGNMENT_CAST = const StrongModeCode(
- ErrorType.HINT, 'ASSIGNMENT_CAST', _implicitCastMessage);
-
- static const StrongModeCode INVALID_PARAMETER_DECLARATION =
- const StrongModeCode(ErrorType.COMPILE_TIME_ERROR,
- 'INVALID_PARAMETER_DECLARATION', _typeCheckMessage);
-
- static const StrongModeCode COULD_NOT_INFER = const StrongModeCode(
- ErrorType.COMPILE_TIME_ERROR,
- 'COULD_NOT_INFER',
- "Could not infer type parameter {0}, {1} must be of type {2}.");
-
- static const StrongModeCode INFERRED_TYPE = const StrongModeCode(
- ErrorType.HINT, 'INFERRED_TYPE', _inferredTypeMessage);
-
- static const StrongModeCode INFERRED_TYPE_LITERAL = const StrongModeCode(
- ErrorType.HINT, 'INFERRED_TYPE_LITERAL', _inferredTypeMessage);
-
- static const StrongModeCode INFERRED_TYPE_ALLOCATION = const StrongModeCode(
- ErrorType.HINT, 'INFERRED_TYPE_ALLOCATION', _inferredTypeMessage);
-
- static const StrongModeCode INFERRED_TYPE_CLOSURE = const StrongModeCode(
- ErrorType.HINT, 'INFERRED_TYPE_CLOSURE', _inferredTypeMessage);
-
- static const StrongModeCode STATIC_TYPE_ERROR = const StrongModeCode(
- ErrorType.COMPILE_TIME_ERROR,
- 'STATIC_TYPE_ERROR',
- 'Type check failed: {0} ({1}) is not of type {2}');
-
- static const StrongModeCode INVALID_SUPER_INVOCATION = const StrongModeCode(
- ErrorType.COMPILE_TIME_ERROR,
- 'INVALID_SUPER_INVOCATION',
- "super call must be last in an initializer "
- "list (see https://goo.gl/EY6hDP): {0}");
-
- static const StrongModeCode NON_GROUND_TYPE_CHECK_INFO = const StrongModeCode(
- ErrorType.HINT,
- 'NON_GROUND_TYPE_CHECK_INFO',
- "Runtime check on non-ground type {0} may throw StrongModeError");
-
- static const StrongModeCode DYNAMIC_INVOKE = const StrongModeCode(
- ErrorType.HINT, 'DYNAMIC_INVOKE', '{0} requires a dynamic invoke');
-
- static const StrongModeCode INVALID_METHOD_OVERRIDE = const StrongModeCode(
- ErrorType.COMPILE_TIME_ERROR,
- 'INVALID_METHOD_OVERRIDE',
- 'Invalid override. $_invalidOverrideMessage');
-
- static const StrongModeCode INVALID_METHOD_OVERRIDE_FROM_BASE =
- const StrongModeCode(
- ErrorType.COMPILE_TIME_ERROR,
- 'INVALID_METHOD_OVERRIDE_FROM_BASE',
- 'Base class introduces an invalid override. '
- '$_invalidOverrideMessage');
-
- static const StrongModeCode INVALID_METHOD_OVERRIDE_FROM_MIXIN =
- const StrongModeCode(
- ErrorType.COMPILE_TIME_ERROR,
- 'INVALID_METHOD_OVERRIDE_FROM_MIXIN',
- 'Mixin introduces an invalid override. $_invalidOverrideMessage');
-
- static const StrongModeCode INVALID_FIELD_OVERRIDE = const StrongModeCode(
- ErrorType.COMPILE_TIME_ERROR,
- 'INVALID_FIELD_OVERRIDE',
- 'Field declaration {3}.{1} cannot be '
- 'overridden in {0}.');
-
- static const StrongModeCode IMPLICIT_DYNAMIC_PARAMETER = const StrongModeCode(
- ErrorType.COMPILE_TIME_ERROR,
- 'IMPLICIT_DYNAMIC_PARAMETER',
- "Missing parameter type for '{0}'$_implicitDynamicTip");
-
- static const StrongModeCode IMPLICIT_DYNAMIC_RETURN = const StrongModeCode(
- ErrorType.COMPILE_TIME_ERROR,
- 'IMPLICIT_DYNAMIC_RETURN',
- "Missing return type for '{0}'$_implicitDynamicTip");
-
- static const StrongModeCode IMPLICIT_DYNAMIC_VARIABLE = const StrongModeCode(
- ErrorType.COMPILE_TIME_ERROR,
- 'IMPLICIT_DYNAMIC_VARIABLE',
- "Missing variable type for '{0}'$_implicitDynamicTip");
-
- static const StrongModeCode IMPLICIT_DYNAMIC_FIELD = const StrongModeCode(
- ErrorType.COMPILE_TIME_ERROR,
- 'IMPLICIT_DYNAMIC_FIELD',
- "Missing field type for '{0}'$_implicitDynamicTip");
-
- static const StrongModeCode IMPLICIT_DYNAMIC_TYPE = const StrongModeCode(
- ErrorType.COMPILE_TIME_ERROR,
- 'IMPLICIT_DYNAMIC_TYPE',
- "Missing type arguments for generic type '{0}'"
- "$_implicitDynamicTip");
-
- static const StrongModeCode IMPLICIT_DYNAMIC_LIST_LITERAL =
- const StrongModeCode(
- ErrorType.COMPILE_TIME_ERROR,
- 'IMPLICIT_DYNAMIC_LIST_LITERAL',
- "Missing type argument for list literal$_implicitDynamicTip");
-
- static const StrongModeCode IMPLICIT_DYNAMIC_MAP_LITERAL =
- const StrongModeCode(
- ErrorType.COMPILE_TIME_ERROR,
- 'IMPLICIT_DYNAMIC_MAP_LITERAL',
- 'Missing type arguments for map literal$_implicitDynamicTip');
-
- static const StrongModeCode IMPLICIT_DYNAMIC_FUNCTION = const StrongModeCode(
- ErrorType.COMPILE_TIME_ERROR,
- 'IMPLICIT_DYNAMIC_FUNCTION',
- "Missing type arguments for generic function '{0}<{1}>'"
- "$_implicitDynamicTip");
-
- static const StrongModeCode IMPLICIT_DYNAMIC_METHOD = const StrongModeCode(
- ErrorType.COMPILE_TIME_ERROR,
- 'IMPLICIT_DYNAMIC_METHOD',
- "Missing type arguments for generic method '{0}<{1}>'"
- "$_implicitDynamicTip");
-
- static const StrongModeCode IMPLICIT_DYNAMIC_INVOKE = const StrongModeCode(
- ErrorType.COMPILE_TIME_ERROR,
- 'IMPLICIT_DYNAMIC_INVOKE',
- "Missing type arguments for calling generic function type '{0}'"
- "$_implicitDynamicTip");
-
- static const StrongModeCode UNSAFE_BLOCK_CLOSURE_INFERENCE =
- const StrongModeCode(
- ErrorType.STATIC_WARNING,
- 'UNSAFE_BLOCK_CLOSURE_INFERENCE',
- _unsafeBlockClosureInferenceMessage);
-
- @override
- final ErrorType type;
-
- /**
- * Initialize a newly created error code to have the given [type] and [name].
- *
- * The message associated with the error will be created from the given
- * [message] template. The correction associated with the error will be
- * created from the optional [correction] template.
- */
- const StrongModeCode(ErrorType type, String name, String message,
- [String correction])
- : type = type,
- super('STRONG_MODE_$name', message, correction);
-
- @override
- ErrorSeverity get errorSeverity => type.severity;
-}
-
-/**
- * The error code indicating a marker in code for work that needs to be finished
- * or revisited.
- */
-class TodoCode extends ErrorCode {
- /**
- * The single enum of TodoCode.
- */
- static const TodoCode TODO = const TodoCode('TODO');
-
- /**
- * This matches the two common Dart task styles
- *
- * * TODO:
- * * TODO(username):
- *
- * As well as
- * * TODO
- *
- * But not
- * * todo
- * * TODOS
- */
- static RegExp TODO_REGEX =
- new RegExp("([\\s/\\*])((TODO[^\\w\\d][^\\r\\n]*)|(TODO:?\$))");
-
- /**
- * Initialize a newly created error code to have the given [name].
- */
- const TodoCode(String name) : super(name, "{0}");
-
- @override
- ErrorSeverity get errorSeverity => ErrorSeverity.INFO;
-
- @override
- ErrorType get type => ErrorType.TODO;
-}
+export 'package:analyzer/error/error.dart';
+export 'package:analyzer/error/listener.dart';
+export 'package:analyzer/src/error/codes.dart';
+export 'package:analyzer/src/task/options.dart'
+ show CONFIGURED_ERROR_PROCESSORS;
diff --git a/pkg/analyzer/lib/src/generated/error_verifier.dart b/pkg/analyzer/lib/src/generated/error_verifier.dart
index 717ef2a..47a4979 100644
--- a/pkg/analyzer/lib/src/generated/error_verifier.dart
+++ b/pkg/analyzer/lib/src/generated/error_verifier.dart
@@ -13,15 +13,17 @@
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/type.dart';
import 'package:analyzer/dart/element/visitor.dart';
+import 'package:analyzer/error/error.dart';
+import 'package:analyzer/error/listener.dart';
import 'package:analyzer/src/dart/element/element.dart';
import 'package:analyzer/src/dart/element/member.dart';
import 'package:analyzer/src/dart/element/type.dart';
import 'package:analyzer/src/dart/resolver/inheritance_manager.dart';
+import 'package:analyzer/src/error/codes.dart';
import 'package:analyzer/src/error/pending_error.dart';
import 'package:analyzer/src/generated/constant.dart';
import 'package:analyzer/src/generated/element_resolver.dart';
import 'package:analyzer/src/generated/engine.dart';
-import 'package:analyzer/src/generated/error.dart';
import 'package:analyzer/src/generated/java_engine.dart';
import 'package:analyzer/src/generated/parser.dart' show ParserErrorCode;
import 'package:analyzer/src/generated/resolver.dart';
@@ -2491,7 +2493,6 @@
DartType expectedStaticType,
ErrorCode errorCode) {
// TODO(leafp): Move the Downcast functionality here.
- // TODO(leafp): Support strict downcasts
if (!_expressionIsAssignableAtType(
expression, actualStaticType, expectedStaticType)) {
_errorReporter.reportTypeErrorForNode(
@@ -5038,11 +5039,19 @@
FunctionType requiredMemberFT = _inheritanceManager
.substituteTypeArgumentsInMemberFromInheritance(
requiredMemberType, memberName, enclosingType);
- foundConcreteFT =
- _typeSystem.typeToConcreteType(_typeProvider, foundConcreteFT);
- requiredMemberFT =
- _typeSystem.typeToConcreteType(_typeProvider, requiredMemberFT);
- if (_typeSystem.isSubtypeOf(foundConcreteFT, requiredMemberFT)) {
+ foundConcreteFT = _typeSystem.functionTypeToConcreteType(
+ _typeProvider, foundConcreteFT);
+ requiredMemberFT = _typeSystem.functionTypeToConcreteType(
+ _typeProvider, requiredMemberFT);
+
+ // Strong mode does override checking for types in CodeChecker, so
+ // we can skip it here. Doing it here leads to unnecessary duplicate
+ // error messages in subclasses that inherit from one that has an
+ // override error.
+ //
+ // See: https://github.com/dart-lang/sdk/issues/25232
+ if (_options.strongMode ||
+ _typeSystem.isSubtypeOf(foundConcreteFT, requiredMemberFT)) {
continue;
}
}
@@ -6229,11 +6238,10 @@
bool _expressionIsAssignableAtType(Expression expression,
DartType actualStaticType, DartType expectedStaticType) {
bool concrete = _options.strongMode && checker.isKnownFunction(expression);
- if (concrete) {
- actualStaticType =
- _typeSystem.typeToConcreteType(_typeProvider, actualStaticType);
+ if (concrete && actualStaticType is FunctionType) {
+ actualStaticType = _typeSystem.functionTypeToConcreteType(
+ _typeProvider, actualStaticType);
// TODO(leafp): Move the Downcast functionality here.
- // TODO(leafp): Support strict downcasts
}
return _typeSystem.isAssignableTo(actualStaticType, expectedStaticType);
}
diff --git a/pkg/analyzer/lib/src/generated/incremental_resolver.dart b/pkg/analyzer/lib/src/generated/incremental_resolver.dart
index bebf33e..f17e793 100644
--- a/pkg/analyzer/lib/src/generated/incremental_resolver.dart
+++ b/pkg/analyzer/lib/src/generated/incremental_resolver.dart
@@ -11,6 +11,8 @@
import 'package:analyzer/dart/ast/token.dart';
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/visitor.dart';
+import 'package:analyzer/error/error.dart';
+import 'package:analyzer/error/listener.dart';
import 'package:analyzer/exception/exception.dart';
import 'package:analyzer/src/context/cache.dart';
import 'package:analyzer/src/dart/ast/token.dart';
@@ -22,7 +24,6 @@
import 'package:analyzer/src/dart/scanner/scanner.dart';
import 'package:analyzer/src/generated/constant.dart';
import 'package:analyzer/src/generated/engine.dart';
-import 'package:analyzer/src/generated/error.dart';
import 'package:analyzer/src/generated/error_verifier.dart';
import 'package:analyzer/src/generated/incremental_logger.dart'
show logger, LoggingTimer;
diff --git a/pkg/analyzer/lib/src/generated/java_core.dart b/pkg/analyzer/lib/src/generated/java_core.dart
index 382fa0d..ed0d03f 100644
--- a/pkg/analyzer/lib/src/generated/java_core.dart
+++ b/pkg/analyzer/lib/src/generated/java_core.dart
@@ -39,6 +39,45 @@
});
}
+/**
+ * Very limited printf implementation, supports only %s and %d.
+ */
+String _printf(String fmt, List args) {
+ StringBuffer sb = new StringBuffer();
+ bool markFound = false;
+ int argIndex = 0;
+ for (int i = 0; i < fmt.length; i++) {
+ int c = fmt.codeUnitAt(i);
+ if (c == 0x25) {
+ if (markFound) {
+ sb.writeCharCode(c);
+ markFound = false;
+ } else {
+ markFound = true;
+ }
+ continue;
+ }
+ if (markFound) {
+ markFound = false;
+ // %d
+ if (c == 0x64) {
+ sb.write(args[argIndex++]);
+ continue;
+ }
+ // %s
+ if (c == 0x73) {
+ sb.write(args[argIndex++]);
+ continue;
+ }
+ // unknown
+ throw new ArgumentError('[$fmt][$i] = 0x${c.toRadixString(16)}');
+ } else {
+ sb.writeCharCode(c);
+ }
+ }
+ return sb.toString();
+}
+
class Character {
static const int MAX_VALUE = 0xffff;
static const int MAX_CODE_POINT = 0x10ffff;
@@ -97,3 +136,30 @@
int compareTo(E other) => ordinal - other.ordinal;
String toString() => name;
}
+
+class PrintStringWriter extends PrintWriter {
+ final StringBuffer _sb = new StringBuffer();
+
+ void print(x) {
+ _sb.write(x);
+ }
+
+ String toString() => _sb.toString();
+}
+
+abstract class PrintWriter {
+ void newLine() {
+ this.print('\n');
+ }
+
+ void print(x);
+
+ void printf(String fmt, List args) {
+ this.print(_printf(fmt, args));
+ }
+
+ void println(String s) {
+ this.print(s);
+ this.newLine();
+ }
+}
diff --git a/pkg/analyzer/lib/src/generated/parser.dart b/pkg/analyzer/lib/src/generated/parser.dart
index 8e7bbe1..672f761 100644
--- a/pkg/analyzer/lib/src/generated/parser.dart
+++ b/pkg/analyzer/lib/src/generated/parser.dart
@@ -9,12 +9,14 @@
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/ast/token.dart';
+import 'package:analyzer/error/error.dart';
+import 'package:analyzer/error/listener.dart';
import 'package:analyzer/src/dart/ast/ast.dart';
import 'package:analyzer/src/dart/ast/token.dart';
import 'package:analyzer/src/dart/scanner/reader.dart';
import 'package:analyzer/src/dart/scanner/scanner.dart';
+import 'package:analyzer/src/error/codes.dart';
import 'package:analyzer/src/generated/engine.dart' show AnalysisEngine;
-import 'package:analyzer/src/generated/error.dart';
import 'package:analyzer/src/generated/generated/shared_messages.dart'
as shared_messages;
import 'package:analyzer/src/generated/java_core.dart';
@@ -88,7 +90,7 @@
'parseTypeArgumentList_0': new MethodTrampoline(
0, (Parser target) => target.parseTypeArgumentList()),
'parseTypeName_0':
- new MethodTrampoline(0, (Parser target) => target.parseTypeName()),
+ new MethodTrampoline(0, (Parser target) => target.parseTypeName(false)),
'parseTypeParameter_0':
new MethodTrampoline(0, (Parser target) => target.parseTypeParameter()),
'parseTypeParameterList_0': new MethodTrampoline(
@@ -100,20 +102,16 @@
5,
(Parser target, arg0, arg1, arg2, arg3, arg4) =>
target._appendScalarValue(arg0, arg1, arg2, arg3, arg4)),
- 'computeStringValue_3': new MethodTrampoline(
- 3,
- (Parser target, arg0, arg1, arg2) =>
- target._computeStringValue(arg0, arg1, arg2)),
'convertToFunctionDeclaration_1': new MethodTrampoline(
1, (Parser target, arg0) => target._convertToFunctionDeclaration(arg0)),
'couldBeStartOfCompilationUnitMember_0': new MethodTrampoline(
0, (Parser target) => target._couldBeStartOfCompilationUnitMember()),
'createSyntheticIdentifier_0': new MethodTrampoline(
- 0, (Parser target) => target._createSyntheticIdentifier()),
+ 0, (Parser target) => target.createSyntheticIdentifier()),
'createSyntheticKeyword_1': new MethodTrampoline(
1, (Parser target, arg0) => target._createSyntheticKeyword(arg0)),
'createSyntheticStringLiteral_0': new MethodTrampoline(
- 0, (Parser target) => target._createSyntheticStringLiteral()),
+ 0, (Parser target) => target.createSyntheticStringLiteral()),
'createSyntheticToken_1': new MethodTrampoline(
1, (Parser target, arg0) => target._createSyntheticToken(arg0)),
'ensureAssignable_1': new MethodTrampoline(
@@ -134,19 +132,19 @@
'injectToken_1': new MethodTrampoline(
1, (Parser target, arg0) => target._injectToken(arg0)),
'isFunctionDeclaration_0': new MethodTrampoline(
- 0, (Parser target) => target._isFunctionDeclaration()),
+ 0, (Parser target) => target.isFunctionDeclaration()),
'isFunctionExpression_1': new MethodTrampoline(
- 1, (Parser target, arg0) => target._isFunctionExpression(arg0)),
+ 1, (Parser target, arg0) => target.isFunctionExpression(arg0)),
'isHexDigit_1': new MethodTrampoline(
1, (Parser target, arg0) => target._isHexDigit(arg0)),
'isInitializedVariableDeclaration_0': new MethodTrampoline(
- 0, (Parser target) => target._isInitializedVariableDeclaration()),
+ 0, (Parser target) => target.isInitializedVariableDeclaration()),
'isLinkText_2': new MethodTrampoline(
2, (Parser target, arg0, arg1) => target._isLinkText(arg0, arg1)),
'isOperator_1': new MethodTrampoline(
1, (Parser target, arg0) => target._isOperator(arg0)),
'isSwitchMember_0':
- new MethodTrampoline(0, (Parser target) => target._isSwitchMember()),
+ new MethodTrampoline(0, (Parser target) => target.isSwitchMember()),
'isTypedIdentifier_1': new MethodTrampoline(
1, (Parser target, arg0) => target._isTypedIdentifier(arg0)),
'lockErrorListener_0':
@@ -164,51 +162,51 @@
'optional_1':
new MethodTrampoline(1, (Parser target, arg0) => target._optional(arg0)),
'parseAdditiveExpression_0': new MethodTrampoline(
- 0, (Parser target) => target._parseAdditiveExpression()),
- 'parseAssertStatement_0': new MethodTrampoline(
- 0, (Parser target) => target._parseAssertStatement()),
+ 0, (Parser target) => target.parseAdditiveExpression()),
+ 'parseAssertStatement_0':
+ new MethodTrampoline(0, (Parser target) => target.parseAssertStatement()),
'parseAssignableExpression_1': new MethodTrampoline(
- 1, (Parser target, arg0) => target._parseAssignableExpression(arg0)),
+ 1, (Parser target, arg0) => target.parseAssignableExpression(arg0)),
'parseAssignableSelector_2': new MethodTrampoline(
2,
(Parser target, arg0, arg1) =>
target._parseAssignableSelector(arg0, arg1)),
- 'parseAwaitExpression_0': new MethodTrampoline(
- 0, (Parser target) => target._parseAwaitExpression()),
+ 'parseAwaitExpression_0':
+ new MethodTrampoline(0, (Parser target) => target.parseAwaitExpression()),
'parseBitwiseAndExpression_0': new MethodTrampoline(
- 0, (Parser target) => target._parseBitwiseAndExpression()),
+ 0, (Parser target) => target.parseBitwiseAndExpression()),
'parseBitwiseXorExpression_0': new MethodTrampoline(
- 0, (Parser target) => target._parseBitwiseXorExpression()),
+ 0, (Parser target) => target.parseBitwiseXorExpression()),
'parseBreakStatement_0':
- new MethodTrampoline(0, (Parser target) => target._parseBreakStatement()),
+ new MethodTrampoline(0, (Parser target) => target.parseBreakStatement()),
'parseCascadeSection_0':
- new MethodTrampoline(0, (Parser target) => target._parseCascadeSection()),
+ new MethodTrampoline(0, (Parser target) => target.parseCascadeSection()),
'parseClassDeclaration_2': new MethodTrampoline(2,
- (Parser target, arg0, arg1) => target._parseClassDeclaration(arg0, arg1)),
+ (Parser target, arg0, arg1) => target.parseClassDeclaration(arg0, arg1)),
'parseClassMembers_2': new MethodTrampoline(
2, (Parser target, arg0, arg1) => target._parseClassMembers(arg0, arg1)),
'parseClassTypeAlias_3': new MethodTrampoline(
3,
(Parser target, arg0, arg1, arg2) =>
- target._parseClassTypeAlias(arg0, arg1, arg2)),
+ target.parseClassTypeAlias(arg0, arg1, arg2)),
'parseCombinator_0':
new MethodTrampoline(0, (Parser target) => target.parseCombinator()),
'parseCombinators_0':
- new MethodTrampoline(0, (Parser target) => target._parseCombinators()),
+ new MethodTrampoline(0, (Parser target) => target.parseCombinators()),
'parseCommentAndMetadata_0': new MethodTrampoline(
- 0, (Parser target) => target._parseCommentAndMetadata()),
+ 0, (Parser target) => target.parseCommentAndMetadata()),
'parseCommentReference_2': new MethodTrampoline(2,
- (Parser target, arg0, arg1) => target._parseCommentReference(arg0, arg1)),
+ (Parser target, arg0, arg1) => target.parseCommentReference(arg0, arg1)),
'parseCommentReferences_1': new MethodTrampoline(
1,
(Parser target, List<DocumentationCommentToken> arg0) =>
target._parseCommentReferences(arg0)),
'parseCompilationUnitMember_1': new MethodTrampoline(
- 1, (Parser target, arg0) => target._parseCompilationUnitMember(arg0)),
+ 1, (Parser target, arg0) => target.parseCompilationUnitMember(arg0)),
'parseConfiguration_0':
- new MethodTrampoline(0, (Parser target) => target._parseConfiguration()),
- 'parseConstExpression_0': new MethodTrampoline(
- 0, (Parser target) => target._parseConstExpression()),
+ new MethodTrampoline(0, (Parser target) => target.parseConfiguration()),
+ 'parseConstExpression_0':
+ new MethodTrampoline(0, (Parser target) => target.parseConstExpression()),
'parseConstructor_8': new MethodTrampoline(
8,
(Parser target, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7) => target
@@ -216,48 +214,48 @@
'parseConstructorFieldInitializer_1': new MethodTrampoline(1,
(Parser target, arg0) => target._parseConstructorFieldInitializer(arg0)),
'parseContinueStatement_0': new MethodTrampoline(
- 0, (Parser target) => target._parseContinueStatement()),
+ 0, (Parser target) => target.parseContinueStatement()),
'parseDirective_1': new MethodTrampoline(
1, (Parser target, arg0) => target._parseDirective(arg0)),
'parseDirectives_0':
- new MethodTrampoline(0, (Parser target) => target._parseDirectives()),
+ new MethodTrampoline(0, (Parser target) => target.parseDirectives2()),
'parseDocumentationComment_0': new MethodTrampoline(0, (Parser target) {
List<DocumentationCommentToken> tokens =
- target._parseDocumentationCommentTokens();
- return target._parseDocumentationComment(tokens);
+ target.parseDocumentationCommentTokens();
+ return target.parseDocumentationComment(tokens);
}),
'parseDoStatement_0':
- new MethodTrampoline(0, (Parser target) => target._parseDoStatement()),
+ new MethodTrampoline(0, (Parser target) => target.parseDoStatement()),
'parseDottedName_0':
- new MethodTrampoline(0, (Parser target) => target._parseDottedName()),
+ new MethodTrampoline(0, (Parser target) => target.parseDottedName()),
'parseEmptyStatement_0':
- new MethodTrampoline(0, (Parser target) => target._parseEmptyStatement()),
+ new MethodTrampoline(0, (Parser target) => target.parseEmptyStatement()),
'parseEnumConstantDeclaration_0': new MethodTrampoline(
0, (Parser target) => target._parseEnumConstantDeclaration()),
'parseEnumDeclaration_1': new MethodTrampoline(
- 1, (Parser target, arg0) => target._parseEnumDeclaration(arg0)),
+ 1, (Parser target, arg0) => target.parseEnumDeclaration(arg0)),
'parseEqualityExpression_0': new MethodTrampoline(
0, (Parser target) => target._parseEqualityExpression()),
'parseExportDirective_1': new MethodTrampoline(
1, (Parser target, arg0) => target._parseExportDirective(arg0)),
'parseExpressionList_0':
- new MethodTrampoline(0, (Parser target) => target._parseExpressionList()),
+ new MethodTrampoline(0, (Parser target) => target.parseExpressionList()),
'parseFinalConstVarOrType_1': new MethodTrampoline(
- 1, (Parser target, arg0) => target._parseFinalConstVarOrType(arg0)),
+ 1, (Parser target, arg0) => target.parseFinalConstVarOrType(arg0)),
'parseFormalParameter_1': new MethodTrampoline(
1, (Parser target, arg0) => target._parseFormalParameter(arg0)),
'parseForStatement_0':
- new MethodTrampoline(0, (Parser target) => target._parseForStatement()),
+ new MethodTrampoline(0, (Parser target) => target.parseForStatement()),
'parseFunctionBody_3': new MethodTrampoline(
3,
(Parser target, arg0, arg1, arg2) =>
- target._parseFunctionBody(arg0, arg1, arg2)),
+ target.parseFunctionBody(arg0, arg1, arg2)),
'parseFunctionDeclaration_3': new MethodTrampoline(
3,
(Parser target, arg0, arg1, arg2) =>
target._parseFunctionDeclaration(arg0, arg1, arg2)),
'parseFunctionDeclarationStatement_0': new MethodTrampoline(
- 0, (Parser target) => target._parseFunctionDeclarationStatement()),
+ 0, (Parser target) => target.parseFunctionDeclarationStatement()),
'parseFunctionDeclarationStatementAfterReturnType_2': new MethodTrampoline(
2,
(Parser target, arg0, arg1) =>
@@ -273,7 +271,7 @@
'parseIdentifierList_0':
new MethodTrampoline(0, (Parser target) => target._parseIdentifierList()),
'parseIfStatement_0':
- new MethodTrampoline(0, (Parser target) => target._parseIfStatement()),
+ new MethodTrampoline(0, (Parser target) => target.parseIfStatement()),
'parseImportDirective_1': new MethodTrampoline(
1, (Parser target, arg0) => target._parseImportDirective(arg0)),
'parseInitializedIdentifierList_4': new MethodTrampoline(
@@ -289,7 +287,7 @@
'parseListLiteral_2': new MethodTrampoline(
2, (Parser target, arg0, arg1) => target._parseListLiteral(arg0, arg1)),
'parseListOrMapLiteral_1': new MethodTrampoline(
- 1, (Parser target, arg0) => target._parseListOrMapLiteral(arg0)),
+ 1, (Parser target, arg0) => target.parseListOrMapLiteral(arg0)),
'parseLogicalAndExpression_0': new MethodTrampoline(
0, (Parser target) => target._parseLogicalAndExpression()),
'parseMapLiteral_2': new MethodTrampoline(
@@ -306,7 +304,7 @@
'parseModifiers_0':
new MethodTrampoline(0, (Parser target) => target._parseModifiers()),
'parseMultiplicativeExpression_0': new MethodTrampoline(
- 0, (Parser target) => target._parseMultiplicativeExpression()),
+ 0, (Parser target) => target.parseMultiplicativeExpression()),
'parseNativeClause_0':
new MethodTrampoline(0, (Parser target) => target._parseNativeClause()),
'parseNewExpression_0':
@@ -316,7 +314,7 @@
'parseOperator_3': new MethodTrampoline(
3,
(Parser target, arg0, arg1, arg2) =>
- target._parseOperator(arg0, arg1, arg2)),
+ target.parseOperator(arg0, arg1, arg2)),
'parseOptionalReturnType_0': new MethodTrampoline(
0, (Parser target) => target._parseOptionalReturnType()),
'parsePartDirective_1': new MethodTrampoline(
@@ -324,65 +322,65 @@
'parsePostfixExpression_0': new MethodTrampoline(
0, (Parser target) => target._parsePostfixExpression()),
'parsePrimaryExpression_0': new MethodTrampoline(
- 0, (Parser target) => target._parsePrimaryExpression()),
+ 0, (Parser target) => target.parsePrimaryExpression()),
'parseRedirectingConstructorInvocation_1': new MethodTrampoline(
1,
(Parser target, arg0) =>
target._parseRedirectingConstructorInvocation(arg0)),
'parseRelationalExpression_0': new MethodTrampoline(
- 0, (Parser target) => target._parseRelationalExpression()),
+ 0, (Parser target) => target.parseRelationalExpression()),
'parseRethrowExpression_0': new MethodTrampoline(
- 0, (Parser target) => target._parseRethrowExpression()),
- 'parseReturnStatement_0': new MethodTrampoline(
- 0, (Parser target) => target._parseReturnStatement()),
+ 0, (Parser target) => target.parseRethrowExpression()),
+ 'parseReturnStatement_0':
+ new MethodTrampoline(0, (Parser target) => target.parseReturnStatement()),
'parseSetter_4': new MethodTrampoline(
4,
(Parser target, arg0, arg1, arg2, arg3) =>
target._parseSetter(arg0, arg1, arg2, arg3)),
- 'parseShiftExpression_0': new MethodTrampoline(
- 0, (Parser target) => target._parseShiftExpression()),
+ 'parseShiftExpression_0':
+ new MethodTrampoline(0, (Parser target) => target.parseShiftExpression()),
'parseStatementList_0':
new MethodTrampoline(0, (Parser target) => target._parseStatementList()),
'parseStringInterpolation_1': new MethodTrampoline(
1, (Parser target, arg0) => target._parseStringInterpolation(arg0)),
'parseSuperConstructorInvocation_0': new MethodTrampoline(
- 0, (Parser target) => target._parseSuperConstructorInvocation()),
- 'parseSwitchStatement_0': new MethodTrampoline(
- 0, (Parser target) => target._parseSwitchStatement()),
+ 0, (Parser target) => target.parseSuperConstructorInvocation()),
+ 'parseSwitchStatement_0':
+ new MethodTrampoline(0, (Parser target) => target.parseSwitchStatement()),
'parseSymbolLiteral_0':
- new MethodTrampoline(0, (Parser target) => target._parseSymbolLiteral()),
- 'parseThrowExpression_0': new MethodTrampoline(
- 0, (Parser target) => target._parseThrowExpression()),
+ new MethodTrampoline(0, (Parser target) => target.parseSymbolLiteral()),
+ 'parseThrowExpression_0':
+ new MethodTrampoline(0, (Parser target) => target.parseThrowExpression()),
'parseThrowExpressionWithoutCascade_0': new MethodTrampoline(
- 0, (Parser target) => target._parseThrowExpressionWithoutCascade()),
+ 0, (Parser target) => target.parseThrowExpressionWithoutCascade()),
'parseTryStatement_0':
- new MethodTrampoline(0, (Parser target) => target._parseTryStatement()),
+ new MethodTrampoline(0, (Parser target) => target.parseTryStatement()),
'parseTypeAlias_1': new MethodTrampoline(
1, (Parser target, arg0) => target._parseTypeAlias(arg0)),
- 'parseUnaryExpression_0': new MethodTrampoline(
- 0, (Parser target) => target._parseUnaryExpression()),
+ 'parseUnaryExpression_0':
+ new MethodTrampoline(0, (Parser target) => target.parseUnaryExpression()),
'parseVariableDeclaration_0': new MethodTrampoline(
- 0, (Parser target) => target._parseVariableDeclaration()),
+ 0, (Parser target) => target.parseVariableDeclaration()),
'parseVariableDeclarationListAfterMetadata_1': new MethodTrampoline(
1,
(Parser target, arg0) =>
- target._parseVariableDeclarationListAfterMetadata(arg0)),
+ target.parseVariableDeclarationListAfterMetadata(arg0)),
'parseVariableDeclarationListAfterType_3': new MethodTrampoline(
3,
(Parser target, arg0, arg1, arg2) =>
- target._parseVariableDeclarationListAfterType(arg0, arg1, arg2)),
+ target.parseVariableDeclarationListAfterType(arg0, arg1, arg2)),
'parseVariableDeclarationStatementAfterMetadata_1': new MethodTrampoline(
1,
(Parser target, arg0) =>
- target._parseVariableDeclarationStatementAfterMetadata(arg0)),
+ target.parseVariableDeclarationStatementAfterMetadata(arg0)),
'parseVariableDeclarationStatementAfterType_3': new MethodTrampoline(
3,
(Parser target, arg0, arg1, arg2) =>
target._parseVariableDeclarationStatementAfterType(arg0, arg1, arg2)),
'parseWhileStatement_0':
- new MethodTrampoline(0, (Parser target) => target._parseWhileStatement()),
+ new MethodTrampoline(0, (Parser target) => target.parseWhileStatement()),
'parseYieldStatement_0':
- new MethodTrampoline(0, (Parser target) => target._parseYieldStatement()),
+ new MethodTrampoline(0, (Parser target) => target.parseYieldStatement()),
'peek_0': new MethodTrampoline(0, (Parser target) => target._peek()),
'peekAt_1':
new MethodTrampoline(1, (Parser target, arg0) => target._peekAt(arg0)),
@@ -409,19 +407,19 @@
'skipPastMatchingToken_1': new MethodTrampoline(
1, (Parser target, arg0) => target._skipPastMatchingToken(arg0)),
'skipPrefixedIdentifier_1': new MethodTrampoline(
- 1, (Parser target, arg0) => target._skipPrefixedIdentifier(arg0)),
+ 1, (Parser target, arg0) => target.skipPrefixedIdentifier(arg0)),
'skipReturnType_1': new MethodTrampoline(
- 1, (Parser target, arg0) => target._skipReturnType(arg0)),
+ 1, (Parser target, arg0) => target.skipReturnType(arg0)),
'skipSimpleIdentifier_1': new MethodTrampoline(
- 1, (Parser target, arg0) => target._skipSimpleIdentifier(arg0)),
+ 1, (Parser target, arg0) => target.skipSimpleIdentifier(arg0)),
'skipStringInterpolation_1': new MethodTrampoline(
1, (Parser target, arg0) => target._skipStringInterpolation(arg0)),
'skipStringLiteral_1': new MethodTrampoline(
- 1, (Parser target, arg0) => target._skipStringLiteral(arg0)),
+ 1, (Parser target, arg0) => target.skipStringLiteral(arg0)),
'skipTypeArgumentList_1': new MethodTrampoline(
- 1, (Parser target, arg0) => target._skipTypeArgumentList(arg0)),
+ 1, (Parser target, arg0) => target.skipTypeArgumentList(arg0)),
'skipTypeName_1': new MethodTrampoline(
- 1, (Parser target, arg0) => target._skipTypeName(arg0)),
+ 1, (Parser target, arg0) => target.skipTypeName(arg0)),
'skipTypeParameterList_1': new MethodTrampoline(
1, (Parser target, arg0) => target._skipTypeParameterList(arg0)),
'tokenMatches_2': new MethodTrampoline(
@@ -432,10 +430,6 @@
(Parser target, arg0, arg1) => target._tokenMatchesKeyword(arg0, arg1)),
'tokenMatchesString_2': new MethodTrampoline(
2, (Parser target, arg0, arg1) => target._tokenMatchesString(arg0, arg1)),
- 'translateCharacter_3': new MethodTrampoline(
- 3,
- (Parser target, arg0, arg1, arg2) =>
- target._translateCharacter(arg0, arg1, arg2)),
'unlockErrorListener_0':
new MethodTrampoline(0, (Parser target) => target._unlockErrorListener()),
'validateFormalParameterList_1': new MethodTrampoline(
@@ -475,8 +469,7 @@
};
Object invokeParserMethodImpl(
- Parser parser, String methodName, List<Object> objects, Token tokenStream) {
- parser.currentToken = tokenStream;
+ Parser parser, String methodName, List<Object> objects) {
MethodTrampoline method =
methodTable_Parser['${methodName}_${objects.length}'];
if (method == null) {
@@ -681,6 +674,12 @@
bool _enableAssertInitializer = false;
/**
+ * A flag indicating whether the parser is to parse the non-nullable modifier
+ * in type names.
+ */
+ bool _enableNnbd = false;
+
+ /**
* A flag indicating whether the parser is to parse the async support.
*/
bool _parseAsync = true;
@@ -741,6 +740,11 @@
Parser(this._source, this._errorListener);
/**
+ * Return the current token.
+ */
+ Token get currentToken => _currentToken;
+
+ /**
* Set the token with which the parse is to begin to the given [token].
*/
void set currentToken(Token token) {
@@ -762,6 +766,20 @@
}
/**
+ * Return `true` if the parser is to parse the non-nullable modifier in type
+ * names.
+ */
+ bool get enableNnbd => _enableNnbd;
+
+ /**
+ * Set whether the parser is to parse the non-nullable modifier in type names
+ * to match the given [enable] flag.
+ */
+ void set enableNnbd(bool enable) {
+ _enableNnbd = enable;
+ }
+
+ /**
* Return `true` if the current token is the first token of a return type that
* is followed by an identifier, possibly followed by a list of type
* parameters, followed by a left-parenthesis. This is used by
@@ -769,7 +787,7 @@
*/
@deprecated
bool get hasReturnTypeInTypeAlias {
- Token next = _skipReturnType(_currentToken);
+ Token next = skipReturnType(_currentToken);
if (next == null) {
return false;
}
@@ -797,6 +815,59 @@
}
/**
+ * Return the content of a string with the given literal representation. The
+ * [lexeme] is the literal representation of the string. The flag [isFirst] is
+ * `true` if this is the first token in a string literal. The flag [isLast] is
+ * `true` if this is the last token in a string literal.
+ */
+ String computeStringValue(String lexeme, bool isFirst, bool isLast) {
+ StringLexemeHelper helper = new StringLexemeHelper(lexeme, isFirst, isLast);
+ int start = helper.start;
+ int end = helper.end;
+ bool stringEndsAfterStart = end >= start;
+ assert(stringEndsAfterStart);
+ if (!stringEndsAfterStart) {
+ AnalysisEngine.instance.logger.logError(
+ "Internal error: computeStringValue($lexeme, $isFirst, $isLast)");
+ return "";
+ }
+ if (helper.isRaw) {
+ return lexeme.substring(start, end);
+ }
+ StringBuffer buffer = new StringBuffer();
+ int index = start;
+ while (index < end) {
+ index = _translateCharacter(buffer, lexeme, index);
+ }
+ return buffer.toString();
+ }
+
+ /**
+ * Return a synthetic identifier.
+ */
+ SimpleIdentifier createSyntheticIdentifier({bool isDeclaration: false}) {
+ Token syntheticToken;
+ if (_currentToken.type == TokenType.KEYWORD) {
+ // Consider current keyword token as an identifier.
+ // It is not always true, e.g. "^is T" where "^" is place the place for
+ // synthetic identifier. By creating SyntheticStringToken we can
+ // distinguish a real identifier from synthetic. In the code completion
+ // behavior will depend on a cursor position - before or on "is".
+ syntheticToken = _injectToken(new SyntheticStringToken(
+ TokenType.IDENTIFIER, _currentToken.lexeme, _currentToken.offset));
+ } else {
+ syntheticToken = _createSyntheticToken(TokenType.IDENTIFIER);
+ }
+ return new SimpleIdentifier(syntheticToken, isDeclaration: isDeclaration);
+ }
+
+ /**
+ * Return a synthetic string literal.
+ */
+ SimpleStringLiteral createSyntheticStringLiteral() =>
+ new SimpleStringLiteral(_createSyntheticToken(TokenType.STRING), "");
+
+ /**
* Advance to the next token in the token stream, making it the new current
* token and return the token that was current before this method was invoked.
*/
@@ -807,6 +878,204 @@
}
/**
+ * Return `true` if the current token appears to be the beginning of a
+ * function declaration.
+ */
+ bool isFunctionDeclaration() {
+ Keyword keyword = _currentToken.keyword;
+ if (keyword == Keyword.VOID) {
+ return true;
+ }
+ Token afterReturnType = skipTypeName(_currentToken);
+ if (afterReturnType == null) {
+ // There was no return type, but it is optional, so go back to where we
+ // started.
+ afterReturnType = _currentToken;
+ }
+ Token afterIdentifier = skipSimpleIdentifier(afterReturnType);
+ if (afterIdentifier == null) {
+ // It's possible that we parsed the function name as if it were a type
+ // name, so see whether it makes sense if we assume that there is no type.
+ afterIdentifier = skipSimpleIdentifier(_currentToken);
+ }
+ if (afterIdentifier == null) {
+ return false;
+ }
+ if (isFunctionExpression(afterIdentifier)) {
+ return true;
+ }
+ // It's possible that we have found a getter. While this isn't valid at this
+ // point we test for it in order to recover better.
+ if (keyword == Keyword.GET) {
+ Token afterName = skipSimpleIdentifier(_currentToken.next);
+ if (afterName == null) {
+ return false;
+ }
+ TokenType type = afterName.type;
+ return type == TokenType.FUNCTION || type == TokenType.OPEN_CURLY_BRACKET;
+ } else if (_tokenMatchesKeyword(afterReturnType, Keyword.GET)) {
+ Token afterName = skipSimpleIdentifier(afterReturnType.next);
+ if (afterName == null) {
+ return false;
+ }
+ TokenType type = afterName.type;
+ return type == TokenType.FUNCTION || type == TokenType.OPEN_CURLY_BRACKET;
+ }
+ return false;
+ }
+
+ /**
+ * Return `true` if the given [token] appears to be the beginning of a
+ * function expression.
+ */
+ bool isFunctionExpression(Token token) {
+ // Function expressions aren't allowed in initializer lists.
+ if (_inInitializer) {
+ return false;
+ }
+ Token afterTypeParameters = _skipTypeParameterList(token);
+ if (afterTypeParameters == null) {
+ afterTypeParameters = token;
+ }
+ Token afterParameters = _skipFormalParameterList(afterTypeParameters);
+ if (afterParameters == null) {
+ return false;
+ }
+ if (afterParameters.matchesAny(
+ const <TokenType>[TokenType.OPEN_CURLY_BRACKET, TokenType.FUNCTION])) {
+ return true;
+ }
+ String lexeme = afterParameters.lexeme;
+ return lexeme == ASYNC || lexeme == SYNC;
+ }
+
+ /**
+ * Return `true` if the current token is the first token in an initialized
+ * variable declaration rather than an expression. This method assumes that we
+ * have already skipped past any metadata that might be associated with the
+ * declaration.
+ *
+ * initializedVariableDeclaration ::=
+ * declaredIdentifier ('=' expression)? (',' initializedIdentifier)*
+ *
+ * declaredIdentifier ::=
+ * metadata finalConstVarOrType identifier
+ *
+ * finalConstVarOrType ::=
+ * 'final' type?
+ * | 'const' type?
+ * | 'var'
+ * | type
+ *
+ * type ::=
+ * qualified typeArguments?
+ *
+ * initializedIdentifier ::=
+ * identifier ('=' expression)?
+ */
+ bool isInitializedVariableDeclaration() {
+ Keyword keyword = _currentToken.keyword;
+ if (keyword == Keyword.FINAL || keyword == Keyword.VAR) {
+ // An expression cannot start with a keyword other than 'const',
+ // 'rethrow', or 'throw'.
+ return true;
+ }
+ if (keyword == Keyword.CONST) {
+ // Look to see whether we might be at the start of a list or map literal,
+ // otherwise this should be the start of a variable declaration.
+ return !_peek().matchesAny(const <TokenType>[
+ TokenType.LT,
+ TokenType.OPEN_CURLY_BRACKET,
+ TokenType.OPEN_SQUARE_BRACKET,
+ TokenType.INDEX
+ ]);
+ }
+ bool allowAdditionalTokens = true;
+ // We know that we have an identifier, and need to see whether it might be
+ // a type name.
+ if (_currentToken.type != TokenType.IDENTIFIER) {
+ allowAdditionalTokens = false;
+ }
+ Token token = skipTypeName(_currentToken);
+ if (token == null) {
+ // There was no type name, so this can't be a declaration.
+ return false;
+ }
+ if (token.type != TokenType.IDENTIFIER) {
+ allowAdditionalTokens = false;
+ }
+ token = skipSimpleIdentifier(token);
+ if (token == null) {
+ return false;
+ }
+ TokenType type = token.type;
+ // Usual cases in valid code:
+ // String v = '';
+ // String v, v2;
+ // String v;
+ // for (String item in items) {}
+ if (type == TokenType.EQ ||
+ type == TokenType.COMMA ||
+ type == TokenType.SEMICOLON ||
+ token.keyword == Keyword.IN) {
+ return true;
+ }
+ // It is OK to parse as a variable declaration in these cases:
+ // String v }
+ // String v if (true) print('OK');
+ // String v { print(42); }
+ // ...but not in these cases:
+ // get getterName {
+ // String get getterName
+ if (allowAdditionalTokens) {
+ if (type == TokenType.CLOSE_CURLY_BRACKET ||
+ type == TokenType.KEYWORD ||
+ type == TokenType.IDENTIFIER ||
+ type == TokenType.OPEN_CURLY_BRACKET) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Return `true` if the current token appears to be the beginning of a switch
+ * member.
+ */
+ bool isSwitchMember() {
+ Token token = _currentToken;
+ while (_tokenMatches(token, TokenType.IDENTIFIER) &&
+ _tokenMatches(token.next, TokenType.COLON)) {
+ token = token.next.next;
+ }
+ Keyword keyword = token.keyword;
+ return keyword == Keyword.CASE || keyword == Keyword.DEFAULT;
+ }
+
+ /**
+ * Parse an additive expression. Return the additive expression that was
+ * parsed.
+ *
+ * additiveExpression ::=
+ * multiplicativeExpression (additiveOperator multiplicativeExpression)*
+ * | 'super' (additiveOperator multiplicativeExpression)+
+ */
+ Expression parseAdditiveExpression() {
+ Expression expression;
+ if (_currentToken.keyword == Keyword.SUPER &&
+ _currentToken.next.type.isAdditiveOperator) {
+ expression = new SuperExpression(getAndAdvance());
+ } else {
+ expression = parseMultiplicativeExpression();
+ }
+ while (_currentToken.type.isAdditiveOperator) {
+ expression = new BinaryExpression(
+ expression, getAndAdvance(), parseMultiplicativeExpression());
+ }
+ return expression;
+ }
+
+ /**
* Parse an annotation. Return the annotation that was parsed.
*
* This method assumes that the current token matches [TokenType.AT].
@@ -915,6 +1184,86 @@
}
/**
+ * Parse an assert statement. Return the assert statement.
+ *
+ * This method assumes that the current token matches `Keyword.ASSERT`.
+ *
+ * assertStatement ::=
+ * 'assert' '(' expression [',' expression] ')' ';'
+ */
+ AssertStatement parseAssertStatement() {
+ Token keyword = getAndAdvance();
+ Token leftParen = _expect(TokenType.OPEN_PAREN);
+ Expression expression = parseExpression2();
+ Token comma;
+ Expression message;
+ if (_matches(TokenType.COMMA)) {
+ comma = getAndAdvance();
+ message = parseExpression2();
+ }
+ Token rightParen = _expect(TokenType.CLOSE_PAREN);
+ Token semicolon = _expect(TokenType.SEMICOLON);
+ return new AssertStatement(
+ keyword, leftParen, expression, comma, message, rightParen, semicolon);
+ }
+
+ /**
+ * Parse an assignable expression. The [primaryAllowed] is `true` if the
+ * expression is allowed to be a primary without any assignable selector.
+ * Return the assignable expression that was parsed.
+ *
+ * assignableExpression ::=
+ * primary (arguments* assignableSelector)+
+ * | 'super' unconditionalAssignableSelector
+ * | identifier
+ */
+ Expression parseAssignableExpression(bool primaryAllowed) {
+ if (_matchesKeyword(Keyword.SUPER)) {
+ return _parseAssignableSelector(
+ new SuperExpression(getAndAdvance()), false,
+ allowConditional: false);
+ }
+ return _parseAssignableExpressionNotStartingWithSuper(primaryAllowed);
+ }
+
+ /**
+ * Parse a await expression. Return the await expression that was parsed.
+ *
+ * This method assumes that the current token matches `_AWAIT`.
+ *
+ * awaitExpression ::=
+ * 'await' unaryExpression
+ */
+ AwaitExpression parseAwaitExpression() {
+ Token awaitToken = getAndAdvance();
+ Expression expression = parseUnaryExpression();
+ return new AwaitExpression(awaitToken, expression);
+ }
+
+ /**
+ * Parse a bitwise and expression. Return the bitwise and expression that was
+ * parsed.
+ *
+ * bitwiseAndExpression ::=
+ * shiftExpression ('&' shiftExpression)*
+ * | 'super' ('&' shiftExpression)+
+ */
+ Expression parseBitwiseAndExpression() {
+ Expression expression;
+ if (_currentToken.keyword == Keyword.SUPER &&
+ _currentToken.next.type == TokenType.AMPERSAND) {
+ expression = new SuperExpression(getAndAdvance());
+ } else {
+ expression = parseShiftExpression();
+ }
+ while (_currentToken.type == TokenType.AMPERSAND) {
+ expression = new BinaryExpression(
+ expression, getAndAdvance(), parseShiftExpression());
+ }
+ return expression;
+ }
+
+ /**
* Parse a bitwise or expression. Return the bitwise or expression that was
* parsed.
*
@@ -928,11 +1277,34 @@
_currentToken.next.type == TokenType.BAR) {
expression = new SuperExpression(getAndAdvance());
} else {
- expression = _parseBitwiseXorExpression();
+ expression = parseBitwiseXorExpression();
}
while (_currentToken.type == TokenType.BAR) {
expression = new BinaryExpression(
- expression, getAndAdvance(), _parseBitwiseXorExpression());
+ expression, getAndAdvance(), parseBitwiseXorExpression());
+ }
+ return expression;
+ }
+
+ /**
+ * Parse a bitwise exclusive-or expression. Return the bitwise exclusive-or
+ * expression that was parsed.
+ *
+ * bitwiseXorExpression ::=
+ * bitwiseAndExpression ('^' bitwiseAndExpression)*
+ * | 'super' ('^' bitwiseAndExpression)+
+ */
+ Expression parseBitwiseXorExpression() {
+ Expression expression;
+ if (_currentToken.keyword == Keyword.SUPER &&
+ _currentToken.next.type == TokenType.CARET) {
+ expression = new SuperExpression(getAndAdvance());
+ } else {
+ expression = parseBitwiseAndExpression();
+ }
+ while (_currentToken.type == TokenType.CARET) {
+ expression = new BinaryExpression(
+ expression, getAndAdvance(), parseBitwiseAndExpression());
}
return expression;
}
@@ -976,6 +1348,259 @@
}
/**
+ * Parse a break statement. Return the break statement that was parsed.
+ *
+ * This method assumes that the current token matches `Keyword.BREAK`.
+ *
+ * breakStatement ::=
+ * 'break' identifier? ';'
+ */
+ Statement parseBreakStatement() {
+ Token breakKeyword = getAndAdvance();
+ SimpleIdentifier label = null;
+ if (_matchesIdentifier()) {
+ label = _parseSimpleIdentifierUnchecked();
+ }
+ if (!_inLoop && !_inSwitch && label == null) {
+ _reportErrorForToken(ParserErrorCode.BREAK_OUTSIDE_OF_LOOP, breakKeyword);
+ }
+ Token semicolon = _expect(TokenType.SEMICOLON);
+ return new BreakStatement(breakKeyword, label, semicolon);
+ }
+
+ /**
+ * Parse a cascade section. Return the expression representing the cascaded
+ * method invocation.
+ *
+ * This method assumes that the current token matches
+ * `TokenType.PERIOD_PERIOD`.
+ *
+ * cascadeSection ::=
+ * '..' (cascadeSelector typeArguments? arguments*)
+ * (assignableSelector typeArguments? arguments*)* cascadeAssignment?
+ *
+ * cascadeSelector ::=
+ * '[' expression ']'
+ * | identifier
+ *
+ * cascadeAssignment ::=
+ * assignmentOperator expressionWithoutCascade
+ */
+ Expression parseCascadeSection() {
+ Token period = getAndAdvance();
+ Expression expression = null;
+ SimpleIdentifier functionName = null;
+ if (_matchesIdentifier()) {
+ functionName = _parseSimpleIdentifierUnchecked();
+ } else if (_currentToken.type == TokenType.OPEN_SQUARE_BRACKET) {
+ Token leftBracket = getAndAdvance();
+ bool wasInInitializer = _inInitializer;
+ _inInitializer = false;
+ try {
+ Expression index = parseExpression2();
+ Token rightBracket = _expect(TokenType.CLOSE_SQUARE_BRACKET);
+ expression = new IndexExpression.forCascade(
+ period, leftBracket, index, rightBracket);
+ period = null;
+ } finally {
+ _inInitializer = wasInInitializer;
+ }
+ } else {
+ _reportErrorForToken(ParserErrorCode.MISSING_IDENTIFIER, _currentToken,
+ [_currentToken.lexeme]);
+ functionName = createSyntheticIdentifier();
+ }
+ assert((expression == null && functionName != null) ||
+ (expression != null && functionName == null));
+ if (_isLikelyArgumentList()) {
+ do {
+ TypeArgumentList typeArguments = _parseOptionalTypeArguments();
+ if (functionName != null) {
+ expression = new MethodInvocation(expression, period, functionName,
+ typeArguments, parseArgumentList());
+ period = null;
+ functionName = null;
+ } else if (expression == null) {
+ // It should not be possible to get here.
+ expression = new MethodInvocation(expression, period,
+ createSyntheticIdentifier(), typeArguments, parseArgumentList());
+ } else {
+ expression = new FunctionExpressionInvocation(
+ expression, typeArguments, parseArgumentList());
+ }
+ } while (_isLikelyArgumentList());
+ } else if (functionName != null) {
+ expression = new PropertyAccess(expression, period, functionName);
+ period = null;
+ }
+ assert(expression != null);
+ bool progress = true;
+ while (progress) {
+ progress = false;
+ Expression selector = _parseAssignableSelector(expression, true);
+ if (!identical(selector, expression)) {
+ expression = selector;
+ progress = true;
+ while (_isLikelyArgumentList()) {
+ TypeArgumentList typeArguments = _parseOptionalTypeArguments();
+ Expression currentExpression = expression;
+ if (currentExpression is PropertyAccess) {
+ expression = new MethodInvocation(
+ currentExpression.target,
+ currentExpression.operator,
+ currentExpression.propertyName,
+ typeArguments,
+ parseArgumentList());
+ } else {
+ expression = new FunctionExpressionInvocation(
+ expression, typeArguments, parseArgumentList());
+ }
+ }
+ }
+ }
+ if (_currentToken.type.isAssignmentOperator) {
+ Token operator = getAndAdvance();
+ _ensureAssignable(expression);
+ expression = new AssignmentExpression(
+ expression, operator, parseExpressionWithoutCascade());
+ }
+ return expression;
+ }
+
+ /**
+ * Parse a class declaration. The [commentAndMetadata] is the metadata to be
+ * associated with the member. The [abstractKeyword] is the token for the
+ * keyword 'abstract', or `null` if the keyword was not given. Return the
+ * class declaration that was parsed.
+ *
+ * This method assumes that the current token matches `Keyword.CLASS`.
+ *
+ * classDeclaration ::=
+ * metadata 'abstract'? 'class' name typeParameterList? (extendsClause withClause?)? implementsClause? '{' classMembers '}' |
+ * metadata 'abstract'? 'class' mixinApplicationClass
+ */
+ CompilationUnitMember parseClassDeclaration(
+ CommentAndMetadata commentAndMetadata, Token abstractKeyword) {
+ //
+ // Parse the name and type parameters.
+ //
+ Token keyword = getAndAdvance();
+ SimpleIdentifier name = parseSimpleIdentifier(isDeclaration: true);
+ String className = name.name;
+ TypeParameterList typeParameters = null;
+ TokenType type = _currentToken.type;
+ if (type == TokenType.LT) {
+ typeParameters = parseTypeParameterList();
+ type = _currentToken.type;
+ }
+ //
+ // Check to see whether this might be a class type alias rather than a class
+ // declaration.
+ //
+ if (type == TokenType.EQ) {
+ return _parseClassTypeAliasAfterName(
+ commentAndMetadata, abstractKeyword, keyword, name, typeParameters);
+ }
+ //
+ // Parse the clauses. The parser accepts clauses in any order, but will
+ // generate errors if they are not in the order required by the
+ // specification.
+ //
+ ExtendsClause extendsClause = null;
+ WithClause withClause = null;
+ ImplementsClause implementsClause = null;
+ bool foundClause = true;
+ while (foundClause) {
+ Keyword keyword = _currentToken.keyword;
+ if (keyword == Keyword.EXTENDS) {
+ if (extendsClause == null) {
+ extendsClause = parseExtendsClause();
+ if (withClause != null) {
+ _reportErrorForToken(
+ ParserErrorCode.WITH_BEFORE_EXTENDS, withClause.withKeyword);
+ } else if (implementsClause != null) {
+ _reportErrorForToken(ParserErrorCode.IMPLEMENTS_BEFORE_EXTENDS,
+ implementsClause.implementsKeyword);
+ }
+ } else {
+ _reportErrorForToken(ParserErrorCode.MULTIPLE_EXTENDS_CLAUSES,
+ extendsClause.extendsKeyword);
+ parseExtendsClause();
+ }
+ } else if (keyword == Keyword.WITH) {
+ if (withClause == null) {
+ withClause = parseWithClause();
+ if (implementsClause != null) {
+ _reportErrorForToken(ParserErrorCode.IMPLEMENTS_BEFORE_WITH,
+ implementsClause.implementsKeyword);
+ }
+ } else {
+ _reportErrorForToken(
+ ParserErrorCode.MULTIPLE_WITH_CLAUSES, withClause.withKeyword);
+ parseWithClause();
+ // TODO(brianwilkerson) Should we merge the list of applied mixins
+ // into a single list?
+ }
+ } else if (keyword == Keyword.IMPLEMENTS) {
+ if (implementsClause == null) {
+ implementsClause = parseImplementsClause();
+ } else {
+ _reportErrorForToken(ParserErrorCode.MULTIPLE_IMPLEMENTS_CLAUSES,
+ implementsClause.implementsKeyword);
+ parseImplementsClause();
+ // TODO(brianwilkerson) Should we merge the list of implemented
+ // classes into a single list?
+ }
+ } else {
+ foundClause = false;
+ }
+ }
+ if (withClause != null && extendsClause == null) {
+ _reportErrorForToken(
+ ParserErrorCode.WITH_WITHOUT_EXTENDS, withClause.withKeyword);
+ }
+ //
+ // Look for and skip over the extra-lingual 'native' specification.
+ //
+ NativeClause nativeClause = null;
+ if (_matchesString(_NATIVE) && _tokenMatches(_peek(), TokenType.STRING)) {
+ nativeClause = _parseNativeClause();
+ }
+ //
+ // Parse the body of the class.
+ //
+ Token leftBracket = null;
+ List<ClassMember> members = null;
+ Token rightBracket = null;
+ if (_matches(TokenType.OPEN_CURLY_BRACKET)) {
+ leftBracket = getAndAdvance();
+ members = _parseClassMembers(className, _getEndToken(leftBracket));
+ rightBracket = _expect(TokenType.CLOSE_CURLY_BRACKET);
+ } else {
+ // Recovery: Check for an unmatched closing curly bracket and parse
+ // members until it is reached.
+ leftBracket = _createSyntheticToken(TokenType.OPEN_CURLY_BRACKET);
+ rightBracket = _createSyntheticToken(TokenType.CLOSE_CURLY_BRACKET);
+ _reportErrorForCurrentToken(ParserErrorCode.MISSING_CLASS_BODY);
+ }
+ ClassDeclaration classDeclaration = new ClassDeclaration(
+ commentAndMetadata.comment,
+ commentAndMetadata.metadata,
+ abstractKeyword,
+ keyword,
+ name,
+ typeParameters,
+ extendsClause,
+ withClause,
+ implementsClause,
+ leftBracket,
+ members,
+ rightBracket);
+ classDeclaration.nativeClause = nativeClause;
+ return classDeclaration;
+ }
+
+ /**
* Parse a class member. The [className] is the name of the class containing
* the member being parsed. Return the class member that was parsed, or `null`
* if what was found was not a valid class member.
@@ -985,7 +1610,7 @@
* | methodSignature functionBody
*/
ClassMember parseClassMember(String className) {
- CommentAndMetadata commentAndMetadata = _parseCommentAndMetadata();
+ CommentAndMetadata commentAndMetadata = parseCommentAndMetadata();
Modifiers modifiers = _parseModifiers();
Keyword keyword = _currentToken.keyword;
if (keyword == Keyword.VOID) {
@@ -1043,7 +1668,7 @@
// 'operator' keyword.
//
_validateModifiersForOperator(modifiers);
- return _parseOperator(
+ return parseOperator(
commentAndMetadata, modifiers.externalKeyword, returnType);
}
_reportErrorForToken(
@@ -1073,20 +1698,20 @@
_reportErrorForCurrentToken(ParserErrorCode.CLASS_IN_CLASS);
// TODO(brianwilkerson) We don't currently have any way to capture the
// class that was parsed.
- _parseClassDeclaration(commentAndMetadata, null);
+ parseClassDeclaration(commentAndMetadata, null);
return null;
} else if (_matchesKeyword(Keyword.ABSTRACT) &&
_tokenMatchesKeyword(_peek(), Keyword.CLASS)) {
_reportErrorForToken(ParserErrorCode.CLASS_IN_CLASS, _peek());
// TODO(brianwilkerson) We don't currently have any way to capture the
// class that was parsed.
- _parseClassDeclaration(commentAndMetadata, getAndAdvance());
+ parseClassDeclaration(commentAndMetadata, getAndAdvance());
return null;
} else if (_matchesKeyword(Keyword.ENUM)) {
_reportErrorForToken(ParserErrorCode.ENUM_IN_CLASS, _peek());
// TODO(brianwilkerson) We don't currently have any way to capture the
// enum that was parsed.
- _parseEnumDeclaration(commentAndMetadata);
+ parseEnumDeclaration(commentAndMetadata);
return null;
} else if (_isOperator(_currentToken)) {
//
@@ -1094,7 +1719,7 @@
// 'operator' keyword.
//
_validateModifiersForOperator(modifiers);
- return _parseOperator(
+ return parseOperator(
commentAndMetadata, modifiers.externalKeyword, null);
}
Token keyword = modifiers.varKeyword;
@@ -1110,7 +1735,7 @@
//
_reportErrorForCurrentToken(ParserErrorCode.MISSING_IDENTIFIER);
VariableDeclaration variable =
- new VariableDeclaration(_createSyntheticIdentifier(), null, null);
+ new VariableDeclaration(createSyntheticIdentifier(), null, null);
List<VariableDeclaration> variables = <VariableDeclaration>[variable];
return new FieldDeclaration(
commentAndMetadata.comment,
@@ -1137,7 +1762,7 @@
null,
null,
null,
- _createSyntheticIdentifier(isDeclaration: true),
+ createSyntheticIdentifier(isDeclaration: true),
null,
new FormalParameterList(
null, <FormalParameter>[], null, null, null),
@@ -1245,7 +1870,7 @@
// 'operator' keyword.
//
_validateModifiersForOperator(modifiers);
- return _parseOperator(
+ return parseOperator(
commentAndMetadata, modifiers.externalKeyword, type);
}
//
@@ -1310,6 +1935,32 @@
}
/**
+ * Parse a class type alias. The [commentAndMetadata] is the metadata to be
+ * associated with the member. The [abstractKeyword] is the token representing
+ * the 'abstract' keyword. The [classKeyword] is the token representing the
+ * 'class' keyword. Return the class type alias that was parsed.
+ *
+ * This method assumes that the current token matches an identifier.
+ *
+ * classTypeAlias ::=
+ * identifier typeParameters? '=' 'abstract'? mixinApplication
+ *
+ * mixinApplication ::=
+ * type withClause implementsClause? ';'
+ */
+ ClassTypeAlias parseClassTypeAlias(CommentAndMetadata commentAndMetadata,
+ Token abstractKeyword, Token classKeyword) {
+ SimpleIdentifier className =
+ _parseSimpleIdentifierUnchecked(isDeclaration: true);
+ TypeParameterList typeParameters = null;
+ if (_matches(TokenType.LT)) {
+ typeParameters = parseTypeParameterList();
+ }
+ return _parseClassTypeAliasAfterName(commentAndMetadata, abstractKeyword,
+ classKeyword, className, typeParameters);
+ }
+
+ /**
* Parse a single combinator. Return the combinator that was parsed, or `null`
* if no combinator is found.
*
@@ -1327,6 +1978,162 @@
}
/**
+ * Parse a list of combinators in a directive. Return the combinators that
+ * were parsed, or `null` if there are no combinators.
+ *
+ * combinator ::=
+ * 'show' identifier (',' identifier)*
+ * | 'hide' identifier (',' identifier)*
+ */
+ List<Combinator> parseCombinators() {
+ List<Combinator> combinators = null;
+ while (true) {
+ Combinator combinator = parseCombinator();
+ if (combinator == null) {
+ break;
+ }
+ combinators ??= <Combinator>[];
+ combinators.add(combinator);
+ }
+ return combinators;
+ }
+
+ /**
+ * Parse the documentation comment and metadata preceding a declaration. This
+ * method allows any number of documentation comments to occur before, after
+ * or between the metadata, but only returns the last (right-most)
+ * documentation comment that is found. Return the documentation comment and
+ * metadata that were parsed.
+ *
+ * metadata ::=
+ * annotation*
+ */
+ CommentAndMetadata parseCommentAndMetadata() {
+ // TODO(brianwilkerson) Consider making the creation of documentation
+ // comments be lazy.
+ List<DocumentationCommentToken> tokens = parseDocumentationCommentTokens();
+ List<Annotation> metadata = null;
+ while (_matches(TokenType.AT)) {
+ metadata ??= <Annotation>[];
+ metadata.add(parseAnnotation());
+ List<DocumentationCommentToken> optionalTokens =
+ parseDocumentationCommentTokens();
+ if (optionalTokens != null) {
+ tokens = optionalTokens;
+ }
+ }
+ return new CommentAndMetadata(parseDocumentationComment(tokens), metadata);
+ }
+
+ /**
+ * Parse a comment reference from the source between square brackets. The
+ * [referenceSource] is the source occurring between the square brackets
+ * within a documentation comment. The [sourceOffset] is the offset of the
+ * first character of the reference source. Return the comment reference that
+ * was parsed, or `null` if no reference could be found.
+ *
+ * commentReference ::=
+ * 'new'? prefixedIdentifier
+ */
+ CommentReference parseCommentReference(
+ String referenceSource, int sourceOffset) {
+ // TODO(brianwilkerson) The errors are not getting the right offset/length
+ // and are being duplicated.
+ try {
+ BooleanErrorListener listener = new BooleanErrorListener();
+ Scanner scanner = new Scanner(
+ null, new SubSequenceReader(referenceSource, sourceOffset), listener);
+ scanner.setSourceStart(1, 1);
+ Token firstToken = scanner.tokenize();
+ if (listener.errorReported) {
+ return null;
+ }
+ if (firstToken.type == TokenType.EOF) {
+ Token syntheticToken =
+ new SyntheticStringToken(TokenType.IDENTIFIER, "", sourceOffset);
+ syntheticToken.setNext(firstToken);
+ return new CommentReference(null, new SimpleIdentifier(syntheticToken));
+ }
+ Token newKeyword = null;
+ if (_tokenMatchesKeyword(firstToken, Keyword.NEW)) {
+ newKeyword = firstToken;
+ firstToken = firstToken.next;
+ }
+ if (firstToken.isUserDefinableOperator) {
+ if (firstToken.next.type != TokenType.EOF) {
+ return null;
+ }
+ Identifier identifier = new SimpleIdentifier(firstToken);
+ return new CommentReference(null, identifier);
+ } else if (_tokenMatchesKeyword(firstToken, Keyword.OPERATOR)) {
+ Token secondToken = firstToken.next;
+ if (secondToken.isUserDefinableOperator) {
+ if (secondToken.next.type != TokenType.EOF) {
+ return null;
+ }
+ Identifier identifier = new SimpleIdentifier(secondToken);
+ return new CommentReference(null, identifier);
+ }
+ return null;
+ } else if (_tokenMatchesIdentifier(firstToken)) {
+ Token secondToken = firstToken.next;
+ Token thirdToken = secondToken.next;
+ Token nextToken;
+ Identifier identifier;
+ if (_tokenMatches(secondToken, TokenType.PERIOD)) {
+ if (thirdToken.isUserDefinableOperator) {
+ identifier = new PrefixedIdentifier(
+ new SimpleIdentifier(firstToken),
+ secondToken,
+ new SimpleIdentifier(thirdToken));
+ nextToken = thirdToken.next;
+ } else if (_tokenMatchesKeyword(thirdToken, Keyword.OPERATOR)) {
+ Token fourthToken = thirdToken.next;
+ if (fourthToken.isUserDefinableOperator) {
+ identifier = new PrefixedIdentifier(
+ new SimpleIdentifier(firstToken),
+ secondToken,
+ new SimpleIdentifier(fourthToken));
+ nextToken = fourthToken.next;
+ } else {
+ return null;
+ }
+ } else if (_tokenMatchesIdentifier(thirdToken)) {
+ identifier = new PrefixedIdentifier(
+ new SimpleIdentifier(firstToken),
+ secondToken,
+ new SimpleIdentifier(thirdToken));
+ nextToken = thirdToken.next;
+ }
+ } else {
+ identifier = new SimpleIdentifier(firstToken);
+ nextToken = firstToken.next;
+ }
+ if (nextToken.type != TokenType.EOF) {
+ return null;
+ }
+ return new CommentReference(newKeyword, identifier);
+ } else {
+ Keyword keyword = firstToken.keyword;
+ if (keyword == Keyword.THIS ||
+ keyword == Keyword.NULL ||
+ keyword == Keyword.TRUE ||
+ keyword == Keyword.FALSE) {
+ // TODO(brianwilkerson) If we want to support this we will need to
+ // extend the definition of CommentReference to take an expression
+ // rather than an identifier. For now we just ignore it to reduce the
+ // number of errors produced, but that's probably not a valid long term
+ // approach.
+ return null;
+ }
+ }
+ } catch (exception) {
+ // Ignored because we assume that it wasn't a real comment reference.
+ }
+ return null;
+ }
+
+ /**
* Parse a compilation unit, starting with the given [token]. Return the
* compilation unit that was parsed.
*/
@@ -1372,7 +2179,7 @@
Token memberStart = _currentToken;
TokenType type = _currentToken.type;
while (type != TokenType.EOF) {
- CommentAndMetadata commentAndMetadata = _parseCommentAndMetadata();
+ CommentAndMetadata commentAndMetadata = parseCommentAndMetadata();
Keyword keyword = _currentToken.keyword;
TokenType nextType = _currentToken.next.type;
if ((keyword == Keyword.IMPORT ||
@@ -1439,7 +2246,7 @@
_advance();
} else {
CompilationUnitMember member =
- _parseCompilationUnitMember(commentAndMetadata);
+ parseCompilationUnitMember(commentAndMetadata);
if (member != null) {
declarations.add(member);
}
@@ -1492,6 +2299,215 @@
}
/**
+ * Parse a compilation unit member. The [commentAndMetadata] is the metadata
+ * to be associated with the member. Return the compilation unit member that
+ * was parsed, or `null` if what was parsed could not be represented as a
+ * compilation unit member.
+ *
+ * compilationUnitMember ::=
+ * classDefinition
+ * | functionTypeAlias
+ * | external functionSignature
+ * | external getterSignature
+ * | external setterSignature
+ * | functionSignature functionBody
+ * | returnType? getOrSet identifier formalParameterList functionBody
+ * | (final | const) type? staticFinalDeclarationList ';'
+ * | variableDeclaration ';'
+ */
+ CompilationUnitMember parseCompilationUnitMember(
+ CommentAndMetadata commentAndMetadata) {
+ Modifiers modifiers = _parseModifiers();
+ Keyword keyword = _currentToken.keyword;
+ if (keyword == Keyword.CLASS) {
+ return parseClassDeclaration(
+ commentAndMetadata, _validateModifiersForClass(modifiers));
+ }
+ Token next = _peek();
+ TokenType nextType = next.type;
+ if (keyword == Keyword.TYPEDEF &&
+ nextType != TokenType.PERIOD &&
+ nextType != TokenType.LT &&
+ nextType != TokenType.OPEN_PAREN) {
+ _validateModifiersForTypedef(modifiers);
+ return _parseTypeAlias(commentAndMetadata);
+ } else if (keyword == Keyword.ENUM) {
+ _validateModifiersForEnum(modifiers);
+ return parseEnumDeclaration(commentAndMetadata);
+ } else if (keyword == Keyword.VOID) {
+ TypeName returnType =
+ new TypeName(new SimpleIdentifier(getAndAdvance()), null);
+ keyword = _currentToken.keyword;
+ next = _peek();
+ if ((keyword == Keyword.GET || keyword == Keyword.SET) &&
+ _tokenMatchesIdentifier(next)) {
+ _validateModifiersForTopLevelFunction(modifiers);
+ return _parseFunctionDeclaration(
+ commentAndMetadata, modifiers.externalKeyword, returnType);
+ } else if (keyword == Keyword.OPERATOR && _isOperator(next)) {
+ _reportErrorForToken(ParserErrorCode.TOP_LEVEL_OPERATOR, _currentToken);
+ return _convertToFunctionDeclaration(_parseOperatorAfterKeyword(
+ commentAndMetadata,
+ modifiers.externalKeyword,
+ returnType,
+ getAndAdvance()));
+ } else if (_matchesIdentifier() &&
+ next.matchesAny(const <TokenType>[
+ TokenType.OPEN_PAREN,
+ TokenType.OPEN_CURLY_BRACKET,
+ TokenType.FUNCTION,
+ TokenType.LT
+ ])) {
+ _validateModifiersForTopLevelFunction(modifiers);
+ return _parseFunctionDeclaration(
+ commentAndMetadata, modifiers.externalKeyword, returnType);
+ } else {
+ //
+ // We have found an error of some kind. Try to recover.
+ //
+ if (_matchesIdentifier()) {
+ if (next.matchesAny(const <TokenType>[
+ TokenType.EQ,
+ TokenType.COMMA,
+ TokenType.SEMICOLON
+ ])) {
+ //
+ // We appear to have a variable declaration with a type of "void".
+ //
+ _reportErrorForNode(ParserErrorCode.VOID_VARIABLE, returnType);
+ return new TopLevelVariableDeclaration(
+ commentAndMetadata.comment,
+ commentAndMetadata.metadata,
+ parseVariableDeclarationListAfterType(null,
+ _validateModifiersForTopLevelVariable(modifiers), null),
+ _expect(TokenType.SEMICOLON));
+ }
+ }
+ _reportErrorForToken(
+ ParserErrorCode.EXPECTED_EXECUTABLE, _currentToken);
+ return null;
+ }
+ } else if ((keyword == Keyword.GET || keyword == Keyword.SET) &&
+ _tokenMatchesIdentifier(next)) {
+ _validateModifiersForTopLevelFunction(modifiers);
+ return _parseFunctionDeclaration(
+ commentAndMetadata, modifiers.externalKeyword, null);
+ } else if (keyword == Keyword.OPERATOR && _isOperator(next)) {
+ _reportErrorForToken(ParserErrorCode.TOP_LEVEL_OPERATOR, _currentToken);
+ return _convertToFunctionDeclaration(_parseOperatorAfterKeyword(
+ commentAndMetadata,
+ modifiers.externalKeyword,
+ null,
+ getAndAdvance()));
+ } else if (!_matchesIdentifier()) {
+ Token keyword = modifiers.varKeyword;
+ if (keyword == null) {
+ keyword = modifiers.finalKeyword;
+ }
+ if (keyword == null) {
+ keyword = modifiers.constKeyword;
+ }
+ if (keyword != null) {
+ //
+ // We appear to have found an incomplete top-level variable declaration.
+ //
+ _reportErrorForCurrentToken(ParserErrorCode.MISSING_IDENTIFIER);
+ VariableDeclaration variable =
+ new VariableDeclaration(createSyntheticIdentifier(), null, null);
+ List<VariableDeclaration> variables = <VariableDeclaration>[variable];
+ return new TopLevelVariableDeclaration(
+ commentAndMetadata.comment,
+ commentAndMetadata.metadata,
+ new VariableDeclarationList(null, null, keyword, null, variables),
+ _expect(TokenType.SEMICOLON));
+ }
+ _reportErrorForToken(ParserErrorCode.EXPECTED_EXECUTABLE, _currentToken);
+ return null;
+ } else if (_isPeekGenericTypeParametersAndOpenParen()) {
+ return _parseFunctionDeclaration(
+ commentAndMetadata, modifiers.externalKeyword, null);
+ } else if (_tokenMatches(next, TokenType.OPEN_PAREN)) {
+ TypeName returnType = _parseOptionalTypeNameComment();
+ _validateModifiersForTopLevelFunction(modifiers);
+ return _parseFunctionDeclaration(
+ commentAndMetadata, modifiers.externalKeyword, returnType);
+ } else if (next.matchesAny(const <TokenType>[
+ TokenType.EQ,
+ TokenType.COMMA,
+ TokenType.SEMICOLON
+ ])) {
+ if (modifiers.constKeyword == null &&
+ modifiers.finalKeyword == null &&
+ modifiers.varKeyword == null) {
+ _reportErrorForCurrentToken(
+ ParserErrorCode.MISSING_CONST_FINAL_VAR_OR_TYPE);
+ }
+ return new TopLevelVariableDeclaration(
+ commentAndMetadata.comment,
+ commentAndMetadata.metadata,
+ parseVariableDeclarationListAfterType(
+ null, _validateModifiersForTopLevelVariable(modifiers), null),
+ _expect(TokenType.SEMICOLON));
+ }
+ TypeName returnType = parseReturnType();
+ keyword = _currentToken.keyword;
+ next = _peek();
+ if ((keyword == Keyword.GET || keyword == Keyword.SET) &&
+ _tokenMatchesIdentifier(next)) {
+ _validateModifiersForTopLevelFunction(modifiers);
+ return _parseFunctionDeclaration(
+ commentAndMetadata, modifiers.externalKeyword, returnType);
+ } else if (keyword == Keyword.OPERATOR && _isOperator(next)) {
+ _reportErrorForToken(ParserErrorCode.TOP_LEVEL_OPERATOR, _currentToken);
+ return _convertToFunctionDeclaration(_parseOperatorAfterKeyword(
+ commentAndMetadata,
+ modifiers.externalKeyword,
+ returnType,
+ getAndAdvance()));
+ } else if (_matches(TokenType.AT)) {
+ return new TopLevelVariableDeclaration(
+ commentAndMetadata.comment,
+ commentAndMetadata.metadata,
+ parseVariableDeclarationListAfterType(null,
+ _validateModifiersForTopLevelVariable(modifiers), returnType),
+ _expect(TokenType.SEMICOLON));
+ } else if (!_matchesIdentifier()) {
+ // TODO(brianwilkerson) Generalize this error. We could also be parsing a
+ // top-level variable at this point.
+ _reportErrorForToken(ParserErrorCode.EXPECTED_EXECUTABLE, _currentToken);
+ Token semicolon;
+ if (_matches(TokenType.SEMICOLON)) {
+ semicolon = getAndAdvance();
+ } else {
+ semicolon = _createSyntheticToken(TokenType.SEMICOLON);
+ }
+ VariableDeclaration variable =
+ new VariableDeclaration(createSyntheticIdentifier(), null, null);
+ List<VariableDeclaration> variables = <VariableDeclaration>[variable];
+ return new TopLevelVariableDeclaration(
+ commentAndMetadata.comment,
+ commentAndMetadata.metadata,
+ new VariableDeclarationList(null, null, null, returnType, variables),
+ semicolon);
+ } else if (next.matchesAny(const <TokenType>[
+ TokenType.OPEN_PAREN,
+ TokenType.FUNCTION,
+ TokenType.OPEN_CURLY_BRACKET,
+ TokenType.LT
+ ])) {
+ _validateModifiersForTopLevelFunction(modifiers);
+ return _parseFunctionDeclaration(
+ commentAndMetadata, modifiers.externalKeyword, returnType);
+ }
+ return new TopLevelVariableDeclaration(
+ commentAndMetadata.comment,
+ commentAndMetadata.metadata,
+ parseVariableDeclarationListAfterType(
+ null, _validateModifiersForTopLevelVariable(modifiers), returnType),
+ _expect(TokenType.SEMICOLON));
+ }
+
+ /**
* Parse a conditional expression. Return the conditional expression that was
* parsed.
*
@@ -1512,6 +2528,64 @@
}
/**
+ * Parse a configuration in either an import or export directive.
+ *
+ * This method assumes that the current token matches `Keyword.IF`.
+ *
+ * configuration ::=
+ * 'if' '(' test ')' uri
+ *
+ * test ::=
+ * dottedName ('==' stringLiteral)?
+ *
+ * dottedName ::=
+ * identifier ('.' identifier)*
+ */
+ Configuration parseConfiguration() {
+ Token ifKeyword = getAndAdvance();
+ Token leftParenthesis = _expect(TokenType.OPEN_PAREN);
+ DottedName name = parseDottedName();
+ Token equalToken = null;
+ StringLiteral value = null;
+ if (_matches(TokenType.EQ_EQ)) {
+ equalToken = getAndAdvance();
+ value = parseStringLiteral();
+ if (value is StringInterpolation) {
+ _reportErrorForNode(
+ ParserErrorCode.INVALID_LITERAL_IN_CONFIGURATION, value);
+ }
+ }
+ Token rightParenthesis = _expect(TokenType.CLOSE_PAREN);
+ StringLiteral libraryUri = _parseUri();
+ return new Configuration(ifKeyword, leftParenthesis, name, equalToken,
+ value, rightParenthesis, libraryUri);
+ }
+
+ /**
+ * Parse a const expression. Return the const expression that was parsed.
+ *
+ * This method assumes that the current token matches `Keyword.CONST`.
+ *
+ * constExpression ::=
+ * instanceCreationExpression
+ * | listLiteral
+ * | mapLiteral
+ */
+ Expression parseConstExpression() {
+ Token keyword = getAndAdvance();
+ TokenType type = _currentToken.type;
+ if (type == TokenType.LT || _injectGenericCommentTypeList()) {
+ return parseListOrMapLiteral(keyword);
+ } else if (type == TokenType.OPEN_SQUARE_BRACKET ||
+ type == TokenType.INDEX) {
+ return _parseListLiteral(keyword, null);
+ } else if (type == TokenType.OPEN_CURLY_BRACKET) {
+ return _parseMapLiteral(keyword, null);
+ }
+ return _parseInstanceCreationExpression(keyword);
+ }
+
+ /**
* Parse the name of a constructor. Return the constructor name that was
* parsed.
*
@@ -1519,7 +2593,7 @@
* type ('.' identifier)?
*/
ConstructorName parseConstructorName() {
- TypeName type = parseTypeName();
+ TypeName type = parseTypeName(false);
Token period = null;
SimpleIdentifier name = null;
if (_matches(TokenType.PERIOD)) {
@@ -1530,6 +2604,32 @@
}
/**
+ * Parse a continue statement. Return the continue statement that was parsed.
+ *
+ * This method assumes that the current token matches `Keyword.CONTINUE`.
+ *
+ * continueStatement ::=
+ * 'continue' identifier? ';'
+ */
+ Statement parseContinueStatement() {
+ Token continueKeyword = getAndAdvance();
+ if (!_inLoop && !_inSwitch) {
+ _reportErrorForToken(
+ ParserErrorCode.CONTINUE_OUTSIDE_OF_LOOP, continueKeyword);
+ }
+ SimpleIdentifier label = null;
+ if (_matchesIdentifier()) {
+ label = _parseSimpleIdentifierUnchecked();
+ }
+ if (_inSwitch && !_inLoop && label == null) {
+ _reportErrorForToken(
+ ParserErrorCode.CONTINUE_WITHOUT_LABEL_IN_CASE, continueKeyword);
+ }
+ Token semicolon = _expect(TokenType.SEMICOLON);
+ return new ContinueStatement(continueKeyword, label, semicolon);
+ }
+
+ /**
* Parse the script tag and directives in a compilation unit, starting with
* the given [token], until the first non-directive is encountered. The
* remainder of the compilation unit will not be parsed. Specifically, if
@@ -1538,7 +2638,194 @@
*/
CompilationUnit parseDirectives(Token token) {
_currentToken = token;
- return _parseDirectives();
+ return parseDirectives2();
+ }
+
+ /**
+ * Parse the script tag and directives in a compilation unit until the first
+ * non-directive is encountered. Return the compilation unit that was parsed.
+ *
+ * compilationUnit ::=
+ * scriptTag? directive*
+ */
+ CompilationUnit parseDirectives2() {
+ Token firstToken = _currentToken;
+ ScriptTag scriptTag = null;
+ if (_matches(TokenType.SCRIPT_TAG)) {
+ scriptTag = new ScriptTag(getAndAdvance());
+ }
+ List<Directive> directives = <Directive>[];
+ while (!_matches(TokenType.EOF)) {
+ CommentAndMetadata commentAndMetadata = parseCommentAndMetadata();
+ Keyword keyword = _currentToken.keyword;
+ TokenType type = _peek().type;
+ if ((keyword == Keyword.IMPORT ||
+ keyword == Keyword.EXPORT ||
+ keyword == Keyword.LIBRARY ||
+ keyword == Keyword.PART) &&
+ type != TokenType.PERIOD &&
+ type != TokenType.LT &&
+ type != TokenType.OPEN_PAREN) {
+ directives.add(_parseDirective(commentAndMetadata));
+ } else if (_matches(TokenType.SEMICOLON)) {
+ _advance();
+ } else {
+ while (!_matches(TokenType.EOF)) {
+ _advance();
+ }
+ return new CompilationUnit(
+ firstToken, scriptTag, directives, null, _currentToken);
+ }
+ }
+ return new CompilationUnit(
+ firstToken, scriptTag, directives, null, _currentToken);
+ }
+
+ /**
+ * Parse a documentation comment based on the given list of documentation
+ * comment tokens. Return the documentation comment that was parsed, or `null`
+ * if there was no comment.
+ *
+ * documentationComment ::=
+ * multiLineComment?
+ * | singleLineComment*
+ */
+ Comment parseDocumentationComment(List<DocumentationCommentToken> tokens) {
+ if (tokens == null) {
+ return null;
+ }
+ List<CommentReference> references = _parseCommentReferences(tokens);
+ return Comment.createDocumentationCommentWithReferences(tokens, references);
+ }
+
+ /**
+ * Parse a documentation comment. Return the documentation comment that was
+ * parsed, or `null` if there was no comment.
+ *
+ * documentationComment ::=
+ * multiLineComment?
+ * | singleLineComment*
+ */
+ List<DocumentationCommentToken> parseDocumentationCommentTokens() {
+ List<DocumentationCommentToken> tokens = <DocumentationCommentToken>[];
+ CommentToken commentToken = _currentToken.precedingComments;
+ while (commentToken != null) {
+ if (commentToken is DocumentationCommentToken) {
+ if (tokens.isNotEmpty) {
+ if (commentToken.type == TokenType.SINGLE_LINE_COMMENT) {
+ if (tokens[0].type != TokenType.SINGLE_LINE_COMMENT) {
+ tokens.clear();
+ }
+ } else {
+ tokens.clear();
+ }
+ }
+ tokens.add(commentToken);
+ }
+ commentToken = commentToken.next;
+ }
+ return tokens.isEmpty ? null : tokens;
+ }
+
+ /**
+ * Parse a do statement. Return the do statement that was parsed.
+ *
+ * This method assumes that the current token matches `Keyword.DO`.
+ *
+ * doStatement ::=
+ * 'do' statement 'while' '(' expression ')' ';'
+ */
+ Statement parseDoStatement() {
+ bool wasInLoop = _inLoop;
+ _inLoop = true;
+ try {
+ Token doKeyword = getAndAdvance();
+ Statement body = parseStatement2();
+ Token whileKeyword = _expectKeyword(Keyword.WHILE);
+ Token leftParenthesis = _expect(TokenType.OPEN_PAREN);
+ Expression condition = parseExpression2();
+ Token rightParenthesis = _expect(TokenType.CLOSE_PAREN);
+ Token semicolon = _expect(TokenType.SEMICOLON);
+ return new DoStatement(doKeyword, body, whileKeyword, leftParenthesis,
+ condition, rightParenthesis, semicolon);
+ } finally {
+ _inLoop = wasInLoop;
+ }
+ }
+
+ /**
+ * Parse a dotted name. Return the dotted name that was parsed.
+ *
+ * dottedName ::=
+ * identifier ('.' identifier)*
+ */
+ DottedName parseDottedName() {
+ List<SimpleIdentifier> components = <SimpleIdentifier>[
+ parseSimpleIdentifier()
+ ];
+ while (_optional(TokenType.PERIOD)) {
+ components.add(parseSimpleIdentifier());
+ }
+ return new DottedName(components);
+ }
+
+ /**
+ * Parse an empty statement. Return the empty statement that was parsed.
+ *
+ * This method assumes that the current token matches `TokenType.SEMICOLON`.
+ *
+ * emptyStatement ::=
+ * ';'
+ */
+ Statement parseEmptyStatement() => new EmptyStatement(getAndAdvance());
+
+ /**
+ * Parse an enum declaration. The [commentAndMetadata] is the metadata to be
+ * associated with the member. Return the enum declaration that was parsed.
+ *
+ * This method assumes that the current token matches `Keyword.ENUM`.
+ *
+ * enumType ::=
+ * metadata 'enum' id '{' id (',' id)* (',')? '}'
+ */
+ EnumDeclaration parseEnumDeclaration(CommentAndMetadata commentAndMetadata) {
+ Token keyword = getAndAdvance();
+ SimpleIdentifier name = parseSimpleIdentifier(isDeclaration: true);
+ Token leftBracket = null;
+ List<EnumConstantDeclaration> constants = <EnumConstantDeclaration>[];
+ Token rightBracket = null;
+ if (_matches(TokenType.OPEN_CURLY_BRACKET)) {
+ leftBracket = getAndAdvance();
+ if (_matchesIdentifier() || _matches(TokenType.AT)) {
+ constants.add(_parseEnumConstantDeclaration());
+ } else if (_matches(TokenType.COMMA) &&
+ _tokenMatchesIdentifier(_peek())) {
+ constants.add(_parseEnumConstantDeclaration());
+ _reportErrorForCurrentToken(ParserErrorCode.MISSING_IDENTIFIER);
+ } else {
+ constants.add(_parseEnumConstantDeclaration());
+ _reportErrorForCurrentToken(ParserErrorCode.EMPTY_ENUM_BODY);
+ }
+ while (_optional(TokenType.COMMA)) {
+ if (_matches(TokenType.CLOSE_CURLY_BRACKET)) {
+ break;
+ }
+ constants.add(_parseEnumConstantDeclaration());
+ }
+ rightBracket = _expect(TokenType.CLOSE_CURLY_BRACKET);
+ } else {
+ leftBracket = _createSyntheticToken(TokenType.OPEN_CURLY_BRACKET);
+ rightBracket = _createSyntheticToken(TokenType.CLOSE_CURLY_BRACKET);
+ _reportErrorForCurrentToken(ParserErrorCode.MISSING_ENUM_BODY);
+ }
+ return new EnumDeclaration(
+ commentAndMetadata.comment,
+ commentAndMetadata.metadata,
+ keyword,
+ name,
+ leftBracket,
+ constants,
+ rightBracket);
}
/**
@@ -1563,10 +2850,10 @@
Expression parseExpression2() {
Keyword keyword = _currentToken.keyword;
if (keyword == Keyword.THROW) {
- return _parseThrowExpression();
+ return parseThrowExpression();
} else if (keyword == Keyword.RETHROW) {
// TODO(brianwilkerson) Rethrow is a statement again.
- return _parseRethrowExpression();
+ return parseRethrowExpression();
}
//
// assignableExpression is a subset of conditionalExpression, so we can
@@ -1579,7 +2866,7 @@
if (type == TokenType.PERIOD_PERIOD) {
List<Expression> cascadeSections = <Expression>[];
do {
- Expression section = _parseCascadeSection();
+ Expression section = parseCascadeSection();
if (section != null) {
cascadeSections.add(section);
}
@@ -1594,6 +2881,20 @@
}
/**
+ * Parse a list of expressions. Return the expression that was parsed.
+ *
+ * expressionList ::=
+ * expression (',' expression)*
+ */
+ List<Expression> parseExpressionList() {
+ List<Expression> expressions = <Expression>[parseExpression2()];
+ while (_optional(TokenType.COMMA)) {
+ expressions.add(parseExpression2());
+ }
+ return expressions;
+ }
+
+ /**
* Parse an expression that does not contain any cascades. Return the
* expression that was parsed.
*
@@ -1604,9 +2905,9 @@
*/
Expression parseExpressionWithoutCascade() {
if (_matchesKeyword(Keyword.THROW)) {
- return _parseThrowExpressionWithoutCascade();
+ return parseThrowExpressionWithoutCascade();
} else if (_matchesKeyword(Keyword.RETHROW)) {
- return _parseRethrowExpression();
+ return parseRethrowExpression();
}
//
// assignableExpression is a subset of conditionalExpression, so we can
@@ -1635,11 +2936,55 @@
*/
ExtendsClause parseExtendsClause() {
Token keyword = getAndAdvance();
- TypeName superclass = parseTypeName();
+ TypeName superclass = parseTypeName(false);
return new ExtendsClause(keyword, superclass);
}
/**
+ * Parse the 'final', 'const', 'var' or type preceding a variable declaration.
+ * The [optional] is `true` if the keyword and type are optional. Return the
+ * 'final', 'const', 'var' or type that was parsed.
+ *
+ * finalConstVarOrType ::=
+ * 'final' type?
+ * | 'const' type?
+ * | 'var'
+ * | type
+ */
+ FinalConstVarOrType parseFinalConstVarOrType(bool optional) {
+ Token keywordToken = null;
+ TypeName type = null;
+ Keyword keyword = _currentToken.keyword;
+ if (keyword == Keyword.FINAL || keyword == Keyword.CONST) {
+ keywordToken = getAndAdvance();
+ if (_isTypedIdentifier(_currentToken)) {
+ type = parseTypeName(false);
+ } else {
+ // Support `final/*=T*/ x;`
+ type = _parseOptionalTypeNameComment();
+ }
+ } else if (keyword == Keyword.VAR) {
+ keywordToken = getAndAdvance();
+ // Support `var/*=T*/ x;`
+ type = _parseOptionalTypeNameComment();
+ if (type != null) {
+ // Clear the keyword to prevent an error.
+ keywordToken = null;
+ }
+ } else if (_isTypedIdentifier(_currentToken)) {
+ type = parseReturnType();
+ } else if (!optional) {
+ _reportErrorForCurrentToken(
+ ParserErrorCode.MISSING_CONST_FINAL_VAR_OR_TYPE);
+ } else {
+ // Support parameters such as `(/*=K*/ key, /*=V*/ value)`
+ // This is not supported if the type is required.
+ type = _parseOptionalTypeNameComment();
+ }
+ return new FinalConstVarOrType(keywordToken, type);
+ }
+
+ /**
* Parse a list of formal parameters. Return the formal parameters that were
* parsed.
*
@@ -1675,6 +3020,289 @@
}
/**
+ * Parse a for statement. Return the for statement that was parsed.
+ *
+ * forStatement ::=
+ * 'for' '(' forLoopParts ')' statement
+ *
+ * forLoopParts ::=
+ * forInitializerStatement expression? ';' expressionList?
+ * | declaredIdentifier 'in' expression
+ * | identifier 'in' expression
+ *
+ * forInitializerStatement ::=
+ * localVariableDeclaration ';'
+ * | expression? ';'
+ */
+ Statement parseForStatement() {
+ bool wasInLoop = _inLoop;
+ _inLoop = true;
+ try {
+ Token awaitKeyword = null;
+ if (_matchesString(_AWAIT)) {
+ awaitKeyword = getAndAdvance();
+ }
+ Token forKeyword = _expectKeyword(Keyword.FOR);
+ Token leftParenthesis = _expect(TokenType.OPEN_PAREN);
+ VariableDeclarationList variableList = null;
+ Expression initialization = null;
+ if (!_matches(TokenType.SEMICOLON)) {
+ CommentAndMetadata commentAndMetadata = parseCommentAndMetadata();
+ if (_matchesIdentifier() &&
+ (_tokenMatchesKeyword(_peek(), Keyword.IN) ||
+ _tokenMatches(_peek(), TokenType.COLON))) {
+ SimpleIdentifier variableName = _parseSimpleIdentifierUnchecked();
+ variableList = new VariableDeclarationList(commentAndMetadata.comment,
+ commentAndMetadata.metadata, null, null, <VariableDeclaration>[
+ new VariableDeclaration(variableName, null, null)
+ ]);
+ } else if (isInitializedVariableDeclaration()) {
+ variableList =
+ parseVariableDeclarationListAfterMetadata(commentAndMetadata);
+ } else {
+ initialization = parseExpression2();
+ }
+ TokenType type = _currentToken.type;
+ if (_matchesKeyword(Keyword.IN) || type == TokenType.COLON) {
+ if (type == TokenType.COLON) {
+ _reportErrorForCurrentToken(ParserErrorCode.COLON_IN_PLACE_OF_IN);
+ }
+ DeclaredIdentifier loopVariable = null;
+ SimpleIdentifier identifier = null;
+ if (variableList == null) {
+ // We found: <expression> 'in'
+ _reportErrorForCurrentToken(
+ ParserErrorCode.MISSING_VARIABLE_IN_FOR_EACH);
+ } else {
+ NodeList<VariableDeclaration> variables = variableList.variables;
+ if (variables.length > 1) {
+ _reportErrorForCurrentToken(
+ ParserErrorCode.MULTIPLE_VARIABLES_IN_FOR_EACH,
+ [variables.length.toString()]);
+ }
+ VariableDeclaration variable = variables[0];
+ if (variable.initializer != null) {
+ _reportErrorForCurrentToken(
+ ParserErrorCode.INITIALIZED_VARIABLE_IN_FOR_EACH);
+ }
+ Token keyword = variableList.keyword;
+ TypeName type = variableList.type;
+ if (keyword != null || type != null) {
+ loopVariable = new DeclaredIdentifier(
+ commentAndMetadata.comment,
+ commentAndMetadata.metadata,
+ keyword,
+ type,
+ new SimpleIdentifier(variable.name.token,
+ isDeclaration: true));
+ } else {
+ if (commentAndMetadata.hasMetadata) {
+ // TODO(jwren) metadata isn't allowed before the identifier in
+ // "identifier in expression", add warning if commentAndMetadata
+ // has content
+ }
+ identifier = variable.name;
+ }
+ }
+ Token inKeyword = getAndAdvance();
+ Expression iterator = parseExpression2();
+ Token rightParenthesis = _expect(TokenType.CLOSE_PAREN);
+ Statement body = parseStatement2();
+ if (loopVariable == null) {
+ return new ForEachStatement.withReference(
+ awaitKeyword,
+ forKeyword,
+ leftParenthesis,
+ identifier,
+ inKeyword,
+ iterator,
+ rightParenthesis,
+ body);
+ }
+ return new ForEachStatement.withDeclaration(
+ awaitKeyword,
+ forKeyword,
+ leftParenthesis,
+ loopVariable,
+ inKeyword,
+ iterator,
+ rightParenthesis,
+ body);
+ }
+ }
+ if (awaitKeyword != null) {
+ _reportErrorForToken(
+ ParserErrorCode.INVALID_AWAIT_IN_FOR, awaitKeyword);
+ }
+ Token leftSeparator = _expect(TokenType.SEMICOLON);
+ Expression condition = null;
+ if (!_matches(TokenType.SEMICOLON)) {
+ condition = parseExpression2();
+ }
+ Token rightSeparator = _expect(TokenType.SEMICOLON);
+ List<Expression> updaters = null;
+ if (!_matches(TokenType.CLOSE_PAREN)) {
+ updaters = parseExpressionList();
+ }
+ Token rightParenthesis = _expect(TokenType.CLOSE_PAREN);
+ Statement body = parseStatement2();
+ return new ForStatement(
+ forKeyword,
+ leftParenthesis,
+ variableList,
+ initialization,
+ leftSeparator,
+ condition,
+ rightSeparator,
+ updaters,
+ rightParenthesis,
+ body);
+ } finally {
+ _inLoop = wasInLoop;
+ }
+ }
+
+ /**
+ * Parse a function body. The [mayBeEmpty] is `true` if the function body is
+ * allowed to be empty. The [emptyErrorCode] is the error code to report if
+ * function body expected, but not found. The [inExpression] is `true` if the
+ * function body is being parsed as part of an expression and therefore does
+ * not have a terminating semicolon. Return the function body that was parsed.
+ *
+ * functionBody ::=
+ * '=>' expression ';'
+ * | block
+ *
+ * functionExpressionBody ::=
+ * '=>' expression
+ * | block
+ */
+ FunctionBody parseFunctionBody(
+ bool mayBeEmpty, ParserErrorCode emptyErrorCode, bool inExpression) {
+ bool wasInAsync = _inAsync;
+ bool wasInGenerator = _inGenerator;
+ bool wasInLoop = _inLoop;
+ bool wasInSwitch = _inSwitch;
+ _inAsync = false;
+ _inGenerator = false;
+ _inLoop = false;
+ _inSwitch = false;
+ try {
+ TokenType type = _currentToken.type;
+ if (type == TokenType.SEMICOLON) {
+ if (!mayBeEmpty) {
+ _reportErrorForCurrentToken(emptyErrorCode);
+ }
+ return new EmptyFunctionBody(getAndAdvance());
+ }
+ Token keyword = null;
+ Token star = null;
+ bool foundAsync = false;
+ bool foundSync = false;
+ if (type == TokenType.IDENTIFIER) {
+ String lexeme = _currentToken.lexeme;
+ if (lexeme == ASYNC) {
+ foundAsync = true;
+ keyword = getAndAdvance();
+ if (!_parseAsync) {
+ _reportErrorForToken(ParserErrorCode.ASYNC_NOT_SUPPORTED, keyword);
+ }
+ if (_matches(TokenType.STAR)) {
+ star = getAndAdvance();
+ _inGenerator = true;
+ }
+ type = _currentToken.type;
+ _inAsync = true;
+ } else if (lexeme == SYNC) {
+ foundSync = true;
+ keyword = getAndAdvance();
+ if (!_parseAsync) {
+ _reportErrorForToken(ParserErrorCode.ASYNC_NOT_SUPPORTED, keyword);
+ }
+ if (_matches(TokenType.STAR)) {
+ star = getAndAdvance();
+ _inGenerator = true;
+ }
+ type = _currentToken.type;
+ }
+ }
+ if (type == TokenType.FUNCTION) {
+ if (keyword != null) {
+ if (!foundAsync) {
+ _reportErrorForToken(ParserErrorCode.INVALID_SYNC, keyword);
+ keyword = null;
+ } else if (star != null) {
+ _reportErrorForToken(
+ ParserErrorCode.INVALID_STAR_AFTER_ASYNC, star);
+ }
+ }
+ Token functionDefinition = getAndAdvance();
+ if (_matchesKeyword(Keyword.RETURN)) {
+ _reportErrorForToken(ParserErrorCode.UNEXPECTED_TOKEN, _currentToken,
+ [_currentToken.lexeme]);
+ _advance();
+ }
+ Expression expression = parseExpression2();
+ Token semicolon = null;
+ if (!inExpression) {
+ semicolon = _expect(TokenType.SEMICOLON);
+ }
+ if (!_parseFunctionBodies) {
+ return new EmptyFunctionBody(
+ _createSyntheticToken(TokenType.SEMICOLON));
+ }
+ return new ExpressionFunctionBody(
+ keyword, functionDefinition, expression, semicolon);
+ } else if (type == TokenType.OPEN_CURLY_BRACKET) {
+ if (keyword != null) {
+ if (foundSync && star == null) {
+ _reportErrorForToken(
+ ParserErrorCode.MISSING_STAR_AFTER_SYNC, keyword);
+ }
+ }
+ if (!_parseFunctionBodies) {
+ _skipBlock();
+ return new EmptyFunctionBody(
+ _createSyntheticToken(TokenType.SEMICOLON));
+ }
+ return new BlockFunctionBody(keyword, star, parseBlock());
+ } else if (_matchesString(_NATIVE)) {
+ Token nativeToken = getAndAdvance();
+ StringLiteral stringLiteral = null;
+ if (_matches(TokenType.STRING)) {
+ stringLiteral = _parseStringLiteralUnchecked();
+ }
+ return new NativeFunctionBody(
+ nativeToken, stringLiteral, _expect(TokenType.SEMICOLON));
+ } else {
+ // Invalid function body
+ _reportErrorForCurrentToken(emptyErrorCode);
+ return new EmptyFunctionBody(
+ _createSyntheticToken(TokenType.SEMICOLON));
+ }
+ } finally {
+ _inAsync = wasInAsync;
+ _inGenerator = wasInGenerator;
+ _inLoop = wasInLoop;
+ _inSwitch = wasInSwitch;
+ }
+ }
+
+ /**
+ * Parse a function declaration statement. Return the function declaration
+ * statement that was parsed.
+ *
+ * functionDeclarationStatement ::=
+ * functionSignature functionBody
+ */
+ Statement parseFunctionDeclarationStatement() {
+ Modifiers modifiers = _parseModifiers();
+ _validateModifiersForFunctionDeclarationStatement(modifiers);
+ return _parseFunctionDeclarationStatementAfterReturnType(
+ parseCommentAndMetadata(), _parseOptionalReturnType());
+ }
+
+ /**
* Parse a function expression. Return the function expression that was
* parsed.
*
@@ -1686,7 +3314,7 @@
FormalParameterList parameters = parseFormalParameterList();
_validateFormalParameterList(parameters);
FunctionBody body =
- _parseFunctionBody(false, ParserErrorCode.MISSING_FUNCTION_BODY, true);
+ parseFunctionBody(false, ParserErrorCode.MISSING_FUNCTION_BODY, true);
return new FunctionExpression(typeParameters, parameters, body);
}
@@ -1706,6 +3334,30 @@
}
/**
+ * Parse an if statement. Return the if statement that was parsed.
+ *
+ * This method assumes that the current token matches `Keyword.IF`.
+ *
+ * ifStatement ::=
+ * 'if' '(' expression ')' statement ('else' statement)?
+ */
+ Statement parseIfStatement() {
+ Token ifKeyword = getAndAdvance();
+ Token leftParenthesis = _expect(TokenType.OPEN_PAREN);
+ Expression condition = parseExpression2();
+ Token rightParenthesis = _expect(TokenType.CLOSE_PAREN);
+ Statement thenStatement = parseStatement2();
+ Token elseKeyword = null;
+ Statement elseStatement = null;
+ if (_matchesKeyword(Keyword.ELSE)) {
+ elseKeyword = getAndAdvance();
+ elseStatement = parseStatement2();
+ }
+ return new IfStatement(ifKeyword, leftParenthesis, condition,
+ rightParenthesis, thenStatement, elseKeyword, elseStatement);
+ }
+
+ /**
* Parse an implements clause. Return the implements clause that was parsed.
*
* This method assumes that the current token matches `Keyword.IMPLEMENTS`.
@@ -1716,9 +3368,9 @@
ImplementsClause parseImplementsClause() {
Token keyword = getAndAdvance();
List<TypeName> interfaces = <TypeName>[];
- interfaces.add(parseTypeName());
+ interfaces.add(parseTypeName(false));
while (_optional(TokenType.COMMA)) {
- interfaces.add(parseTypeName());
+ interfaces.add(parseTypeName(false));
}
return new ImplementsClause(keyword, interfaces);
}
@@ -1755,6 +3407,32 @@
}
/**
+ * Parse a list or map literal. The [modifier] is the 'const' modifier
+ * appearing before the literal, or `null` if there is no modifier. Return the
+ * list or map literal that was parsed.
+ *
+ * listOrMapLiteral ::=
+ * listLiteral
+ * | mapLiteral
+ */
+ TypedLiteral parseListOrMapLiteral(Token modifier) {
+ TypeArgumentList typeArguments = _parseOptionalTypeArguments();
+ if (_matches(TokenType.OPEN_CURLY_BRACKET)) {
+ return _parseMapLiteral(modifier, typeArguments);
+ } else if (_matches(TokenType.OPEN_SQUARE_BRACKET) ||
+ _matches(TokenType.INDEX)) {
+ return _parseListLiteral(modifier, typeArguments);
+ }
+ _reportErrorForCurrentToken(ParserErrorCode.EXPECTED_LIST_OR_MAP_LITERAL);
+ return new ListLiteral(
+ modifier,
+ typeArguments,
+ _createSyntheticToken(TokenType.OPEN_SQUARE_BRACKET),
+ null,
+ _createSyntheticToken(TokenType.CLOSE_SQUARE_BRACKET));
+ }
+
+ /**
* Parse a logical or expression. Return the logical or expression that was
* parsed.
*
@@ -1784,6 +3462,29 @@
}
/**
+ * Parse a multiplicative expression. Return the multiplicative expression
+ * that was parsed.
+ *
+ * multiplicativeExpression ::=
+ * unaryExpression (multiplicativeOperator unaryExpression)*
+ * | 'super' (multiplicativeOperator unaryExpression)+
+ */
+ Expression parseMultiplicativeExpression() {
+ Expression expression;
+ if (_currentToken.keyword == Keyword.SUPER &&
+ _currentToken.next.type.isMultiplicativeOperator) {
+ expression = new SuperExpression(getAndAdvance());
+ } else {
+ expression = parseUnaryExpression();
+ }
+ while (_currentToken.type.isMultiplicativeOperator) {
+ expression = new BinaryExpression(
+ expression, getAndAdvance(), parseUnaryExpression());
+ }
+ return expression;
+ }
+
+ /**
* Parse a normal formal parameter. Return the normal formal parameter that
* was parsed.
*
@@ -1803,8 +3504,8 @@
* | metadata identifier
*/
NormalFormalParameter parseNormalFormalParameter() {
- CommentAndMetadata commentAndMetadata = _parseCommentAndMetadata();
- FinalConstVarOrType holder = _parseFinalConstVarOrType(true);
+ CommentAndMetadata commentAndMetadata = parseCommentAndMetadata();
+ FinalConstVarOrType holder = parseFinalConstVarOrType(true);
Token thisKeyword = null;
Token period = null;
if (_matchesKeyword(Keyword.THIS)) {
@@ -1820,13 +3521,18 @@
_reportErrorForToken(
ParserErrorCode.FUNCTION_TYPED_PARAMETER_VAR, holder.keyword);
}
+ Token question = null;
+ if (enableNnbd && _matches(TokenType.QUESTION)) {
+ question = getAndAdvance();
+ }
return new FunctionTypedFormalParameter(
commentAndMetadata.comment,
commentAndMetadata.metadata,
holder.type,
new SimpleIdentifier(identifier.token, isDeclaration: true),
typeParameters,
- parameters);
+ parameters,
+ question: question);
} else {
return new FieldFormalParameter(
commentAndMetadata.comment,
@@ -1878,6 +3584,33 @@
}
/**
+ * Parse an operator declaration. The [commentAndMetadata] is the
+ * documentation comment and metadata to be associated with the declaration.
+ * The [externalKeyword] is the 'external' token. The [returnType] is the
+ * return type that has already been parsed, or `null` if there was no return
+ * type. Return the operator declaration that was parsed.
+ *
+ * operatorDeclaration ::=
+ * operatorSignature (';' | functionBody)
+ *
+ * operatorSignature ::=
+ * 'external'? returnType? 'operator' operator formalParameterList
+ */
+ MethodDeclaration parseOperator(CommentAndMetadata commentAndMetadata,
+ Token externalKeyword, TypeName returnType) {
+ Token operatorKeyword;
+ if (_matchesKeyword(Keyword.OPERATOR)) {
+ operatorKeyword = getAndAdvance();
+ } else {
+ _reportErrorForToken(
+ ParserErrorCode.MISSING_KEYWORD_OPERATOR, _currentToken);
+ operatorKeyword = _createSyntheticKeyword(Keyword.OPERATOR);
+ }
+ return _parseOperatorAfterKeyword(
+ commentAndMetadata, externalKeyword, returnType, operatorKeyword);
+ }
+
+ /**
* Parse a prefixed identifier. Return the prefixed identifier that was
* parsed.
*
@@ -1889,6 +3622,206 @@
}
/**
+ * Parse a primary expression. Return the primary expression that was parsed.
+ *
+ * primary ::=
+ * thisExpression
+ * | 'super' unconditionalAssignableSelector
+ * | functionExpression
+ * | literal
+ * | identifier
+ * | newExpression
+ * | constObjectExpression
+ * | '(' expression ')'
+ * | argumentDefinitionTest
+ *
+ * literal ::=
+ * nullLiteral
+ * | booleanLiteral
+ * | numericLiteral
+ * | stringLiteral
+ * | symbolLiteral
+ * | mapLiteral
+ * | listLiteral
+ */
+ Expression parsePrimaryExpression() {
+ if (_matchesIdentifier()) {
+ // TODO(brianwilkerson) The code below was an attempt to recover from an
+ // error case, but it needs to be applied as a recovery only after we
+ // know that parsing it as an identifier doesn't work. Leaving the code as
+ // a reminder of how to recover.
+// if (isFunctionExpression(_peek())) {
+// //
+// // Function expressions were allowed to have names at one point, but this is now illegal.
+// //
+// reportError(ParserErrorCode.NAMED_FUNCTION_EXPRESSION, getAndAdvance());
+// return parseFunctionExpression();
+// }
+ return _parsePrefixedIdentifierUnchecked();
+ }
+ TokenType type = _currentToken.type;
+ if (type == TokenType.STRING) {
+ return parseStringLiteral();
+ } else if (type == TokenType.INT) {
+ Token token = getAndAdvance();
+ int value = null;
+ try {
+ value = int.parse(token.lexeme);
+ } on FormatException {
+ // The invalid format should have been reported by the scanner.
+ }
+ return new IntegerLiteral(token, value);
+ }
+ Keyword keyword = _currentToken.keyword;
+ if (keyword == Keyword.NULL) {
+ return new NullLiteral(getAndAdvance());
+ } else if (keyword == Keyword.NEW) {
+ return _parseNewExpression();
+ } else if (keyword == Keyword.THIS) {
+ return new ThisExpression(getAndAdvance());
+ } else if (keyword == Keyword.SUPER) {
+ // TODO(paulberry): verify with Gilad that "super" must be followed by
+ // unconditionalAssignableSelector in this case.
+ return _parseAssignableSelector(
+ new SuperExpression(getAndAdvance()), false,
+ allowConditional: false);
+ } else if (keyword == Keyword.FALSE) {
+ return new BooleanLiteral(getAndAdvance(), false);
+ } else if (keyword == Keyword.TRUE) {
+ return new BooleanLiteral(getAndAdvance(), true);
+ }
+ if (type == TokenType.DOUBLE) {
+ Token token = getAndAdvance();
+ double value = 0.0;
+ try {
+ value = double.parse(token.lexeme);
+ } on FormatException {
+ // The invalid format should have been reported by the scanner.
+ }
+ return new DoubleLiteral(token, value);
+ } else if (type == TokenType.HEXADECIMAL) {
+ Token token = getAndAdvance();
+ int value = null;
+ try {
+ value = int.parse(token.lexeme.substring(2), radix: 16);
+ } on FormatException {
+ // The invalid format should have been reported by the scanner.
+ }
+ return new IntegerLiteral(token, value);
+ } else if (keyword == Keyword.CONST) {
+ return parseConstExpression();
+ } else if (type == TokenType.OPEN_PAREN) {
+ if (isFunctionExpression(_currentToken)) {
+ return parseFunctionExpression();
+ }
+ Token leftParenthesis = getAndAdvance();
+ bool wasInInitializer = _inInitializer;
+ _inInitializer = false;
+ try {
+ Expression expression = parseExpression2();
+ Token rightParenthesis = _expect(TokenType.CLOSE_PAREN);
+ return new ParenthesizedExpression(
+ leftParenthesis, expression, rightParenthesis);
+ } finally {
+ _inInitializer = wasInInitializer;
+ }
+ } else if (type == TokenType.LT || _injectGenericCommentTypeList()) {
+ return parseListOrMapLiteral(null);
+ } else if (type == TokenType.OPEN_CURLY_BRACKET) {
+ return _parseMapLiteral(null, null);
+ } else if (type == TokenType.OPEN_SQUARE_BRACKET ||
+ type == TokenType.INDEX) {
+ return _parseListLiteral(null, null);
+ } else if (type == TokenType.QUESTION &&
+ _tokenMatches(_peek(), TokenType.IDENTIFIER)) {
+ _reportErrorForCurrentToken(
+ ParserErrorCode.UNEXPECTED_TOKEN, [_currentToken.lexeme]);
+ _advance();
+ return parsePrimaryExpression();
+ } else if (keyword == Keyword.VOID) {
+ //
+ // Recover from having a return type of "void" where a return type is not
+ // expected.
+ //
+ // TODO(brianwilkerson) Improve this error message.
+ _reportErrorForCurrentToken(
+ ParserErrorCode.UNEXPECTED_TOKEN, [_currentToken.lexeme]);
+ _advance();
+ return parsePrimaryExpression();
+ } else if (type == TokenType.HASH) {
+ return parseSymbolLiteral();
+ } else {
+ _reportErrorForCurrentToken(ParserErrorCode.MISSING_IDENTIFIER);
+ return createSyntheticIdentifier();
+ }
+ }
+
+ /**
+ * Parse a relational expression. Return the relational expression that was
+ * parsed.
+ *
+ * relationalExpression ::=
+ * bitwiseOrExpression ('is' '!'? type | 'as' type | relationalOperator bitwiseOrExpression)?
+ * | 'super' relationalOperator bitwiseOrExpression
+ */
+ Expression parseRelationalExpression() {
+ if (_currentToken.keyword == Keyword.SUPER &&
+ _currentToken.next.type.isRelationalOperator) {
+ Expression expression = new SuperExpression(getAndAdvance());
+ Token operator = getAndAdvance();
+ return new BinaryExpression(
+ expression, operator, parseBitwiseOrExpression());
+ }
+ Expression expression = parseBitwiseOrExpression();
+ Keyword keyword = _currentToken.keyword;
+ if (keyword == Keyword.AS) {
+ Token asOperator = getAndAdvance();
+ return new AsExpression(expression, asOperator, parseTypeName(true));
+ } else if (keyword == Keyword.IS) {
+ Token isOperator = getAndAdvance();
+ Token notOperator = null;
+ if (_matches(TokenType.BANG)) {
+ notOperator = getAndAdvance();
+ }
+ return new IsExpression(
+ expression, isOperator, notOperator, parseTypeName(true));
+ } else if (_currentToken.type.isRelationalOperator) {
+ Token operator = getAndAdvance();
+ return new BinaryExpression(
+ expression, operator, parseBitwiseOrExpression());
+ }
+ return expression;
+ }
+
+ /**
+ * Parse a rethrow expression. Return the rethrow expression that was parsed.
+ *
+ * This method assumes that the current token matches `Keyword.RETHROW`.
+ *
+ * rethrowExpression ::=
+ * 'rethrow'
+ */
+ Expression parseRethrowExpression() => new RethrowExpression(getAndAdvance());
+
+ /**
+ * Parse a return statement. Return the return statement that was parsed.
+ *
+ * This method assumes that the current token matches `Keyword.RETURN`.
+ *
+ * returnStatement ::=
+ * 'return' expression? ';'
+ */
+ Statement parseReturnStatement() {
+ Token returnKeyword = getAndAdvance();
+ if (_matches(TokenType.SEMICOLON)) {
+ return new ReturnStatement(returnKeyword, null, getAndAdvance());
+ }
+ Expression expression = parseExpression2();
+ Token semicolon = _expect(TokenType.SEMICOLON);
+ return new ReturnStatement(returnKeyword, expression, semicolon);
+ }
+
+ /**
* Parse a return type. Return the return type that was parsed.
*
* returnType ::=
@@ -1899,11 +3832,33 @@
if (_currentToken.keyword == Keyword.VOID) {
return new TypeName(new SimpleIdentifier(getAndAdvance()), null);
} else {
- return parseTypeName();
+ return parseTypeName(false);
}
}
/**
+ * Parse a shift expression. Return the shift expression that was parsed.
+ *
+ * shiftExpression ::=
+ * additiveExpression (shiftOperator additiveExpression)*
+ * | 'super' (shiftOperator additiveExpression)+
+ */
+ Expression parseShiftExpression() {
+ Expression expression;
+ if (_currentToken.keyword == Keyword.SUPER &&
+ _currentToken.next.type.isShiftOperator) {
+ expression = new SuperExpression(getAndAdvance());
+ } else {
+ expression = parseAdditiveExpression();
+ }
+ while (_currentToken.type.isShiftOperator) {
+ expression = new BinaryExpression(
+ expression, getAndAdvance(), parseAdditiveExpression());
+ }
+ return expression;
+ }
+
+ /**
* Parse a simple identifier. Return the simple identifier that was parsed.
*
* identifier ::=
@@ -1914,7 +3869,7 @@
return _parseSimpleIdentifierUnchecked(isDeclaration: isDeclaration);
}
_reportErrorForCurrentToken(ParserErrorCode.MISSING_IDENTIFIER);
- return _createSyntheticIdentifier(isDeclaration: isDeclaration);
+ return createSyntheticIdentifier(isDeclaration: isDeclaration);
}
/**
@@ -1972,7 +3927,263 @@
return _parseStringLiteralUnchecked();
}
_reportErrorForCurrentToken(ParserErrorCode.EXPECTED_STRING_LITERAL);
- return _createSyntheticStringLiteral();
+ return createSyntheticStringLiteral();
+ }
+
+ /**
+ * Parse a super constructor invocation. Return the super constructor
+ * invocation that was parsed.
+ *
+ * This method assumes that the current token matches [Keyword.SUPER].
+ *
+ * superConstructorInvocation ::=
+ * 'super' ('.' identifier)? arguments
+ */
+ SuperConstructorInvocation parseSuperConstructorInvocation() {
+ Token keyword = getAndAdvance();
+ Token period = null;
+ SimpleIdentifier constructorName = null;
+ if (_matches(TokenType.PERIOD)) {
+ period = getAndAdvance();
+ constructorName = parseSimpleIdentifier();
+ }
+ ArgumentList argumentList = _parseArgumentListChecked();
+ return new SuperConstructorInvocation(
+ keyword, period, constructorName, argumentList);
+ }
+
+ /**
+ * Parse a switch statement. Return the switch statement that was parsed.
+ *
+ * switchStatement ::=
+ * 'switch' '(' expression ')' '{' switchCase* defaultCase? '}'
+ *
+ * switchCase ::=
+ * label* ('case' expression ':') statements
+ *
+ * defaultCase ::=
+ * label* 'default' ':' statements
+ */
+ SwitchStatement parseSwitchStatement() {
+ bool wasInSwitch = _inSwitch;
+ _inSwitch = true;
+ try {
+ HashSet<String> definedLabels = new HashSet<String>();
+ Token keyword = _expectKeyword(Keyword.SWITCH);
+ Token leftParenthesis = _expect(TokenType.OPEN_PAREN);
+ Expression expression = parseExpression2();
+ Token rightParenthesis = _expect(TokenType.CLOSE_PAREN);
+ Token leftBracket = _expect(TokenType.OPEN_CURLY_BRACKET);
+ Token defaultKeyword = null;
+ List<SwitchMember> members = <SwitchMember>[];
+ TokenType type = _currentToken.type;
+ while (type != TokenType.EOF && type != TokenType.CLOSE_CURLY_BRACKET) {
+ List<Label> labels = <Label>[];
+ while (
+ _matchesIdentifier() && _tokenMatches(_peek(), TokenType.COLON)) {
+ SimpleIdentifier identifier =
+ _parseSimpleIdentifierUnchecked(isDeclaration: true);
+ String label = identifier.token.lexeme;
+ if (definedLabels.contains(label)) {
+ _reportErrorForToken(
+ ParserErrorCode.DUPLICATE_LABEL_IN_SWITCH_STATEMENT,
+ identifier.token,
+ [label]);
+ } else {
+ definedLabels.add(label);
+ }
+ Token colon = getAndAdvance();
+ labels.add(new Label(identifier, colon));
+ }
+ Keyword keyword = _currentToken.keyword;
+ if (keyword == Keyword.CASE) {
+ Token caseKeyword = getAndAdvance();
+ Expression caseExpression = parseExpression2();
+ Token colon = _expect(TokenType.COLON);
+ members.add(new SwitchCase(labels, caseKeyword, caseExpression, colon,
+ _parseStatementList()));
+ if (defaultKeyword != null) {
+ _reportErrorForToken(
+ ParserErrorCode.SWITCH_HAS_CASE_AFTER_DEFAULT_CASE,
+ caseKeyword);
+ }
+ } else if (keyword == Keyword.DEFAULT) {
+ if (defaultKeyword != null) {
+ _reportErrorForToken(
+ ParserErrorCode.SWITCH_HAS_MULTIPLE_DEFAULT_CASES, _peek());
+ }
+ defaultKeyword = getAndAdvance();
+ Token colon = _expect(TokenType.COLON);
+ members.add(new SwitchDefault(
+ labels, defaultKeyword, colon, _parseStatementList()));
+ } else {
+ // We need to advance, otherwise we could end up in an infinite loop,
+ // but this could be a lot smarter about recovering from the error.
+ _reportErrorForCurrentToken(ParserErrorCode.EXPECTED_CASE_OR_DEFAULT);
+ bool atEndOrNextMember() {
+ TokenType type = _currentToken.type;
+ if (type == TokenType.EOF ||
+ type == TokenType.CLOSE_CURLY_BRACKET) {
+ return true;
+ }
+ Keyword keyword = _currentToken.keyword;
+ return keyword == Keyword.CASE || keyword == Keyword.DEFAULT;
+ }
+
+ while (!atEndOrNextMember()) {
+ _advance();
+ }
+ }
+ type = _currentToken.type;
+ }
+ Token rightBracket = _expect(TokenType.CLOSE_CURLY_BRACKET);
+ return new SwitchStatement(keyword, leftParenthesis, expression,
+ rightParenthesis, leftBracket, members, rightBracket);
+ } finally {
+ _inSwitch = wasInSwitch;
+ }
+ }
+
+ /**
+ * Parse a symbol literal. Return the symbol literal that was parsed.
+ *
+ * This method assumes that the current token matches [TokenType.HASH].
+ *
+ * symbolLiteral ::=
+ * '#' identifier ('.' identifier)*
+ */
+ SymbolLiteral parseSymbolLiteral() {
+ Token poundSign = getAndAdvance();
+ List<Token> components = <Token>[];
+ if (_matchesIdentifier()) {
+ components.add(getAndAdvance());
+ while (_optional(TokenType.PERIOD)) {
+ if (_matchesIdentifier()) {
+ components.add(getAndAdvance());
+ } else {
+ _reportErrorForCurrentToken(ParserErrorCode.MISSING_IDENTIFIER);
+ components.add(_createSyntheticToken(TokenType.IDENTIFIER));
+ break;
+ }
+ }
+ } else if (_currentToken.isOperator) {
+ components.add(getAndAdvance());
+ } else if (_matchesKeyword(Keyword.VOID)) {
+ components.add(getAndAdvance());
+ } else {
+ _reportErrorForCurrentToken(ParserErrorCode.MISSING_IDENTIFIER);
+ components.add(_createSyntheticToken(TokenType.IDENTIFIER));
+ }
+ return new SymbolLiteral(poundSign, components);
+ }
+
+ /**
+ * Parse a throw expression. Return the throw expression that was parsed.
+ *
+ * This method assumes that the current token matches [Keyword.THROW].
+ *
+ * throwExpression ::=
+ * 'throw' expression
+ */
+ Expression parseThrowExpression() {
+ Token keyword = getAndAdvance();
+ TokenType type = _currentToken.type;
+ if (type == TokenType.SEMICOLON || type == TokenType.CLOSE_PAREN) {
+ _reportErrorForToken(
+ ParserErrorCode.MISSING_EXPRESSION_IN_THROW, _currentToken);
+ return new ThrowExpression(keyword, createSyntheticIdentifier());
+ }
+ Expression expression = parseExpression2();
+ return new ThrowExpression(keyword, expression);
+ }
+
+ /**
+ * Parse a throw expression. Return the throw expression that was parsed.
+ *
+ * This method assumes that the current token matches [Keyword.THROW].
+ *
+ * throwExpressionWithoutCascade ::=
+ * 'throw' expressionWithoutCascade
+ */
+ Expression parseThrowExpressionWithoutCascade() {
+ Token keyword = getAndAdvance();
+ TokenType type = _currentToken.type;
+ if (type == TokenType.SEMICOLON || type == TokenType.CLOSE_PAREN) {
+ _reportErrorForToken(
+ ParserErrorCode.MISSING_EXPRESSION_IN_THROW, _currentToken);
+ return new ThrowExpression(keyword, createSyntheticIdentifier());
+ }
+ Expression expression = parseExpressionWithoutCascade();
+ return new ThrowExpression(keyword, expression);
+ }
+
+ /**
+ * Parse a try statement. Return the try statement that was parsed.
+ *
+ * This method assumes that the current token matches [Keyword.TRY].
+ *
+ * tryStatement ::=
+ * 'try' block (onPart+ finallyPart? | finallyPart)
+ *
+ * onPart ::=
+ * catchPart block
+ * | 'on' type catchPart? block
+ *
+ * catchPart ::=
+ * 'catch' '(' identifier (',' identifier)? ')'
+ *
+ * finallyPart ::=
+ * 'finally' block
+ */
+ Statement parseTryStatement() {
+ Token tryKeyword = getAndAdvance();
+ Block body = _parseBlockChecked();
+ List<CatchClause> catchClauses = <CatchClause>[];
+ Block finallyClause = null;
+ while (_matchesString(_ON) || _matchesKeyword(Keyword.CATCH)) {
+ Token onKeyword = null;
+ TypeName exceptionType = null;
+ if (_matchesString(_ON)) {
+ onKeyword = getAndAdvance();
+ exceptionType = parseTypeName(false);
+ }
+ Token catchKeyword = null;
+ Token leftParenthesis = null;
+ SimpleIdentifier exceptionParameter = null;
+ Token comma = null;
+ SimpleIdentifier stackTraceParameter = null;
+ Token rightParenthesis = null;
+ if (_matchesKeyword(Keyword.CATCH)) {
+ catchKeyword = getAndAdvance();
+ leftParenthesis = _expect(TokenType.OPEN_PAREN);
+ exceptionParameter = parseSimpleIdentifier(isDeclaration: true);
+ if (_matches(TokenType.COMMA)) {
+ comma = getAndAdvance();
+ stackTraceParameter = parseSimpleIdentifier(isDeclaration: true);
+ }
+ rightParenthesis = _expect(TokenType.CLOSE_PAREN);
+ }
+ Block catchBody = _parseBlockChecked();
+ catchClauses.add(new CatchClause(
+ onKeyword,
+ exceptionType,
+ catchKeyword,
+ leftParenthesis,
+ exceptionParameter,
+ comma,
+ stackTraceParameter,
+ rightParenthesis,
+ catchBody));
+ }
+ Token finallyKeyword = null;
+ if (_matchesKeyword(Keyword.FINALLY)) {
+ finallyKeyword = getAndAdvance();
+ finallyClause = _parseBlockChecked();
+ } else if (catchClauses.isEmpty) {
+ _reportErrorForCurrentToken(ParserErrorCode.MISSING_CATCH_OR_FINALLY);
+ }
+ return new TryStatement(
+ tryKeyword, body, catchClauses, finallyKeyword, finallyClause);
}
/**
@@ -1989,9 +4200,9 @@
*/
TypeArgumentList parseTypeArgumentList() {
Token leftBracket = getAndAdvance();
- List<TypeName> arguments = <TypeName>[parseTypeName()];
+ List<TypeName> arguments = <TypeName>[parseTypeName(false)];
while (_optional(TokenType.COMMA)) {
- arguments.add(parseTypeName());
+ arguments.add(parseTypeName(false));
}
Token rightBracket = _expectGt();
return new TypeArgumentList(leftBracket, arguments, rightBracket);
@@ -2003,8 +4214,8 @@
* type ::=
* qualified typeArguments?
*/
- TypeName parseTypeName() {
- TypeName realType = _parseTypeName();
+ TypeName parseTypeName(bool inExpression) {
+ TypeName realType = _parseTypeName(inExpression);
// If this is followed by a generic method type comment, allow the comment
// type to replace the real type name.
// TODO(jmesserly): this feels like a big hammer. Can we restrict it to
@@ -2020,11 +4231,11 @@
* metadata name ('extends' bound)?
*/
TypeParameter parseTypeParameter() {
- CommentAndMetadata commentAndMetadata = _parseCommentAndMetadata();
+ CommentAndMetadata commentAndMetadata = parseCommentAndMetadata();
SimpleIdentifier name = parseSimpleIdentifier(isDeclaration: true);
if (_matchesKeyword(Keyword.EXTENDS)) {
Token keyword = getAndAdvance();
- TypeName bound = parseTypeName();
+ TypeName bound = parseTypeName(false);
return new TypeParameter(commentAndMetadata.comment,
commentAndMetadata.metadata, name, keyword, bound);
}
@@ -2052,6 +4263,200 @@
}
/**
+ * Parse a unary expression. Return the unary expression that was parsed.
+ *
+ * unaryExpression ::=
+ * prefixOperator unaryExpression
+ * | awaitExpression
+ * | postfixExpression
+ * | unaryOperator 'super'
+ * | '-' 'super'
+ * | incrementOperator assignableExpression
+ */
+ Expression parseUnaryExpression() {
+ TokenType type = _currentToken.type;
+ if (type == TokenType.MINUS ||
+ type == TokenType.BANG ||
+ type == TokenType.TILDE) {
+ Token operator = getAndAdvance();
+ if (_matchesKeyword(Keyword.SUPER)) {
+ TokenType nextType = _peek().type;
+ if (nextType == TokenType.OPEN_SQUARE_BRACKET ||
+ nextType == TokenType.PERIOD) {
+ // "prefixOperator unaryExpression"
+ // --> "prefixOperator postfixExpression"
+ // --> "prefixOperator primary selector*"
+ // --> "prefixOperator 'super' assignableSelector selector*"
+ return new PrefixExpression(operator, parseUnaryExpression());
+ }
+ return new PrefixExpression(
+ operator, new SuperExpression(getAndAdvance()));
+ }
+ return new PrefixExpression(operator, parseUnaryExpression());
+ } else if (_currentToken.type.isIncrementOperator) {
+ Token operator = getAndAdvance();
+ if (_matchesKeyword(Keyword.SUPER)) {
+ TokenType nextType = _peek().type;
+ if (nextType == TokenType.OPEN_SQUARE_BRACKET ||
+ nextType == TokenType.PERIOD) {
+ // --> "prefixOperator 'super' assignableSelector selector*"
+ return new PrefixExpression(operator, parseUnaryExpression());
+ }
+ //
+ // Even though it is not valid to use an incrementing operator
+ // ('++' or '--') before 'super', we can (and therefore must) interpret
+ // "--super" as semantically equivalent to "-(-super)". Unfortunately,
+ // we cannot do the same for "++super" because "+super" is also not
+ // valid.
+ //
+ if (type == TokenType.MINUS_MINUS) {
+ Token firstOperator = _createToken(operator, TokenType.MINUS);
+ Token secondOperator =
+ new Token(TokenType.MINUS, operator.offset + 1);
+ secondOperator.setNext(_currentToken);
+ firstOperator.setNext(secondOperator);
+ operator.previous.setNext(firstOperator);
+ return new PrefixExpression(
+ firstOperator,
+ new PrefixExpression(
+ secondOperator, new SuperExpression(getAndAdvance())));
+ }
+ // Invalid operator before 'super'
+ _reportErrorForCurrentToken(
+ ParserErrorCode.INVALID_OPERATOR_FOR_SUPER, [operator.lexeme]);
+ return new PrefixExpression(
+ operator, new SuperExpression(getAndAdvance()));
+ }
+ return new PrefixExpression(
+ operator, _parseAssignableExpressionNotStartingWithSuper(false));
+ } else if (type == TokenType.PLUS) {
+ _reportErrorForCurrentToken(ParserErrorCode.MISSING_IDENTIFIER);
+ return createSyntheticIdentifier();
+ } else if (_inAsync && _matchesString(_AWAIT)) {
+ return parseAwaitExpression();
+ }
+ return _parsePostfixExpression();
+ }
+
+ /**
+ * Parse a variable declaration. Return the variable declaration that was
+ * parsed.
+ *
+ * variableDeclaration ::=
+ * identifier ('=' expression)?
+ */
+ VariableDeclaration parseVariableDeclaration() {
+ // TODO(paulberry): prior to the fix for bug 23204, we permitted
+ // annotations before variable declarations (e.g. "String @deprecated s;").
+ // Although such constructions are prohibited by the spec, we may want to
+ // consider handling them anyway to allow for better parser recovery in the
+ // event that the user erroneously tries to use them. However, as a
+ // counterargument, this would likely degrade parser recovery in the event
+ // of a construct like "class C { int @deprecated foo() {} }" (i.e. the
+ // user is in the middle of inserting "int bar;" prior to
+ // "@deprecated foo() {}").
+ SimpleIdentifier name = parseSimpleIdentifier(isDeclaration: true);
+ Token equals = null;
+ Expression initializer = null;
+ if (_matches(TokenType.EQ)) {
+ equals = getAndAdvance();
+ initializer = parseExpression2();
+ }
+ return new VariableDeclaration(name, equals, initializer);
+ }
+
+ /**
+ * Parse a variable declaration list. The [commentAndMetadata] is the metadata
+ * to be associated with the variable declaration list. Return the variable
+ * declaration list that was parsed.
+ *
+ * variableDeclarationList ::=
+ * finalConstVarOrType variableDeclaration (',' variableDeclaration)*
+ */
+ VariableDeclarationList parseVariableDeclarationListAfterMetadata(
+ CommentAndMetadata commentAndMetadata) {
+ FinalConstVarOrType holder = parseFinalConstVarOrType(false);
+ return parseVariableDeclarationListAfterType(
+ commentAndMetadata, holder.keyword, holder.type);
+ }
+
+ /**
+ * Parse a variable declaration list. The [commentAndMetadata] is the metadata
+ * to be associated with the variable declaration list, or `null` if there is
+ * no attempt at parsing the comment and metadata. The [keyword] is the token
+ * representing the 'final', 'const' or 'var' keyword, or `null` if there is
+ * no keyword. The [type] is the type of the variables in the list. Return the
+ * variable declaration list that was parsed.
+ *
+ * variableDeclarationList ::=
+ * finalConstVarOrType variableDeclaration (',' variableDeclaration)*
+ */
+ VariableDeclarationList parseVariableDeclarationListAfterType(
+ CommentAndMetadata commentAndMetadata, Token keyword, TypeName type) {
+ if (type != null &&
+ keyword != null &&
+ _tokenMatchesKeyword(keyword, Keyword.VAR)) {
+ _reportErrorForToken(ParserErrorCode.VAR_AND_TYPE, keyword);
+ }
+ List<VariableDeclaration> variables = <VariableDeclaration>[
+ parseVariableDeclaration()
+ ];
+ while (_optional(TokenType.COMMA)) {
+ variables.add(parseVariableDeclaration());
+ }
+ return new VariableDeclarationList(commentAndMetadata?.comment,
+ commentAndMetadata?.metadata, keyword, type, variables);
+ }
+
+ /**
+ * Parse a variable declaration statement. The [commentAndMetadata] is the
+ * metadata to be associated with the variable declaration statement, or
+ * `null` if there is no attempt at parsing the comment and metadata. Return
+ * the variable declaration statement that was parsed.
+ *
+ * variableDeclarationStatement ::=
+ * variableDeclarationList ';'
+ */
+ VariableDeclarationStatement parseVariableDeclarationStatementAfterMetadata(
+ CommentAndMetadata commentAndMetadata) {
+ // Token startToken = currentToken;
+ VariableDeclarationList variableList =
+ parseVariableDeclarationListAfterMetadata(commentAndMetadata);
+// if (!matches(TokenType.SEMICOLON)) {
+// if (matches(startToken, Keyword.VAR) && isTypedIdentifier(startToken.getNext())) {
+// // TODO(brianwilkerson) This appears to be of the form "var type variable". We should do
+// // a better job of recovering in this case.
+// }
+// }
+ Token semicolon = _expect(TokenType.SEMICOLON);
+ return new VariableDeclarationStatement(variableList, semicolon);
+ }
+
+ /**
+ * Parse a while statement. Return the while statement that was parsed.
+ *
+ * This method assumes that the current token matches [Keyword.WHILE].
+ *
+ * whileStatement ::=
+ * 'while' '(' expression ')' statement
+ */
+ Statement parseWhileStatement() {
+ bool wasInLoop = _inLoop;
+ _inLoop = true;
+ try {
+ Token keyword = getAndAdvance();
+ Token leftParenthesis = _expect(TokenType.OPEN_PAREN);
+ Expression condition = parseExpression2();
+ Token rightParenthesis = _expect(TokenType.CLOSE_PAREN);
+ Statement body = parseStatement2();
+ return new WhileStatement(
+ keyword, leftParenthesis, condition, rightParenthesis, body);
+ } finally {
+ _inLoop = wasInLoop;
+ }
+ }
+
+ /**
* Parse a with clause. Return the with clause that was parsed.
*
* This method assumes that the current token matches `Keyword.WITH`.
@@ -2061,14 +4466,201 @@
*/
WithClause parseWithClause() {
Token withKeyword = getAndAdvance();
- List<TypeName> types = <TypeName>[parseTypeName()];
+ List<TypeName> types = <TypeName>[parseTypeName(false)];
while (_optional(TokenType.COMMA)) {
- types.add(parseTypeName());
+ types.add(parseTypeName(false));
}
return new WithClause(withKeyword, types);
}
/**
+ * Parse a yield statement. Return the yield statement that was parsed.
+ *
+ * This method assumes that the current token matches [Keyword.YIELD].
+ *
+ * yieldStatement ::=
+ * 'yield' '*'? expression ';'
+ */
+ YieldStatement parseYieldStatement() {
+ Token yieldToken = getAndAdvance();
+ Token star = null;
+ if (_matches(TokenType.STAR)) {
+ star = getAndAdvance();
+ }
+ Expression expression = parseExpression2();
+ Token semicolon = _expect(TokenType.SEMICOLON);
+ return new YieldStatement(yieldToken, star, expression, semicolon);
+ }
+
+ /**
+ * Parse a prefixed identifier, starting at the [startToken], without actually
+ * creating a prefixed identifier or changing the current token. Return the
+ * token following the prefixed identifier that was parsed, or `null` if the
+ * given token is not the first token in a valid prefixed identifier.
+ *
+ * This method must be kept in sync with [parsePrefixedIdentifier].
+ *
+ * prefixedIdentifier ::=
+ * identifier ('.' identifier)?
+ */
+ Token skipPrefixedIdentifier(Token startToken) {
+ Token token = skipSimpleIdentifier(startToken);
+ if (token == null) {
+ return null;
+ } else if (!_tokenMatches(token, TokenType.PERIOD)) {
+ return token;
+ }
+ token = token.next;
+ Token nextToken = skipSimpleIdentifier(token);
+ if (nextToken != null) {
+ return nextToken;
+ } else if (_tokenMatches(token, TokenType.CLOSE_PAREN) ||
+ _tokenMatches(token, TokenType.COMMA)) {
+ // If the `id.` is followed by something that cannot produce a valid
+ // structure then assume this is a prefixed identifier but missing the
+ // trailing identifier
+ return token;
+ }
+ return null;
+ }
+
+ /**
+ * Parse a return type, starting at the [startToken], without actually
+ * creating a return type or changing the current token. Return the token
+ * following the return type that was parsed, or `null` if the given token is
+ * not the first token in a valid return type.
+ *
+ * This method must be kept in sync with [parseReturnType].
+ *
+ * returnType ::=
+ * 'void'
+ * | type
+ */
+ Token skipReturnType(Token startToken) {
+ if (_tokenMatchesKeyword(startToken, Keyword.VOID)) {
+ return startToken.next;
+ } else {
+ return skipTypeName(startToken);
+ }
+ }
+
+ /**
+ * Parse a simple identifier, starting at the [startToken], without actually
+ * creating a simple identifier or changing the current token. Return the
+ * token following the simple identifier that was parsed, or `null` if the
+ * given token is not the first token in a valid simple identifier.
+ *
+ * This method must be kept in sync with [parseSimpleIdentifier].
+ *
+ * identifier ::=
+ * IDENTIFIER
+ */
+ Token skipSimpleIdentifier(Token startToken) {
+ if (_tokenMatches(startToken, TokenType.IDENTIFIER) ||
+ _tokenMatchesPseudoKeyword(startToken)) {
+ return startToken.next;
+ }
+ return null;
+ }
+
+ /**
+ * Parse a string literal, starting at the [startToken], without actually
+ * creating a string literal or changing the current token. Return the token
+ * following the string literal that was parsed, or `null` if the given token
+ * is not the first token in a valid string literal.
+ *
+ * This method must be kept in sync with [parseStringLiteral].
+ *
+ * stringLiteral ::=
+ * MULTI_LINE_STRING+
+ * | SINGLE_LINE_STRING+
+ */
+ Token skipStringLiteral(Token startToken) {
+ Token token = startToken;
+ while (token != null && _tokenMatches(token, TokenType.STRING)) {
+ token = token.next;
+ TokenType type = token.type;
+ if (type == TokenType.STRING_INTERPOLATION_EXPRESSION ||
+ type == TokenType.STRING_INTERPOLATION_IDENTIFIER) {
+ token = _skipStringInterpolation(token);
+ }
+ }
+ if (identical(token, startToken)) {
+ return null;
+ }
+ return token;
+ }
+
+ /**
+ * Parse a list of type arguments, starting at the [startToken], without
+ * actually creating a type argument list or changing the current token.
+ * Return the token following the type argument list that was parsed, or
+ * `null` if the given token is not the first token in a valid type argument
+ * list.
+ *
+ * This method must be kept in sync with [parseTypeArgumentList].
+ *
+ * typeArguments ::=
+ * '<' typeList '>'
+ *
+ * typeList ::=
+ * type (',' type)*
+ */
+ Token skipTypeArgumentList(Token startToken) {
+ Token token = startToken;
+ if (!_tokenMatches(token, TokenType.LT) &&
+ !_injectGenericCommentTypeList()) {
+ return null;
+ }
+ token = skipTypeName(token.next);
+ if (token == null) {
+ // If the start token '<' is followed by '>'
+ // then assume this should be type argument list but is missing a type
+ token = startToken.next;
+ if (_tokenMatches(token, TokenType.GT)) {
+ return token.next;
+ }
+ return null;
+ }
+ while (_tokenMatches(token, TokenType.COMMA)) {
+ token = skipTypeName(token.next);
+ if (token == null) {
+ return null;
+ }
+ }
+ if (token.type == TokenType.GT) {
+ return token.next;
+ } else if (token.type == TokenType.GT_GT) {
+ Token second = new Token(TokenType.GT, token.offset + 1);
+ second.setNextWithoutSettingPrevious(token.next);
+ return second;
+ }
+ return null;
+ }
+
+ /**
+ * Parse a type name, starting at the [startToken], without actually creating
+ * a type name or changing the current token. Return the token following the
+ * type name that was parsed, or `null` if the given token is not the first
+ * token in a valid type name.
+ *
+ * This method must be kept in sync with [parseTypeName].
+ *
+ * type ::=
+ * qualified typeArguments?
+ */
+ Token skipTypeName(Token startToken) {
+ Token token = skipPrefixedIdentifier(startToken);
+ if (token == null) {
+ return null;
+ }
+ if (_tokenMatches(token, TokenType.LT)) {
+ token = skipTypeArgumentList(token);
+ }
+ return token;
+ }
+
+ /**
* Advance to the next token in the token stream.
*/
void _advance() {
@@ -2099,31 +4691,27 @@
}
/**
- * Return the content of a string with the given literal representation. The
- * [lexeme] is the literal representation of the string. The flag [isFirst] is
- * `true` if this is the first token in a string literal. The flag [isLast] is
- * `true` if this is the last token in a string literal.
+ * Clone all token starting from the given [token] up to the end of the token
+ * stream, and return the first token in the new token stream.
*/
- String _computeStringValue(String lexeme, bool isFirst, bool isLast) {
- StringLexemeHelper helper = new StringLexemeHelper(lexeme, isFirst, isLast);
- int start = helper.start;
- int end = helper.end;
- bool stringEndsAfterStart = end >= start;
- assert(stringEndsAfterStart);
- if (!stringEndsAfterStart) {
- AnalysisEngine.instance.logger.logError(
- "Internal error: computeStringValue($lexeme, $isFirst, $isLast)");
- return "";
+ Token _cloneTokens(Token token) {
+ if (token == null) {
+ return null;
}
- if (helper.isRaw) {
- return lexeme.substring(start, end);
+ token = token is CommentToken ? token.parent : token;
+ Token head = new Token(TokenType.EOF, -1);
+ head.setNext(head);
+ Token current = head;
+ while (token.type != TokenType.EOF) {
+ Token clone = token.copy();
+ current.setNext(clone);
+ current = clone;
+ token = token.next;
}
- StringBuffer buffer = new StringBuffer();
- int index = start;
- while (index < end) {
- index = _translateCharacter(buffer, lexeme, index);
- }
- return buffer.toString();
+ Token tail = new Token(TokenType.EOF, 0);
+ tail.setNext(tail);
+ current.setNext(tail);
+ return head.next;
}
/**
@@ -2179,7 +4767,7 @@
// This looks like the start of a function
return true;
}
- Token token = _skipReturnType(_currentToken);
+ Token token = skipReturnType(_currentToken);
if (token == null) {
return false;
}
@@ -2195,37 +4783,12 @@
}
/**
- * Return a synthetic identifier.
- */
- SimpleIdentifier _createSyntheticIdentifier({bool isDeclaration: false}) {
- Token syntheticToken;
- if (_currentToken.type == TokenType.KEYWORD) {
- // Consider current keyword token as an identifier.
- // It is not always true, e.g. "^is T" where "^" is place the place for
- // synthetic identifier. By creating SyntheticStringToken we can
- // distinguish a real identifier from synthetic. In the code completion
- // behavior will depend on a cursor position - before or on "is".
- syntheticToken = _injectToken(new SyntheticStringToken(
- TokenType.IDENTIFIER, _currentToken.lexeme, _currentToken.offset));
- } else {
- syntheticToken = _createSyntheticToken(TokenType.IDENTIFIER);
- }
- return new SimpleIdentifier(syntheticToken, isDeclaration: isDeclaration);
- }
-
- /**
* Return a synthetic token representing the given [keyword].
*/
Token _createSyntheticKeyword(Keyword keyword) => _injectToken(
new Parser_SyntheticKeywordToken(keyword, _currentToken.offset));
/**
- * Return a synthetic string literal.
- */
- SimpleStringLiteral _createSyntheticStringLiteral() =>
- new SimpleStringLiteral(_createSyntheticToken(TokenType.STRING), "");
-
- /**
* Return a synthetic token with the given [type].
*/
Token _createSyntheticToken(TokenType type) =>
@@ -2495,75 +5058,20 @@
}
/**
- * Return `true` if the current token appears to be the beginning of a
- * function declaration.
+ * Return `true` if the current token could be the question mark in a
+ * condition expression. The current token is assumed to be a question mark.
*/
- bool _isFunctionDeclaration() {
- Keyword keyword = _currentToken.keyword;
- if (keyword == Keyword.VOID) {
- return true;
+ bool _isConditionalOperator() {
+ void parseOperation(Parser parser) {
+ parser.parseExpressionWithoutCascade();
}
- Token afterReturnType = _skipTypeName(_currentToken);
- if (afterReturnType == null) {
- // There was no return type, but it is optional, so go back to where we
- // started.
- afterReturnType = _currentToken;
- }
- Token afterIdentifier = _skipSimpleIdentifier(afterReturnType);
- if (afterIdentifier == null) {
- // It's possible that we parsed the function name as if it were a type
- // name, so see whether it makes sense if we assume that there is no type.
- afterIdentifier = _skipSimpleIdentifier(_currentToken);
- }
- if (afterIdentifier == null) {
- return false;
- }
- if (_isFunctionExpression(afterIdentifier)) {
- return true;
- }
- // It's possible that we have found a getter. While this isn't valid at this
- // point we test for it in order to recover better.
- if (keyword == Keyword.GET) {
- Token afterName = _skipSimpleIdentifier(_currentToken.next);
- if (afterName == null) {
- return false;
- }
- TokenType type = afterName.type;
- return type == TokenType.FUNCTION || type == TokenType.OPEN_CURLY_BRACKET;
- } else if (_tokenMatchesKeyword(afterReturnType, Keyword.GET)) {
- Token afterName = _skipSimpleIdentifier(afterReturnType.next);
- if (afterName == null) {
- return false;
- }
- TokenType type = afterName.type;
- return type == TokenType.FUNCTION || type == TokenType.OPEN_CURLY_BRACKET;
- }
- return false;
- }
- /**
- * Return `true` if the given [token] appears to be the beginning of a
- * function expression.
- */
- bool _isFunctionExpression(Token token) {
- // Function expressions aren't allowed in initializer lists.
- if (_inInitializer) {
+ Token token = _skip(_currentToken.next, parseOperation);
+ if (token == null || !_tokenMatches(token, TokenType.COLON)) {
return false;
}
- Token afterTypeParameters = _skipTypeParameterList(token);
- if (afterTypeParameters == null) {
- afterTypeParameters = token;
- }
- Token afterParameters = _skipFormalParameterList(afterTypeParameters);
- if (afterParameters == null) {
- return false;
- }
- if (afterParameters.matchesAny(
- const <TokenType>[TokenType.OPEN_CURLY_BRACKET, TokenType.FUNCTION])) {
- return true;
- }
- String lexeme = afterParameters.lexeme;
- return lexeme == ASYNC || lexeme == SYNC;
+ token = _skip(token.next, parseOperation);
+ return token != null;
}
/**
@@ -2574,95 +5082,6 @@
(0x41 <= character && character <= 0x46) ||
(0x61 <= character && character <= 0x66);
- /**
- * Return `true` if the current token is the first token in an initialized
- * variable declaration rather than an expression. This method assumes that we
- * have already skipped past any metadata that might be associated with the
- * declaration.
- *
- * initializedVariableDeclaration ::=
- * declaredIdentifier ('=' expression)? (',' initializedIdentifier)*
- *
- * declaredIdentifier ::=
- * metadata finalConstVarOrType identifier
- *
- * finalConstVarOrType ::=
- * 'final' type?
- * | 'const' type?
- * | 'var'
- * | type
- *
- * type ::=
- * qualified typeArguments?
- *
- * initializedIdentifier ::=
- * identifier ('=' expression)?
- */
- bool _isInitializedVariableDeclaration() {
- Keyword keyword = _currentToken.keyword;
- if (keyword == Keyword.FINAL || keyword == Keyword.VAR) {
- // An expression cannot start with a keyword other than 'const',
- // 'rethrow', or 'throw'.
- return true;
- }
- if (keyword == Keyword.CONST) {
- // Look to see whether we might be at the start of a list or map literal,
- // otherwise this should be the start of a variable declaration.
- return !_peek().matchesAny(const <TokenType>[
- TokenType.LT,
- TokenType.OPEN_CURLY_BRACKET,
- TokenType.OPEN_SQUARE_BRACKET,
- TokenType.INDEX
- ]);
- }
- bool allowAdditionalTokens = true;
- // We know that we have an identifier, and need to see whether it might be
- // a type name.
- if (_currentToken.type != TokenType.IDENTIFIER) {
- allowAdditionalTokens = false;
- }
- Token token = _skipTypeName(_currentToken);
- if (token == null) {
- // There was no type name, so this can't be a declaration.
- return false;
- }
- if (token.type != TokenType.IDENTIFIER) {
- allowAdditionalTokens = false;
- }
- token = _skipSimpleIdentifier(token);
- if (token == null) {
- return false;
- }
- TokenType type = token.type;
- // Usual cases in valid code:
- // String v = '';
- // String v, v2;
- // String v;
- // for (String item in items) {}
- if (type == TokenType.EQ ||
- type == TokenType.COMMA ||
- type == TokenType.SEMICOLON ||
- token.keyword == Keyword.IN) {
- return true;
- }
- // It is OK to parse as a variable declaration in these cases:
- // String v }
- // String v if (true) print('OK');
- // String v { print(42); }
- // ...but not in these cases:
- // get getterName {
- // String get getterName
- if (allowAdditionalTokens) {
- if (type == TokenType.CLOSE_CURLY_BRACKET ||
- type == TokenType.KEYWORD ||
- type == TokenType.IDENTIFIER ||
- type == TokenType.OPEN_CURLY_BRACKET) {
- return true;
- }
- }
- return false;
- }
-
bool _isLikelyArgumentList() {
// Try to reduce the amount of lookahead required here before enabling
// generic methods.
@@ -2672,7 +5091,7 @@
if (!parseGenericMethods) {
return false;
}
- Token token = _skipTypeArgumentList(_currentToken);
+ Token token = skipTypeArgumentList(_currentToken);
return token != null && _tokenMatches(token, TokenType.OPEN_PAREN);
}
@@ -2738,25 +5157,11 @@
}
/**
- * Return `true` if the current token appears to be the beginning of a switch
- * member.
- */
- bool _isSwitchMember() {
- Token token = _currentToken;
- while (_tokenMatches(token, TokenType.IDENTIFIER) &&
- _tokenMatches(token.next, TokenType.COLON)) {
- token = token.next.next;
- }
- Keyword keyword = token.keyword;
- return keyword == Keyword.CASE || keyword == Keyword.DEFAULT;
- }
-
- /**
* Return `true` if the [startToken] appears to be the first token of a type
* name that is followed by a variable or field formal parameter.
*/
bool _isTypedIdentifier(Token startToken) {
- Token token = _skipReturnType(startToken);
+ Token token = skipReturnType(startToken);
if (token == null) {
return false;
} else if (_tokenMatchesIdentifier(token)) {
@@ -2868,29 +5273,6 @@
}
/**
- * Parse an additive expression. Return the additive expression that was
- * parsed.
- *
- * additiveExpression ::=
- * multiplicativeExpression (additiveOperator multiplicativeExpression)*
- * | 'super' (additiveOperator multiplicativeExpression)+
- */
- Expression _parseAdditiveExpression() {
- Expression expression;
- if (_currentToken.keyword == Keyword.SUPER &&
- _currentToken.next.type.isAdditiveOperator) {
- expression = new SuperExpression(getAndAdvance());
- } else {
- expression = _parseMultiplicativeExpression();
- }
- while (_currentToken.type.isAdditiveOperator) {
- expression = new BinaryExpression(
- expression, getAndAdvance(), _parseMultiplicativeExpression());
- }
- return expression;
- }
-
- /**
* Parse an argument list when we need to check for an open paren and recover
* when there isn't one. Return the argument list that was parsed.
*/
@@ -2932,49 +5314,6 @@
}
/**
- * Parse an assert statement. Return the assert statement.
- *
- * This method assumes that the current token matches `Keyword.ASSERT`.
- *
- * assertStatement ::=
- * 'assert' '(' expression [',' expression] ')' ';'
- */
- AssertStatement _parseAssertStatement() {
- Token keyword = getAndAdvance();
- Token leftParen = _expect(TokenType.OPEN_PAREN);
- Expression expression = parseExpression2();
- Token comma;
- Expression message;
- if (_matches(TokenType.COMMA)) {
- comma = getAndAdvance();
- message = parseExpression2();
- }
- Token rightParen = _expect(TokenType.CLOSE_PAREN);
- Token semicolon = _expect(TokenType.SEMICOLON);
- return new AssertStatement(
- keyword, leftParen, expression, comma, message, rightParen, semicolon);
- }
-
- /**
- * Parse an assignable expression. The [primaryAllowed] is `true` if the
- * expression is allowed to be a primary without any assignable selector.
- * Return the assignable expression that was parsed.
- *
- * assignableExpression ::=
- * primary (arguments* assignableSelector)+
- * | 'super' unconditionalAssignableSelector
- * | identifier
- */
- Expression _parseAssignableExpression(bool primaryAllowed) {
- if (_matchesKeyword(Keyword.SUPER)) {
- return _parseAssignableSelector(
- new SuperExpression(getAndAdvance()), false,
- allowConditional: false);
- }
- return _parseAssignableExpressionNotStartingWithSuper(primaryAllowed);
- }
-
- /**
* Parse an assignable expression given that the current token is not 'super'.
* The [primaryAllowed] is `true` if the expression is allowed to be a primary
* without any assignable selector. Return the assignable expression that was
@@ -2987,7 +5326,7 @@
// ambiguity by determining whether the primary consists of anything other
// than an identifier and/or is followed by an assignableSelector.
//
- Expression expression = _parsePrimaryExpression();
+ Expression expression = parsePrimaryExpression();
bool isOptional = primaryAllowed || expression is SimpleIdentifier;
while (true) {
while (_isLikelyArgumentList()) {
@@ -3086,66 +5425,6 @@
}
/**
- * Parse a await expression. Return the await expression that was parsed.
- *
- * This method assumes that the current token matches `_AWAIT`.
- *
- * awaitExpression ::=
- * 'await' unaryExpression
- */
- AwaitExpression _parseAwaitExpression() {
- Token awaitToken = getAndAdvance();
- Expression expression = _parseUnaryExpression();
- return new AwaitExpression(awaitToken, expression);
- }
-
- /**
- * Parse a bitwise and expression. Return the bitwise and expression that was
- * parsed.
- *
- * bitwiseAndExpression ::=
- * shiftExpression ('&' shiftExpression)*
- * | 'super' ('&' shiftExpression)+
- */
- Expression _parseBitwiseAndExpression() {
- Expression expression;
- if (_currentToken.keyword == Keyword.SUPER &&
- _currentToken.next.type == TokenType.AMPERSAND) {
- expression = new SuperExpression(getAndAdvance());
- } else {
- expression = _parseShiftExpression();
- }
- while (_currentToken.type == TokenType.AMPERSAND) {
- expression = new BinaryExpression(
- expression, getAndAdvance(), _parseShiftExpression());
- }
- return expression;
- }
-
- /**
- * Parse a bitwise exclusive-or expression. Return the bitwise exclusive-or
- * expression that was parsed.
- *
- * bitwiseXorExpression ::=
- * bitwiseAndExpression ('^' bitwiseAndExpression)*
- * | 'super' ('^' bitwiseAndExpression)+
- */
- Expression _parseBitwiseXorExpression() {
- Expression expression;
- if (_currentToken.keyword == Keyword.SUPER &&
- _currentToken.next.type == TokenType.CARET) {
- expression = new SuperExpression(getAndAdvance());
- } else {
- expression = _parseBitwiseAndExpression();
- }
- while (_currentToken.type == TokenType.CARET) {
- expression = new BinaryExpression(
- expression, getAndAdvance(), _parseBitwiseAndExpression());
- }
- return expression;
- }
-
- /**
* Parse a block when we need to check for an open curly brace and recover
* when there isn't one. Return the block that was parsed.
*
@@ -3166,259 +5445,6 @@
}
/**
- * Parse a break statement. Return the break statement that was parsed.
- *
- * This method assumes that the current token matches `Keyword.BREAK`.
- *
- * breakStatement ::=
- * 'break' identifier? ';'
- */
- Statement _parseBreakStatement() {
- Token breakKeyword = getAndAdvance();
- SimpleIdentifier label = null;
- if (_matchesIdentifier()) {
- label = _parseSimpleIdentifierUnchecked();
- }
- if (!_inLoop && !_inSwitch && label == null) {
- _reportErrorForToken(ParserErrorCode.BREAK_OUTSIDE_OF_LOOP, breakKeyword);
- }
- Token semicolon = _expect(TokenType.SEMICOLON);
- return new BreakStatement(breakKeyword, label, semicolon);
- }
-
- /**
- * Parse a cascade section. Return the expression representing the cascaded
- * method invocation.
- *
- * This method assumes that the current token matches
- * `TokenType.PERIOD_PERIOD`.
- *
- * cascadeSection ::=
- * '..' (cascadeSelector typeArguments? arguments*)
- * (assignableSelector typeArguments? arguments*)* cascadeAssignment?
- *
- * cascadeSelector ::=
- * '[' expression ']'
- * | identifier
- *
- * cascadeAssignment ::=
- * assignmentOperator expressionWithoutCascade
- */
- Expression _parseCascadeSection() {
- Token period = getAndAdvance();
- Expression expression = null;
- SimpleIdentifier functionName = null;
- if (_matchesIdentifier()) {
- functionName = _parseSimpleIdentifierUnchecked();
- } else if (_currentToken.type == TokenType.OPEN_SQUARE_BRACKET) {
- Token leftBracket = getAndAdvance();
- bool wasInInitializer = _inInitializer;
- _inInitializer = false;
- try {
- Expression index = parseExpression2();
- Token rightBracket = _expect(TokenType.CLOSE_SQUARE_BRACKET);
- expression = new IndexExpression.forCascade(
- period, leftBracket, index, rightBracket);
- period = null;
- } finally {
- _inInitializer = wasInInitializer;
- }
- } else {
- _reportErrorForToken(ParserErrorCode.MISSING_IDENTIFIER, _currentToken,
- [_currentToken.lexeme]);
- functionName = _createSyntheticIdentifier();
- }
- assert((expression == null && functionName != null) ||
- (expression != null && functionName == null));
- if (_isLikelyArgumentList()) {
- do {
- TypeArgumentList typeArguments = _parseOptionalTypeArguments();
- if (functionName != null) {
- expression = new MethodInvocation(expression, period, functionName,
- typeArguments, parseArgumentList());
- period = null;
- functionName = null;
- } else if (expression == null) {
- // It should not be possible to get here.
- expression = new MethodInvocation(expression, period,
- _createSyntheticIdentifier(), typeArguments, parseArgumentList());
- } else {
- expression = new FunctionExpressionInvocation(
- expression, typeArguments, parseArgumentList());
- }
- } while (_isLikelyArgumentList());
- } else if (functionName != null) {
- expression = new PropertyAccess(expression, period, functionName);
- period = null;
- }
- assert(expression != null);
- bool progress = true;
- while (progress) {
- progress = false;
- Expression selector = _parseAssignableSelector(expression, true);
- if (!identical(selector, expression)) {
- expression = selector;
- progress = true;
- while (_isLikelyArgumentList()) {
- TypeArgumentList typeArguments = _parseOptionalTypeArguments();
- Expression currentExpression = expression;
- if (currentExpression is PropertyAccess) {
- expression = new MethodInvocation(
- currentExpression.target,
- currentExpression.operator,
- currentExpression.propertyName,
- typeArguments,
- parseArgumentList());
- } else {
- expression = new FunctionExpressionInvocation(
- expression, typeArguments, parseArgumentList());
- }
- }
- }
- }
- if (_currentToken.type.isAssignmentOperator) {
- Token operator = getAndAdvance();
- _ensureAssignable(expression);
- expression = new AssignmentExpression(
- expression, operator, parseExpressionWithoutCascade());
- }
- return expression;
- }
-
- /**
- * Parse a class declaration. The [commentAndMetadata] is the metadata to be
- * associated with the member. The [abstractKeyword] is the token for the
- * keyword 'abstract', or `null` if the keyword was not given. Return the
- * class declaration that was parsed.
- *
- * This method assumes that the current token matches `Keyword.CLASS`.
- *
- * classDeclaration ::=
- * metadata 'abstract'? 'class' name typeParameterList? (extendsClause withClause?)? implementsClause? '{' classMembers '}' |
- * metadata 'abstract'? 'class' mixinApplicationClass
- */
- CompilationUnitMember _parseClassDeclaration(
- CommentAndMetadata commentAndMetadata, Token abstractKeyword) {
- //
- // Parse the name and type parameters.
- //
- Token keyword = getAndAdvance();
- SimpleIdentifier name = parseSimpleIdentifier(isDeclaration: true);
- String className = name.name;
- TypeParameterList typeParameters = null;
- TokenType type = _currentToken.type;
- if (type == TokenType.LT) {
- typeParameters = parseTypeParameterList();
- type = _currentToken.type;
- }
- //
- // Check to see whether this might be a class type alias rather than a class
- // declaration.
- //
- if (type == TokenType.EQ) {
- return _parseClassTypeAliasAfterName(
- commentAndMetadata, abstractKeyword, keyword, name, typeParameters);
- }
- //
- // Parse the clauses. The parser accepts clauses in any order, but will
- // generate errors if they are not in the order required by the
- // specification.
- //
- ExtendsClause extendsClause = null;
- WithClause withClause = null;
- ImplementsClause implementsClause = null;
- bool foundClause = true;
- while (foundClause) {
- Keyword keyword = _currentToken.keyword;
- if (keyword == Keyword.EXTENDS) {
- if (extendsClause == null) {
- extendsClause = parseExtendsClause();
- if (withClause != null) {
- _reportErrorForToken(
- ParserErrorCode.WITH_BEFORE_EXTENDS, withClause.withKeyword);
- } else if (implementsClause != null) {
- _reportErrorForToken(ParserErrorCode.IMPLEMENTS_BEFORE_EXTENDS,
- implementsClause.implementsKeyword);
- }
- } else {
- _reportErrorForToken(ParserErrorCode.MULTIPLE_EXTENDS_CLAUSES,
- extendsClause.extendsKeyword);
- parseExtendsClause();
- }
- } else if (keyword == Keyword.WITH) {
- if (withClause == null) {
- withClause = parseWithClause();
- if (implementsClause != null) {
- _reportErrorForToken(ParserErrorCode.IMPLEMENTS_BEFORE_WITH,
- implementsClause.implementsKeyword);
- }
- } else {
- _reportErrorForToken(
- ParserErrorCode.MULTIPLE_WITH_CLAUSES, withClause.withKeyword);
- parseWithClause();
- // TODO(brianwilkerson) Should we merge the list of applied mixins
- // into a single list?
- }
- } else if (keyword == Keyword.IMPLEMENTS) {
- if (implementsClause == null) {
- implementsClause = parseImplementsClause();
- } else {
- _reportErrorForToken(ParserErrorCode.MULTIPLE_IMPLEMENTS_CLAUSES,
- implementsClause.implementsKeyword);
- parseImplementsClause();
- // TODO(brianwilkerson) Should we merge the list of implemented
- // classes into a single list?
- }
- } else {
- foundClause = false;
- }
- }
- if (withClause != null && extendsClause == null) {
- _reportErrorForToken(
- ParserErrorCode.WITH_WITHOUT_EXTENDS, withClause.withKeyword);
- }
- //
- // Look for and skip over the extra-lingual 'native' specification.
- //
- NativeClause nativeClause = null;
- if (_matchesString(_NATIVE) && _tokenMatches(_peek(), TokenType.STRING)) {
- nativeClause = _parseNativeClause();
- }
- //
- // Parse the body of the class.
- //
- Token leftBracket = null;
- List<ClassMember> members = null;
- Token rightBracket = null;
- if (_matches(TokenType.OPEN_CURLY_BRACKET)) {
- leftBracket = getAndAdvance();
- members = _parseClassMembers(className, _getEndToken(leftBracket));
- rightBracket = _expect(TokenType.CLOSE_CURLY_BRACKET);
- } else {
- // Recovery: Check for an unmatched closing curly bracket and parse
- // members until it is reached.
- leftBracket = _createSyntheticToken(TokenType.OPEN_CURLY_BRACKET);
- rightBracket = _createSyntheticToken(TokenType.CLOSE_CURLY_BRACKET);
- _reportErrorForCurrentToken(ParserErrorCode.MISSING_CLASS_BODY);
- }
- ClassDeclaration classDeclaration = new ClassDeclaration(
- commentAndMetadata.comment,
- commentAndMetadata.metadata,
- abstractKeyword,
- keyword,
- name,
- typeParameters,
- extendsClause,
- withClause,
- implementsClause,
- leftBracket,
- members,
- rightBracket);
- classDeclaration.nativeClause = nativeClause;
- return classDeclaration;
- }
-
- /**
* Parse a list of class members. The [className] is the name of the class
* whose members are being parsed. The [closingBracket] is the closing bracket
* for the class, or `null` if the closing bracket is missing. Return the list
@@ -3462,32 +5488,6 @@
* Parse a class type alias. The [commentAndMetadata] is the metadata to be
* associated with the member. The [abstractKeyword] is the token representing
* the 'abstract' keyword. The [classKeyword] is the token representing the
- * 'class' keyword. Return the class type alias that was parsed.
- *
- * This method assumes that the current token matches an identifier.
- *
- * classTypeAlias ::=
- * identifier typeParameters? '=' 'abstract'? mixinApplication
- *
- * mixinApplication ::=
- * type withClause implementsClause? ';'
- */
- ClassTypeAlias _parseClassTypeAlias(CommentAndMetadata commentAndMetadata,
- Token abstractKeyword, Token classKeyword) {
- SimpleIdentifier className =
- _parseSimpleIdentifierUnchecked(isDeclaration: true);
- TypeParameterList typeParameters = null;
- if (_matches(TokenType.LT)) {
- typeParameters = parseTypeParameterList();
- }
- return _parseClassTypeAliasAfterName(commentAndMetadata, abstractKeyword,
- classKeyword, className, typeParameters);
- }
-
- /**
- * Parse a class type alias. The [commentAndMetadata] is the metadata to be
- * associated with the member. The [abstractKeyword] is the token representing
- * the 'abstract' keyword. The [classKeyword] is the token representing the
* 'class' keyword. The [className] is the name of the alias, and the
* [typeParameters] are the type parameters following the name. Return the
* class type alias that was parsed.
@@ -3505,7 +5505,7 @@
SimpleIdentifier className,
TypeParameterList typeParameters) {
Token equals = _expect(TokenType.EQ);
- TypeName superclass = parseTypeName();
+ TypeName superclass = parseTypeName(false);
WithClause withClause = null;
if (_matchesKeyword(Keyword.WITH)) {
withClause = parseWithClause();
@@ -3548,162 +5548,6 @@
}
/**
- * Parse a list of combinators in a directive. Return the combinators that
- * were parsed, or `null` if there are no combinators.
- *
- * combinator ::=
- * 'show' identifier (',' identifier)*
- * | 'hide' identifier (',' identifier)*
- */
- List<Combinator> _parseCombinators() {
- List<Combinator> combinators = null;
- while (true) {
- Combinator combinator = parseCombinator();
- if (combinator == null) {
- break;
- }
- combinators ??= <Combinator>[];
- combinators.add(combinator);
- }
- return combinators;
- }
-
- /**
- * Parse the documentation comment and metadata preceding a declaration. This
- * method allows any number of documentation comments to occur before, after
- * or between the metadata, but only returns the last (right-most)
- * documentation comment that is found. Return the documentation comment and
- * metadata that were parsed.
- *
- * metadata ::=
- * annotation*
- */
- CommentAndMetadata _parseCommentAndMetadata() {
- // TODO(brianwilkerson) Consider making the creation of documentation
- // comments be lazy.
- List<DocumentationCommentToken> tokens = _parseDocumentationCommentTokens();
- List<Annotation> metadata = null;
- while (_matches(TokenType.AT)) {
- metadata ??= <Annotation>[];
- metadata.add(parseAnnotation());
- List<DocumentationCommentToken> optionalTokens =
- _parseDocumentationCommentTokens();
- if (optionalTokens != null) {
- tokens = optionalTokens;
- }
- }
- return new CommentAndMetadata(_parseDocumentationComment(tokens), metadata);
- }
-
- /**
- * Parse a comment reference from the source between square brackets. The
- * [referenceSource] is the source occurring between the square brackets
- * within a documentation comment. The [sourceOffset] is the offset of the
- * first character of the reference source. Return the comment reference that
- * was parsed, or `null` if no reference could be found.
- *
- * commentReference ::=
- * 'new'? prefixedIdentifier
- */
- CommentReference _parseCommentReference(
- String referenceSource, int sourceOffset) {
- // TODO(brianwilkerson) The errors are not getting the right offset/length
- // and are being duplicated.
- try {
- BooleanErrorListener listener = new BooleanErrorListener();
- Scanner scanner = new Scanner(
- null, new SubSequenceReader(referenceSource, sourceOffset), listener);
- scanner.setSourceStart(1, 1);
- Token firstToken = scanner.tokenize();
- if (listener.errorReported) {
- return null;
- }
- if (firstToken.type == TokenType.EOF) {
- Token syntheticToken =
- new SyntheticStringToken(TokenType.IDENTIFIER, "", sourceOffset);
- syntheticToken.setNext(firstToken);
- return new CommentReference(null, new SimpleIdentifier(syntheticToken));
- }
- Token newKeyword = null;
- if (_tokenMatchesKeyword(firstToken, Keyword.NEW)) {
- newKeyword = firstToken;
- firstToken = firstToken.next;
- }
- if (firstToken.isUserDefinableOperator) {
- if (firstToken.next.type != TokenType.EOF) {
- return null;
- }
- Identifier identifier = new SimpleIdentifier(firstToken);
- return new CommentReference(null, identifier);
- } else if (_tokenMatchesKeyword(firstToken, Keyword.OPERATOR)) {
- Token secondToken = firstToken.next;
- if (secondToken.isUserDefinableOperator) {
- if (secondToken.next.type != TokenType.EOF) {
- return null;
- }
- Identifier identifier = new SimpleIdentifier(secondToken);
- return new CommentReference(null, identifier);
- }
- return null;
- } else if (_tokenMatchesIdentifier(firstToken)) {
- Token secondToken = firstToken.next;
- Token thirdToken = secondToken.next;
- Token nextToken;
- Identifier identifier;
- if (_tokenMatches(secondToken, TokenType.PERIOD)) {
- if (thirdToken.isUserDefinableOperator) {
- identifier = new PrefixedIdentifier(
- new SimpleIdentifier(firstToken),
- secondToken,
- new SimpleIdentifier(thirdToken));
- nextToken = thirdToken.next;
- } else if (_tokenMatchesKeyword(thirdToken, Keyword.OPERATOR)) {
- Token fourthToken = thirdToken.next;
- if (fourthToken.isUserDefinableOperator) {
- identifier = new PrefixedIdentifier(
- new SimpleIdentifier(firstToken),
- secondToken,
- new SimpleIdentifier(fourthToken));
- nextToken = fourthToken.next;
- } else {
- return null;
- }
- } else if (_tokenMatchesIdentifier(thirdToken)) {
- identifier = new PrefixedIdentifier(
- new SimpleIdentifier(firstToken),
- secondToken,
- new SimpleIdentifier(thirdToken));
- nextToken = thirdToken.next;
- }
- } else {
- identifier = new SimpleIdentifier(firstToken);
- nextToken = firstToken.next;
- }
- if (nextToken.type != TokenType.EOF) {
- return null;
- }
- return new CommentReference(newKeyword, identifier);
- } else {
- Keyword keyword = firstToken.keyword;
- if (keyword == Keyword.THIS ||
- keyword == Keyword.NULL ||
- keyword == Keyword.TRUE ||
- keyword == Keyword.FALSE) {
- // TODO(brianwilkerson) If we want to support this we will need to
- // extend the definition of CommentReference to take an expression
- // rather than an identifier. For now we just ignore it to reduce the
- // number of errors produced, but that's probably not a valid long term
- // approach.
- return null;
- }
- }
- } catch (exception) {
- // Ignored because we assume that it wasn't a real comment reference.
- }
- return null;
- }
-
- /**
* Parse all of the comment references occurring in the given array of
* documentation comments. The [tokens] are the comment tokens representing
* the documentation comments to be parsed. Return the comment references that
@@ -3749,7 +5593,7 @@
// TODO(brianwilkerson) Handle the case where there's a library
// URI in the link text.
} else {
- CommentReference reference = _parseCommentReference(
+ CommentReference reference = parseCommentReference(
comment.substring(leftIndex + 1, rightIndex), nameOffset);
if (reference != null) {
references.add(reference);
@@ -3788,249 +5632,6 @@
}
/**
- * Parse a compilation unit member. The [commentAndMetadata] is the metadata
- * to be associated with the member. Return the compilation unit member that
- * was parsed, or `null` if what was parsed could not be represented as a
- * compilation unit member.
- *
- * compilationUnitMember ::=
- * classDefinition
- * | functionTypeAlias
- * | external functionSignature
- * | external getterSignature
- * | external setterSignature
- * | functionSignature functionBody
- * | returnType? getOrSet identifier formalParameterList functionBody
- * | (final | const) type? staticFinalDeclarationList ';'
- * | variableDeclaration ';'
- */
- CompilationUnitMember _parseCompilationUnitMember(
- CommentAndMetadata commentAndMetadata) {
- Modifiers modifiers = _parseModifiers();
- Keyword keyword = _currentToken.keyword;
- if (keyword == Keyword.CLASS) {
- return _parseClassDeclaration(
- commentAndMetadata, _validateModifiersForClass(modifiers));
- }
- Token next = _peek();
- TokenType nextType = next.type;
- if (keyword == Keyword.TYPEDEF &&
- nextType != TokenType.PERIOD &&
- nextType != TokenType.LT &&
- nextType != TokenType.OPEN_PAREN) {
- _validateModifiersForTypedef(modifiers);
- return _parseTypeAlias(commentAndMetadata);
- } else if (keyword == Keyword.ENUM) {
- _validateModifiersForEnum(modifiers);
- return _parseEnumDeclaration(commentAndMetadata);
- } else if (keyword == Keyword.VOID) {
- TypeName returnType =
- new TypeName(new SimpleIdentifier(getAndAdvance()), null);
- keyword = _currentToken.keyword;
- next = _peek();
- if ((keyword == Keyword.GET || keyword == Keyword.SET) &&
- _tokenMatchesIdentifier(next)) {
- _validateModifiersForTopLevelFunction(modifiers);
- return _parseFunctionDeclaration(
- commentAndMetadata, modifiers.externalKeyword, returnType);
- } else if (keyword == Keyword.OPERATOR && _isOperator(next)) {
- _reportErrorForToken(ParserErrorCode.TOP_LEVEL_OPERATOR, _currentToken);
- return _convertToFunctionDeclaration(_parseOperatorAfterKeyword(
- commentAndMetadata,
- modifiers.externalKeyword,
- returnType,
- getAndAdvance()));
- } else if (_matchesIdentifier() &&
- next.matchesAny(const <TokenType>[
- TokenType.OPEN_PAREN,
- TokenType.OPEN_CURLY_BRACKET,
- TokenType.FUNCTION,
- TokenType.LT
- ])) {
- _validateModifiersForTopLevelFunction(modifiers);
- return _parseFunctionDeclaration(
- commentAndMetadata, modifiers.externalKeyword, returnType);
- } else {
- //
- // We have found an error of some kind. Try to recover.
- //
- if (_matchesIdentifier()) {
- if (next.matchesAny(const <TokenType>[
- TokenType.EQ,
- TokenType.COMMA,
- TokenType.SEMICOLON
- ])) {
- //
- // We appear to have a variable declaration with a type of "void".
- //
- _reportErrorForNode(ParserErrorCode.VOID_VARIABLE, returnType);
- return new TopLevelVariableDeclaration(
- commentAndMetadata.comment,
- commentAndMetadata.metadata,
- _parseVariableDeclarationListAfterType(null,
- _validateModifiersForTopLevelVariable(modifiers), null),
- _expect(TokenType.SEMICOLON));
- }
- }
- _reportErrorForToken(
- ParserErrorCode.EXPECTED_EXECUTABLE, _currentToken);
- return null;
- }
- } else if ((keyword == Keyword.GET || keyword == Keyword.SET) &&
- _tokenMatchesIdentifier(next)) {
- _validateModifiersForTopLevelFunction(modifiers);
- return _parseFunctionDeclaration(
- commentAndMetadata, modifiers.externalKeyword, null);
- } else if (keyword == Keyword.OPERATOR && _isOperator(next)) {
- _reportErrorForToken(ParserErrorCode.TOP_LEVEL_OPERATOR, _currentToken);
- return _convertToFunctionDeclaration(_parseOperatorAfterKeyword(
- commentAndMetadata,
- modifiers.externalKeyword,
- null,
- getAndAdvance()));
- } else if (!_matchesIdentifier()) {
- Token keyword = modifiers.varKeyword;
- if (keyword == null) {
- keyword = modifiers.finalKeyword;
- }
- if (keyword == null) {
- keyword = modifiers.constKeyword;
- }
- if (keyword != null) {
- //
- // We appear to have found an incomplete top-level variable declaration.
- //
- _reportErrorForCurrentToken(ParserErrorCode.MISSING_IDENTIFIER);
- VariableDeclaration variable =
- new VariableDeclaration(_createSyntheticIdentifier(), null, null);
- List<VariableDeclaration> variables = <VariableDeclaration>[variable];
- return new TopLevelVariableDeclaration(
- commentAndMetadata.comment,
- commentAndMetadata.metadata,
- new VariableDeclarationList(null, null, keyword, null, variables),
- _expect(TokenType.SEMICOLON));
- }
- _reportErrorForToken(ParserErrorCode.EXPECTED_EXECUTABLE, _currentToken);
- return null;
- } else if (_isPeekGenericTypeParametersAndOpenParen()) {
- return _parseFunctionDeclaration(
- commentAndMetadata, modifiers.externalKeyword, null);
- } else if (_tokenMatches(next, TokenType.OPEN_PAREN)) {
- TypeName returnType = _parseOptionalTypeNameComment();
- _validateModifiersForTopLevelFunction(modifiers);
- return _parseFunctionDeclaration(
- commentAndMetadata, modifiers.externalKeyword, returnType);
- } else if (next.matchesAny(const <TokenType>[
- TokenType.EQ,
- TokenType.COMMA,
- TokenType.SEMICOLON
- ])) {
- if (modifiers.constKeyword == null &&
- modifiers.finalKeyword == null &&
- modifiers.varKeyword == null) {
- _reportErrorForCurrentToken(
- ParserErrorCode.MISSING_CONST_FINAL_VAR_OR_TYPE);
- }
- return new TopLevelVariableDeclaration(
- commentAndMetadata.comment,
- commentAndMetadata.metadata,
- _parseVariableDeclarationListAfterType(
- null, _validateModifiersForTopLevelVariable(modifiers), null),
- _expect(TokenType.SEMICOLON));
- }
- TypeName returnType = parseReturnType();
- keyword = _currentToken.keyword;
- next = _peek();
- if ((keyword == Keyword.GET || keyword == Keyword.SET) &&
- _tokenMatchesIdentifier(next)) {
- _validateModifiersForTopLevelFunction(modifiers);
- return _parseFunctionDeclaration(
- commentAndMetadata, modifiers.externalKeyword, returnType);
- } else if (keyword == Keyword.OPERATOR && _isOperator(next)) {
- _reportErrorForToken(ParserErrorCode.TOP_LEVEL_OPERATOR, _currentToken);
- return _convertToFunctionDeclaration(_parseOperatorAfterKeyword(
- commentAndMetadata,
- modifiers.externalKeyword,
- returnType,
- getAndAdvance()));
- } else if (_matches(TokenType.AT)) {
- return new TopLevelVariableDeclaration(
- commentAndMetadata.comment,
- commentAndMetadata.metadata,
- _parseVariableDeclarationListAfterType(null,
- _validateModifiersForTopLevelVariable(modifiers), returnType),
- _expect(TokenType.SEMICOLON));
- } else if (!_matchesIdentifier()) {
- // TODO(brianwilkerson) Generalize this error. We could also be parsing a
- // top-level variable at this point.
- _reportErrorForToken(ParserErrorCode.EXPECTED_EXECUTABLE, _currentToken);
- Token semicolon;
- if (_matches(TokenType.SEMICOLON)) {
- semicolon = getAndAdvance();
- } else {
- semicolon = _createSyntheticToken(TokenType.SEMICOLON);
- }
- VariableDeclaration variable =
- new VariableDeclaration(_createSyntheticIdentifier(), null, null);
- List<VariableDeclaration> variables = <VariableDeclaration>[variable];
- return new TopLevelVariableDeclaration(
- commentAndMetadata.comment,
- commentAndMetadata.metadata,
- new VariableDeclarationList(null, null, null, returnType, variables),
- semicolon);
- } else if (next.matchesAny(const <TokenType>[
- TokenType.OPEN_PAREN,
- TokenType.FUNCTION,
- TokenType.OPEN_CURLY_BRACKET,
- TokenType.LT
- ])) {
- _validateModifiersForTopLevelFunction(modifiers);
- return _parseFunctionDeclaration(
- commentAndMetadata, modifiers.externalKeyword, returnType);
- }
- return new TopLevelVariableDeclaration(
- commentAndMetadata.comment,
- commentAndMetadata.metadata,
- _parseVariableDeclarationListAfterType(
- null, _validateModifiersForTopLevelVariable(modifiers), returnType),
- _expect(TokenType.SEMICOLON));
- }
-
- /**
- * Parse a configuration in either an import or export directive.
- *
- * This method assumes that the current token matches `Keyword.IF`.
- *
- * configuration ::=
- * 'if' '(' test ')' uri
- *
- * test ::=
- * dottedName ('==' stringLiteral)?
- *
- * dottedName ::=
- * identifier ('.' identifier)*
- */
- Configuration _parseConfiguration() {
- Token ifKeyword = getAndAdvance();
- Token leftParenthesis = _expect(TokenType.OPEN_PAREN);
- DottedName name = _parseDottedName();
- Token equalToken = null;
- StringLiteral value = null;
- if (_matches(TokenType.EQ_EQ)) {
- equalToken = getAndAdvance();
- value = parseStringLiteral();
- if (value is StringInterpolation) {
- _reportErrorForNode(
- ParserErrorCode.INVALID_LITERAL_IN_CONFIGURATION, value);
- }
- }
- Token rightParenthesis = _expect(TokenType.CLOSE_PAREN);
- StringLiteral libraryUri = _parseUri();
- return new Configuration(ifKeyword, leftParenthesis, name, equalToken,
- value, rightParenthesis, libraryUri);
- }
-
- /**
* Parse a list of configurations. Return the configurations that were parsed,
* or `null` if there are no configurations.
*/
@@ -4038,35 +5639,11 @@
List<Configuration> configurations = null;
while (_matchesKeyword(Keyword.IF)) {
configurations ??= <Configuration>[];
- configurations.add(_parseConfiguration());
+ configurations.add(parseConfiguration());
}
return configurations;
}
- /**
- * Parse a const expression. Return the const expression that was parsed.
- *
- * This method assumes that the current token matches `Keyword.CONST`.
- *
- * constExpression ::=
- * instanceCreationExpression
- * | listLiteral
- * | mapLiteral
- */
- Expression _parseConstExpression() {
- Token keyword = getAndAdvance();
- TokenType type = _currentToken.type;
- if (type == TokenType.LT || _injectGenericCommentTypeList()) {
- return _parseListOrMapLiteral(keyword);
- } else if (type == TokenType.OPEN_SQUARE_BRACKET ||
- type == TokenType.INDEX) {
- return _parseListLiteral(keyword, null);
- } else if (type == TokenType.OPEN_CURLY_BRACKET) {
- return _parseMapLiteral(keyword, null);
- }
- return _parseInstanceCreationExpression(keyword);
- }
-
ConstructorDeclaration _parseConstructor(
CommentAndMetadata commentAndMetadata,
Token externalKeyword,
@@ -4097,7 +5674,7 @@
initializers.add(_parseConstructorFieldInitializer(true));
}
} else if (keyword == Keyword.SUPER) {
- initializers.add(_parseSuperConstructorInvocation());
+ initializers.add(parseSuperConstructorInvocation());
} else if (_matches(TokenType.OPEN_CURLY_BRACKET) ||
_matches(TokenType.FUNCTION)) {
_reportErrorForCurrentToken(ParserErrorCode.MISSING_INITIALIZER);
@@ -4125,8 +5702,8 @@
redirectedConstructor);
}
} else {
- body = _parseFunctionBody(
- true, ParserErrorCode.MISSING_FUNCTION_BODY, false);
+ body =
+ parseFunctionBody(true, ParserErrorCode.MISSING_FUNCTION_BODY, false);
if (constKeyword != null &&
factoryKeyword != null &&
externalKeyword == null) {
@@ -4198,7 +5775,7 @@
equals = _createSyntheticToken(TokenType.EQ);
} else {
return new ConstructorFieldInitializer(keywordToken, period, fieldName,
- _createSyntheticToken(TokenType.EQ), _createSyntheticIdentifier());
+ _createSyntheticToken(TokenType.EQ), createSyntheticIdentifier());
}
}
bool wasInInitializer = _inInitializer;
@@ -4208,7 +5785,7 @@
if (_matches(TokenType.PERIOD_PERIOD)) {
List<Expression> cascadeSections = <Expression>[];
do {
- Expression section = _parseCascadeSection();
+ Expression section = parseCascadeSection();
if (section != null) {
cascadeSections.add(section);
}
@@ -4223,32 +5800,6 @@
}
/**
- * Parse a continue statement. Return the continue statement that was parsed.
- *
- * This method assumes that the current token matches `Keyword.CONTINUE`.
- *
- * continueStatement ::=
- * 'continue' identifier? ';'
- */
- Statement _parseContinueStatement() {
- Token continueKeyword = getAndAdvance();
- if (!_inLoop && !_inSwitch) {
- _reportErrorForToken(
- ParserErrorCode.CONTINUE_OUTSIDE_OF_LOOP, continueKeyword);
- }
- SimpleIdentifier label = null;
- if (_matchesIdentifier()) {
- label = _parseSimpleIdentifierUnchecked();
- }
- if (_inSwitch && !_inLoop && label == null) {
- _reportErrorForToken(
- ParserErrorCode.CONTINUE_WITHOUT_LABEL_IN_CASE, continueKeyword);
- }
- Token semicolon = _expect(TokenType.SEMICOLON);
- return new ContinueStatement(continueKeyword, label, semicolon);
- }
-
- /**
* Parse a directive. The [commentAndMetadata] is the metadata to be
* associated with the directive. Return the directive that was parsed.
*
@@ -4276,144 +5827,6 @@
}
/**
- * Parse the script tag and directives in a compilation unit until the first
- * non-directive is encountered. Return the compilation unit that was parsed.
- *
- * compilationUnit ::=
- * scriptTag? directive*
- */
- CompilationUnit _parseDirectives() {
- Token firstToken = _currentToken;
- ScriptTag scriptTag = null;
- if (_matches(TokenType.SCRIPT_TAG)) {
- scriptTag = new ScriptTag(getAndAdvance());
- }
- List<Directive> directives = <Directive>[];
- while (!_matches(TokenType.EOF)) {
- CommentAndMetadata commentAndMetadata = _parseCommentAndMetadata();
- Keyword keyword = _currentToken.keyword;
- TokenType type = _peek().type;
- if ((keyword == Keyword.IMPORT ||
- keyword == Keyword.EXPORT ||
- keyword == Keyword.LIBRARY ||
- keyword == Keyword.PART) &&
- type != TokenType.PERIOD &&
- type != TokenType.LT &&
- type != TokenType.OPEN_PAREN) {
- directives.add(_parseDirective(commentAndMetadata));
- } else if (_matches(TokenType.SEMICOLON)) {
- _advance();
- } else {
- while (!_matches(TokenType.EOF)) {
- _advance();
- }
- return new CompilationUnit(
- firstToken, scriptTag, directives, null, _currentToken);
- }
- }
- return new CompilationUnit(
- firstToken, scriptTag, directives, null, _currentToken);
- }
-
- /**
- * Parse a documentation comment based on the given list of documentation
- * comment tokens. Return the documentation comment that was parsed, or `null`
- * if there was no comment.
- *
- * documentationComment ::=
- * multiLineComment?
- * | singleLineComment*
- */
- Comment _parseDocumentationComment(List<DocumentationCommentToken> tokens) {
- if (tokens == null) {
- return null;
- }
- List<CommentReference> references = _parseCommentReferences(tokens);
- return Comment.createDocumentationCommentWithReferences(tokens, references);
- }
-
- /**
- * Parse a documentation comment. Return the documentation comment that was
- * parsed, or `null` if there was no comment.
- *
- * documentationComment ::=
- * multiLineComment?
- * | singleLineComment*
- */
- List<DocumentationCommentToken> _parseDocumentationCommentTokens() {
- List<DocumentationCommentToken> tokens = <DocumentationCommentToken>[];
- CommentToken commentToken = _currentToken.precedingComments;
- while (commentToken != null) {
- if (commentToken is DocumentationCommentToken) {
- if (tokens.isNotEmpty) {
- if (commentToken.type == TokenType.SINGLE_LINE_COMMENT) {
- if (tokens[0].type != TokenType.SINGLE_LINE_COMMENT) {
- tokens.clear();
- }
- } else {
- tokens.clear();
- }
- }
- tokens.add(commentToken);
- }
- commentToken = commentToken.next;
- }
- return tokens.isEmpty ? null : tokens;
- }
-
- /**
- * Parse a do statement. Return the do statement that was parsed.
- *
- * This method assumes that the current token matches `Keyword.DO`.
- *
- * doStatement ::=
- * 'do' statement 'while' '(' expression ')' ';'
- */
- Statement _parseDoStatement() {
- bool wasInLoop = _inLoop;
- _inLoop = true;
- try {
- Token doKeyword = getAndAdvance();
- Statement body = parseStatement2();
- Token whileKeyword = _expectKeyword(Keyword.WHILE);
- Token leftParenthesis = _expect(TokenType.OPEN_PAREN);
- Expression condition = parseExpression2();
- Token rightParenthesis = _expect(TokenType.CLOSE_PAREN);
- Token semicolon = _expect(TokenType.SEMICOLON);
- return new DoStatement(doKeyword, body, whileKeyword, leftParenthesis,
- condition, rightParenthesis, semicolon);
- } finally {
- _inLoop = wasInLoop;
- }
- }
-
- /**
- * Parse a dotted name. Return the dotted name that was parsed.
- *
- * dottedName ::=
- * identifier ('.' identifier)*
- */
- DottedName _parseDottedName() {
- List<SimpleIdentifier> components = <SimpleIdentifier>[
- parseSimpleIdentifier()
- ];
- while (_optional(TokenType.PERIOD)) {
- components.add(parseSimpleIdentifier());
- }
- return new DottedName(components);
- }
-
- /**
- * Parse an empty statement. Return the empty statement that was parsed.
- *
- * This method assumes that the current token matches `TokenType.SEMICOLON`.
- *
- * emptyStatement ::=
- * ';'
- */
- Statement _parseEmptyStatement() => new EmptyStatement(getAndAdvance());
-
- /**
* Parse an enum constant declaration. Return the enum constant declaration
* that was parsed.
*
@@ -4428,12 +5841,12 @@
* metadata id
*/
EnumConstantDeclaration _parseEnumConstantDeclaration() {
- CommentAndMetadata commentAndMetadata = _parseCommentAndMetadata();
+ CommentAndMetadata commentAndMetadata = parseCommentAndMetadata();
SimpleIdentifier name;
if (_matchesIdentifier()) {
name = _parseSimpleIdentifierUnchecked(isDeclaration: true);
} else {
- name = _createSyntheticIdentifier();
+ name = createSyntheticIdentifier();
}
if (commentAndMetadata.hasMetadata) {
_reportErrorForNode(ParserErrorCode.ANNOTATION_ON_ENUM_CONSTANT,
@@ -4444,55 +5857,6 @@
}
/**
- * Parse an enum declaration. The [commentAndMetadata] is the metadata to be
- * associated with the member. Return the enum declaration that was parsed.
- *
- * This method assumes that the current token matches `Keyword.ENUM`.
- *
- * enumType ::=
- * metadata 'enum' id '{' id (',' id)* (',')? '}'
- */
- EnumDeclaration _parseEnumDeclaration(CommentAndMetadata commentAndMetadata) {
- Token keyword = getAndAdvance();
- SimpleIdentifier name = parseSimpleIdentifier(isDeclaration: true);
- Token leftBracket = null;
- List<EnumConstantDeclaration> constants = <EnumConstantDeclaration>[];
- Token rightBracket = null;
- if (_matches(TokenType.OPEN_CURLY_BRACKET)) {
- leftBracket = getAndAdvance();
- if (_matchesIdentifier() || _matches(TokenType.AT)) {
- constants.add(_parseEnumConstantDeclaration());
- } else if (_matches(TokenType.COMMA) &&
- _tokenMatchesIdentifier(_peek())) {
- constants.add(_parseEnumConstantDeclaration());
- _reportErrorForCurrentToken(ParserErrorCode.MISSING_IDENTIFIER);
- } else {
- constants.add(_parseEnumConstantDeclaration());
- _reportErrorForCurrentToken(ParserErrorCode.EMPTY_ENUM_BODY);
- }
- while (_optional(TokenType.COMMA)) {
- if (_matches(TokenType.CLOSE_CURLY_BRACKET)) {
- break;
- }
- constants.add(_parseEnumConstantDeclaration());
- }
- rightBracket = _expect(TokenType.CLOSE_CURLY_BRACKET);
- } else {
- leftBracket = _createSyntheticToken(TokenType.OPEN_CURLY_BRACKET);
- rightBracket = _createSyntheticToken(TokenType.CLOSE_CURLY_BRACKET);
- _reportErrorForCurrentToken(ParserErrorCode.MISSING_ENUM_BODY);
- }
- return new EnumDeclaration(
- commentAndMetadata.comment,
- commentAndMetadata.metadata,
- keyword,
- name,
- leftBracket,
- constants,
- rightBracket);
- }
-
- /**
* Parse an equality expression. Return the equality expression that was
* parsed.
*
@@ -4506,7 +5870,7 @@
_currentToken.next.type.isEqualityOperator) {
expression = new SuperExpression(getAndAdvance());
} else {
- expression = _parseRelationalExpression();
+ expression = parseRelationalExpression();
}
bool leftEqualityExpression = false;
while (_currentToken.type.isEqualityOperator) {
@@ -4515,7 +5879,7 @@
ParserErrorCode.EQUALITY_CANNOT_BE_EQUALITY_OPERAND, expression);
}
expression = new BinaryExpression(
- expression, getAndAdvance(), _parseRelationalExpression());
+ expression, getAndAdvance(), parseRelationalExpression());
leftEqualityExpression = true;
}
return expression;
@@ -4534,7 +5898,7 @@
Token exportKeyword = getAndAdvance();
StringLiteral libraryUri = _parseUri();
List<Configuration> configurations = _parseConfigurations();
- List<Combinator> combinators = _parseCombinators();
+ List<Combinator> combinators = parseCombinators();
Token semicolon = _expect(TokenType.SEMICOLON);
return new ExportDirective(
commentAndMetadata.comment,
@@ -4547,64 +5911,6 @@
}
/**
- * Parse a list of expressions. Return the expression that was parsed.
- *
- * expressionList ::=
- * expression (',' expression)*
- */
- List<Expression> _parseExpressionList() {
- List<Expression> expressions = <Expression>[parseExpression2()];
- while (_optional(TokenType.COMMA)) {
- expressions.add(parseExpression2());
- }
- return expressions;
- }
-
- /**
- * Parse the 'final', 'const', 'var' or type preceding a variable declaration.
- * The [optional] is `true` if the keyword and type are optional. Return the
- * 'final', 'const', 'var' or type that was parsed.
- *
- * finalConstVarOrType ::=
- * 'final' type?
- * | 'const' type?
- * | 'var'
- * | type
- */
- FinalConstVarOrType _parseFinalConstVarOrType(bool optional) {
- Token keywordToken = null;
- TypeName type = null;
- Keyword keyword = _currentToken.keyword;
- if (keyword == Keyword.FINAL || keyword == Keyword.CONST) {
- keywordToken = getAndAdvance();
- if (_isTypedIdentifier(_currentToken)) {
- type = parseTypeName();
- } else {
- // Support `final/*=T*/ x;`
- type = _parseOptionalTypeNameComment();
- }
- } else if (keyword == Keyword.VAR) {
- keywordToken = getAndAdvance();
- // Support `var/*=T*/ x;`
- type = _parseOptionalTypeNameComment();
- if (type != null) {
- // Clear the keyword to prevent an error.
- keywordToken = null;
- }
- } else if (_isTypedIdentifier(_currentToken)) {
- type = parseReturnType();
- } else if (!optional) {
- _reportErrorForCurrentToken(
- ParserErrorCode.MISSING_CONST_FINAL_VAR_OR_TYPE);
- } else {
- // Support parameters such as `(/*=K*/ key, /*=V*/ value)`
- // This is not supported if the type is required.
- type = _parseOptionalTypeNameComment();
- }
- return new FinalConstVarOrType(keywordToken, type);
- }
-
- /**
* Parse a formal parameter. At most one of `isOptional` and `isNamed` can be
* `true`. The [kind] is the kind of parameter being expected based on the
* presence or absence of group delimiters. Return the formal parameter that
@@ -4820,275 +6126,6 @@
}
/**
- * Parse a for statement. Return the for statement that was parsed.
- *
- * forStatement ::=
- * 'for' '(' forLoopParts ')' statement
- *
- * forLoopParts ::=
- * forInitializerStatement expression? ';' expressionList?
- * | declaredIdentifier 'in' expression
- * | identifier 'in' expression
- *
- * forInitializerStatement ::=
- * localVariableDeclaration ';'
- * | expression? ';'
- */
- Statement _parseForStatement() {
- bool wasInLoop = _inLoop;
- _inLoop = true;
- try {
- Token awaitKeyword = null;
- if (_matchesString(_AWAIT)) {
- awaitKeyword = getAndAdvance();
- }
- Token forKeyword = _expectKeyword(Keyword.FOR);
- Token leftParenthesis = _expect(TokenType.OPEN_PAREN);
- VariableDeclarationList variableList = null;
- Expression initialization = null;
- if (!_matches(TokenType.SEMICOLON)) {
- CommentAndMetadata commentAndMetadata = _parseCommentAndMetadata();
- if (_matchesIdentifier() &&
- (_tokenMatchesKeyword(_peek(), Keyword.IN) ||
- _tokenMatches(_peek(), TokenType.COLON))) {
- SimpleIdentifier variableName = _parseSimpleIdentifierUnchecked();
- variableList = new VariableDeclarationList(commentAndMetadata.comment,
- commentAndMetadata.metadata, null, null, <VariableDeclaration>[
- new VariableDeclaration(variableName, null, null)
- ]);
- } else if (_isInitializedVariableDeclaration()) {
- variableList =
- _parseVariableDeclarationListAfterMetadata(commentAndMetadata);
- } else {
- initialization = parseExpression2();
- }
- TokenType type = _currentToken.type;
- if (_matchesKeyword(Keyword.IN) || type == TokenType.COLON) {
- if (type == TokenType.COLON) {
- _reportErrorForCurrentToken(ParserErrorCode.COLON_IN_PLACE_OF_IN);
- }
- DeclaredIdentifier loopVariable = null;
- SimpleIdentifier identifier = null;
- if (variableList == null) {
- // We found: <expression> 'in'
- _reportErrorForCurrentToken(
- ParserErrorCode.MISSING_VARIABLE_IN_FOR_EACH);
- } else {
- NodeList<VariableDeclaration> variables = variableList.variables;
- if (variables.length > 1) {
- _reportErrorForCurrentToken(
- ParserErrorCode.MULTIPLE_VARIABLES_IN_FOR_EACH,
- [variables.length.toString()]);
- }
- VariableDeclaration variable = variables[0];
- if (variable.initializer != null) {
- _reportErrorForCurrentToken(
- ParserErrorCode.INITIALIZED_VARIABLE_IN_FOR_EACH);
- }
- Token keyword = variableList.keyword;
- TypeName type = variableList.type;
- if (keyword != null || type != null) {
- loopVariable = new DeclaredIdentifier(
- commentAndMetadata.comment,
- commentAndMetadata.metadata,
- keyword,
- type,
- new SimpleIdentifier(variable.name.token,
- isDeclaration: true));
- } else {
- if (commentAndMetadata.hasMetadata) {
- // TODO(jwren) metadata isn't allowed before the identifier in
- // "identifier in expression", add warning if commentAndMetadata
- // has content
- }
- identifier = variable.name;
- }
- }
- Token inKeyword = getAndAdvance();
- Expression iterator = parseExpression2();
- Token rightParenthesis = _expect(TokenType.CLOSE_PAREN);
- Statement body = parseStatement2();
- if (loopVariable == null) {
- return new ForEachStatement.withReference(
- awaitKeyword,
- forKeyword,
- leftParenthesis,
- identifier,
- inKeyword,
- iterator,
- rightParenthesis,
- body);
- }
- return new ForEachStatement.withDeclaration(
- awaitKeyword,
- forKeyword,
- leftParenthesis,
- loopVariable,
- inKeyword,
- iterator,
- rightParenthesis,
- body);
- }
- }
- if (awaitKeyword != null) {
- _reportErrorForToken(
- ParserErrorCode.INVALID_AWAIT_IN_FOR, awaitKeyword);
- }
- Token leftSeparator = _expect(TokenType.SEMICOLON);
- Expression condition = null;
- if (!_matches(TokenType.SEMICOLON)) {
- condition = parseExpression2();
- }
- Token rightSeparator = _expect(TokenType.SEMICOLON);
- List<Expression> updaters = null;
- if (!_matches(TokenType.CLOSE_PAREN)) {
- updaters = _parseExpressionList();
- }
- Token rightParenthesis = _expect(TokenType.CLOSE_PAREN);
- Statement body = parseStatement2();
- return new ForStatement(
- forKeyword,
- leftParenthesis,
- variableList,
- initialization,
- leftSeparator,
- condition,
- rightSeparator,
- updaters,
- rightParenthesis,
- body);
- } finally {
- _inLoop = wasInLoop;
- }
- }
-
- /**
- * Parse a function body. The [mayBeEmpty] is `true` if the function body is
- * allowed to be empty. The [emptyErrorCode] is the error code to report if
- * function body expected, but not found. The [inExpression] is `true` if the
- * function body is being parsed as part of an expression and therefore does
- * not have a terminating semicolon. Return the function body that was parsed.
- *
- * functionBody ::=
- * '=>' expression ';'
- * | block
- *
- * functionExpressionBody ::=
- * '=>' expression
- * | block
- */
- FunctionBody _parseFunctionBody(
- bool mayBeEmpty, ParserErrorCode emptyErrorCode, bool inExpression) {
- bool wasInAsync = _inAsync;
- bool wasInGenerator = _inGenerator;
- bool wasInLoop = _inLoop;
- bool wasInSwitch = _inSwitch;
- _inAsync = false;
- _inGenerator = false;
- _inLoop = false;
- _inSwitch = false;
- try {
- TokenType type = _currentToken.type;
- if (type == TokenType.SEMICOLON) {
- if (!mayBeEmpty) {
- _reportErrorForCurrentToken(emptyErrorCode);
- }
- return new EmptyFunctionBody(getAndAdvance());
- }
- Token keyword = null;
- Token star = null;
- bool foundAsync = false;
- bool foundSync = false;
- if (type == TokenType.IDENTIFIER) {
- String lexeme = _currentToken.lexeme;
- if (lexeme == ASYNC) {
- foundAsync = true;
- keyword = getAndAdvance();
- if (!_parseAsync) {
- _reportErrorForToken(ParserErrorCode.ASYNC_NOT_SUPPORTED, keyword);
- }
- if (_matches(TokenType.STAR)) {
- star = getAndAdvance();
- _inGenerator = true;
- }
- type = _currentToken.type;
- _inAsync = true;
- } else if (lexeme == SYNC) {
- foundSync = true;
- keyword = getAndAdvance();
- if (!_parseAsync) {
- _reportErrorForToken(ParserErrorCode.ASYNC_NOT_SUPPORTED, keyword);
- }
- if (_matches(TokenType.STAR)) {
- star = getAndAdvance();
- _inGenerator = true;
- }
- type = _currentToken.type;
- }
- }
- if (type == TokenType.FUNCTION) {
- if (keyword != null) {
- if (!foundAsync) {
- _reportErrorForToken(ParserErrorCode.INVALID_SYNC, keyword);
- keyword = null;
- } else if (star != null) {
- _reportErrorForToken(
- ParserErrorCode.INVALID_STAR_AFTER_ASYNC, star);
- }
- }
- Token functionDefinition = getAndAdvance();
- if (_matchesKeyword(Keyword.RETURN)) {
- _reportErrorForToken(ParserErrorCode.UNEXPECTED_TOKEN, _currentToken,
- [_currentToken.lexeme]);
- _advance();
- }
- Expression expression = parseExpression2();
- Token semicolon = null;
- if (!inExpression) {
- semicolon = _expect(TokenType.SEMICOLON);
- }
- if (!_parseFunctionBodies) {
- return new EmptyFunctionBody(
- _createSyntheticToken(TokenType.SEMICOLON));
- }
- return new ExpressionFunctionBody(
- keyword, functionDefinition, expression, semicolon);
- } else if (type == TokenType.OPEN_CURLY_BRACKET) {
- if (keyword != null) {
- if (foundSync && star == null) {
- _reportErrorForToken(
- ParserErrorCode.MISSING_STAR_AFTER_SYNC, keyword);
- }
- }
- if (!_parseFunctionBodies) {
- _skipBlock();
- return new EmptyFunctionBody(
- _createSyntheticToken(TokenType.SEMICOLON));
- }
- return new BlockFunctionBody(keyword, star, parseBlock());
- } else if (_matchesString(_NATIVE)) {
- Token nativeToken = getAndAdvance();
- StringLiteral stringLiteral = null;
- if (_matches(TokenType.STRING)) {
- stringLiteral = _parseStringLiteralUnchecked();
- }
- return new NativeFunctionBody(
- nativeToken, stringLiteral, _expect(TokenType.SEMICOLON));
- } else {
- // Invalid function body
- _reportErrorForCurrentToken(emptyErrorCode);
- return new EmptyFunctionBody(
- _createSyntheticToken(TokenType.SEMICOLON));
- }
- } finally {
- _inAsync = wasInAsync;
- _inGenerator = wasInGenerator;
- _inLoop = wasInLoop;
- _inSwitch = wasInSwitch;
- }
- }
-
- /**
* Parse a function declaration. The [commentAndMetadata] is the documentation
* comment and metadata to be associated with the declaration. The
* [externalKeyword] is the 'external' keyword, or `null` if the function is
@@ -5144,7 +6181,7 @@
}
FunctionBody body;
if (externalKeyword == null) {
- body = _parseFunctionBody(
+ body = parseFunctionBody(
false, ParserErrorCode.MISSING_FUNCTION_BODY, false);
} else {
body = new EmptyFunctionBody(_expect(TokenType.SEMICOLON));
@@ -5165,20 +6202,6 @@
}
/**
- * Parse a function declaration statement. Return the function declaration
- * statement that was parsed.
- *
- * functionDeclarationStatement ::=
- * functionSignature functionBody
- */
- Statement _parseFunctionDeclarationStatement() {
- Modifiers modifiers = _parseModifiers();
- _validateModifiersForFunctionDeclarationStatement(modifiers);
- return _parseFunctionDeclarationStatementAfterReturnType(
- _parseCommentAndMetadata(), _parseOptionalReturnType());
- }
-
- /**
* Parse a function declaration statement. The [commentAndMetadata] is the
* documentation comment and metadata to be associated with the declaration.
* The [returnType] is the return type, or `null` if there is no return type.
@@ -5333,7 +6356,7 @@
_advance();
_advance();
}
- FunctionBody body = _parseFunctionBody(
+ FunctionBody body = parseFunctionBody(
externalKeyword != null || staticKeyword == null,
ParserErrorCode.STATIC_GETTER_WITHOUT_BODY,
false);
@@ -5372,30 +6395,6 @@
}
/**
- * Parse an if statement. Return the if statement that was parsed.
- *
- * This method assumes that the current token matches `Keyword.IF`.
- *
- * ifStatement ::=
- * 'if' '(' expression ')' statement ('else' statement)?
- */
- Statement _parseIfStatement() {
- Token ifKeyword = getAndAdvance();
- Token leftParenthesis = _expect(TokenType.OPEN_PAREN);
- Expression condition = parseExpression2();
- Token rightParenthesis = _expect(TokenType.CLOSE_PAREN);
- Statement thenStatement = parseStatement2();
- Token elseKeyword = null;
- Statement elseStatement = null;
- if (_matchesKeyword(Keyword.ELSE)) {
- elseKeyword = getAndAdvance();
- elseStatement = parseStatement2();
- }
- return new IfStatement(ifKeyword, leftParenthesis, condition,
- rightParenthesis, thenStatement, elseKeyword, elseStatement);
- }
-
- /**
* Parse an import directive. The [commentAndMetadata] is the metadata to be
* associated with the directive. Return the import directive that was parsed.
*
@@ -5436,7 +6435,7 @@
}
}
}
- List<Combinator> combinators = _parseCombinators();
+ List<Combinator> combinators = parseCombinators();
Token semicolon = _expect(TokenType.SEMICOLON);
return new ImportDirective(
commentAndMetadata.comment,
@@ -5476,7 +6475,7 @@
Token keyword,
TypeName type) {
VariableDeclarationList fieldList =
- _parseVariableDeclarationListAfterType(null, keyword, type);
+ parseVariableDeclarationListAfterType(null, keyword, type);
return new FieldDeclaration(
commentAndMetadata.comment,
commentAndMetadata.metadata,
@@ -5542,7 +6541,7 @@
_reportErrorForToken(missingNameError, missingNameToken);
}
return new LibraryIdentifier(
- <SimpleIdentifier>[_createSyntheticIdentifier()]);
+ <SimpleIdentifier>[createSyntheticIdentifier()]);
}
/**
@@ -5599,32 +6598,6 @@
}
/**
- * Parse a list or map literal. The [modifier] is the 'const' modifier
- * appearing before the literal, or `null` if there is no modifier. Return the
- * list or map literal that was parsed.
- *
- * listOrMapLiteral ::=
- * listLiteral
- * | mapLiteral
- */
- TypedLiteral _parseListOrMapLiteral(Token modifier) {
- TypeArgumentList typeArguments = _parseOptionalTypeArguments();
- if (_matches(TokenType.OPEN_CURLY_BRACKET)) {
- return _parseMapLiteral(modifier, typeArguments);
- } else if (_matches(TokenType.OPEN_SQUARE_BRACKET) ||
- _matches(TokenType.INDEX)) {
- return _parseListLiteral(modifier, typeArguments);
- }
- _reportErrorForCurrentToken(ParserErrorCode.EXPECTED_LIST_OR_MAP_LITERAL);
- return new ListLiteral(
- modifier,
- typeArguments,
- _createSyntheticToken(TokenType.OPEN_SQUARE_BRACKET),
- null,
- _createSyntheticToken(TokenType.CLOSE_SQUARE_BRACKET));
- }
-
- /**
* Parse a logical and expression. Return the logical and expression that was
* parsed.
*
@@ -5698,7 +6671,7 @@
SimpleIdentifier name,
TypeParameterList typeParameters,
FormalParameterList parameters) {
- FunctionBody body = _parseFunctionBody(
+ FunctionBody body = parseFunctionBody(
externalKeyword != null || staticKeyword == null,
ParserErrorCode.MISSING_FUNCTION_BODY,
false);
@@ -5858,29 +6831,6 @@
}
/**
- * Parse a multiplicative expression. Return the multiplicative expression
- * that was parsed.
- *
- * multiplicativeExpression ::=
- * unaryExpression (multiplicativeOperator unaryExpression)*
- * | 'super' (multiplicativeOperator unaryExpression)+
- */
- Expression _parseMultiplicativeExpression() {
- Expression expression;
- if (_currentToken.keyword == Keyword.SUPER &&
- _currentToken.next.type.isMultiplicativeOperator) {
- expression = new SuperExpression(getAndAdvance());
- } else {
- expression = _parseUnaryExpression();
- }
- while (_currentToken.type.isMultiplicativeOperator) {
- expression = new BinaryExpression(
- expression, getAndAdvance(), _parseUnaryExpression());
- }
- return expression;
- }
-
- /**
* Parse a class native clause. Return the native clause that was parsed.
*
* This method assumes that the current token matches `_NATIVE`.
@@ -5927,11 +6877,11 @@
*/
Statement _parseNonLabeledStatement() {
// TODO(brianwilkerson) Pass the comment and metadata on where appropriate.
- CommentAndMetadata commentAndMetadata = _parseCommentAndMetadata();
+ CommentAndMetadata commentAndMetadata = parseCommentAndMetadata();
TokenType type = _currentToken.type;
if (type == TokenType.OPEN_CURLY_BRACKET) {
if (_tokenMatches(_peek(), TokenType.STRING)) {
- Token afterString = _skipStringLiteral(_currentToken.next);
+ Token afterString = skipStringLiteral(_currentToken.next);
if (afterString != null && afterString.type == TokenType.COLON) {
return new ExpressionStatement(
parseExpression2(), _expect(TokenType.SEMICOLON));
@@ -5944,33 +6894,33 @@
// TODO(jwren) compute some metrics to figure out a better order for this
// if-then sequence to optimize performance
if (keyword == Keyword.ASSERT) {
- return _parseAssertStatement();
+ return parseAssertStatement();
} else if (keyword == Keyword.BREAK) {
- return _parseBreakStatement();
+ return parseBreakStatement();
} else if (keyword == Keyword.CONTINUE) {
- return _parseContinueStatement();
+ return parseContinueStatement();
} else if (keyword == Keyword.DO) {
- return _parseDoStatement();
+ return parseDoStatement();
} else if (keyword == Keyword.FOR) {
- return _parseForStatement();
+ return parseForStatement();
} else if (keyword == Keyword.IF) {
- return _parseIfStatement();
+ return parseIfStatement();
} else if (keyword == Keyword.RETHROW) {
return new ExpressionStatement(
- _parseRethrowExpression(), _expect(TokenType.SEMICOLON));
+ parseRethrowExpression(), _expect(TokenType.SEMICOLON));
} else if (keyword == Keyword.RETURN) {
- return _parseReturnStatement();
+ return parseReturnStatement();
} else if (keyword == Keyword.SWITCH) {
- return _parseSwitchStatement();
+ return parseSwitchStatement();
} else if (keyword == Keyword.THROW) {
return new ExpressionStatement(
- _parseThrowExpression(), _expect(TokenType.SEMICOLON));
+ parseThrowExpression(), _expect(TokenType.SEMICOLON));
} else if (keyword == Keyword.TRY) {
- return _parseTryStatement();
+ return parseTryStatement();
} else if (keyword == Keyword.WHILE) {
- return _parseWhileStatement();
+ return parseWhileStatement();
} else if (keyword == Keyword.VAR || keyword == Keyword.FINAL) {
- return _parseVariableDeclarationStatementAfterMetadata(
+ return parseVariableDeclarationStatementAfterMetadata(
commentAndMetadata);
} else if (keyword == Keyword.VOID) {
TypeName returnType =
@@ -5999,7 +6949,7 @@
// We appear to have a variable declaration with a type of "void".
//
_reportErrorForNode(ParserErrorCode.VOID_VARIABLE, returnType);
- return _parseVariableDeclarationStatementAfterMetadata(
+ return parseVariableDeclarationStatementAfterMetadata(
commentAndMetadata);
}
} else if (_matches(TokenType.CLOSE_CURLY_BRACKET)) {
@@ -6025,7 +6975,7 @@
return new ExpressionStatement(
parseExpression2(), _expect(TokenType.SEMICOLON));
} else if (_tokenMatches(next, TokenType.IDENTIFIER)) {
- Token afterType = _skipTypeName(next);
+ Token afterType = skipTypeName(next);
if (afterType != null) {
if (_tokenMatches(afterType, TokenType.OPEN_PAREN) ||
(_tokenMatches(afterType, TokenType.PERIOD) &&
@@ -6036,7 +6986,7 @@
}
}
}
- return _parseVariableDeclarationStatementAfterMetadata(
+ return parseVariableDeclarationStatementAfterMetadata(
commentAndMetadata);
} else if (keyword == Keyword.NEW ||
keyword == Keyword.TRUE ||
@@ -6054,29 +7004,28 @@
return new EmptyStatement(_createSyntheticToken(TokenType.SEMICOLON));
}
} else if (_inGenerator && _matchesString(_YIELD)) {
- return _parseYieldStatement();
+ return parseYieldStatement();
} else if (_inAsync && _matchesString(_AWAIT)) {
if (_tokenMatchesKeyword(_peek(), Keyword.FOR)) {
- return _parseForStatement();
+ return parseForStatement();
}
return new ExpressionStatement(
parseExpression2(), _expect(TokenType.SEMICOLON));
} else if (_matchesString(_AWAIT) &&
_tokenMatchesKeyword(_peek(), Keyword.FOR)) {
Token awaitToken = _currentToken;
- Statement statement = _parseForStatement();
+ Statement statement = parseForStatement();
if (statement is! ForStatement) {
_reportErrorForToken(
CompileTimeErrorCode.ASYNC_FOR_IN_WRONG_CONTEXT, awaitToken);
}
return statement;
} else if (type == TokenType.SEMICOLON) {
- return _parseEmptyStatement();
- } else if (_isInitializedVariableDeclaration()) {
- return _parseVariableDeclarationStatementAfterMetadata(
- commentAndMetadata);
- } else if (_isFunctionDeclaration()) {
- return _parseFunctionDeclarationStatement();
+ return parseEmptyStatement();
+ } else if (isInitializedVariableDeclaration()) {
+ return parseVariableDeclarationStatementAfterMetadata(commentAndMetadata);
+ } else if (isFunctionDeclaration()) {
+ return parseFunctionDeclarationStatement();
} else if (type == TokenType.CLOSE_CURLY_BRACKET) {
_reportErrorForCurrentToken(ParserErrorCode.MISSING_STATEMENT);
return new EmptyStatement(_createSyntheticToken(TokenType.SEMICOLON));
@@ -6087,33 +7036,6 @@
}
/**
- * Parse an operator declaration. The [commentAndMetadata] is the
- * documentation comment and metadata to be associated with the declaration.
- * The [externalKeyword] is the 'external' token. The [returnType] is the
- * return type that has already been parsed, or `null` if there was no return
- * type. Return the operator declaration that was parsed.
- *
- * operatorDeclaration ::=
- * operatorSignature (';' | functionBody)
- *
- * operatorSignature ::=
- * 'external'? returnType? 'operator' operator formalParameterList
- */
- MethodDeclaration _parseOperator(CommentAndMetadata commentAndMetadata,
- Token externalKeyword, TypeName returnType) {
- Token operatorKeyword;
- if (_matchesKeyword(Keyword.OPERATOR)) {
- operatorKeyword = getAndAdvance();
- } else {
- _reportErrorForToken(
- ParserErrorCode.MISSING_KEYWORD_OPERATOR, _currentToken);
- operatorKeyword = _createSyntheticKeyword(Keyword.OPERATOR);
- }
- return _parseOperatorAfterKeyword(
- commentAndMetadata, externalKeyword, returnType, operatorKeyword);
- }
-
- /**
* Parse an operator declaration starting after the 'operator' keyword. The
* [commentAndMetadata] is the documentation comment and metadata to be
* associated with the declaration. The [externalKeyword] is the 'external'
@@ -6151,7 +7073,7 @@
FormalParameterList parameters = parseFormalParameterList();
_validateFormalParameterList(parameters);
FunctionBody body =
- _parseFunctionBody(true, ParserErrorCode.MISSING_FUNCTION_BODY, false);
+ parseFunctionBody(true, ParserErrorCode.MISSING_FUNCTION_BODY, false);
if (externalKeyword != null && body is! EmptyFunctionBody) {
_reportErrorForCurrentToken(ParserErrorCode.EXTERNAL_OPERATOR_WITH_BODY);
}
@@ -6215,7 +7137,7 @@
TypeName _parseOptionalTypeNameComment() {
if (_injectGenericCommentTypeAssign()) {
- return _parseTypeName();
+ return _parseTypeName(false);
}
return null;
}
@@ -6296,7 +7218,7 @@
* | argumentList
*/
Expression _parsePostfixExpression() {
- Expression operand = _parseAssignableExpression(true);
+ Expression operand = parseAssignableExpression(true);
TokenType type = _currentToken.type;
if (type == TokenType.OPEN_SQUARE_BRACKET ||
type == TokenType.PERIOD ||
@@ -6369,141 +7291,6 @@
}
/**
- * Parse a primary expression. Return the primary expression that was parsed.
- *
- * primary ::=
- * thisExpression
- * | 'super' unconditionalAssignableSelector
- * | functionExpression
- * | literal
- * | identifier
- * | newExpression
- * | constObjectExpression
- * | '(' expression ')'
- * | argumentDefinitionTest
- *
- * literal ::=
- * nullLiteral
- * | booleanLiteral
- * | numericLiteral
- * | stringLiteral
- * | symbolLiteral
- * | mapLiteral
- * | listLiteral
- */
- Expression _parsePrimaryExpression() {
- if (_matchesIdentifier()) {
- // TODO(brianwilkerson) The code below was an attempt to recover from an
- // error case, but it needs to be applied as a recovery only after we
- // know that parsing it as an identifier doesn't work. Leaving the code as
- // a reminder of how to recover.
-// if (isFunctionExpression(_peek())) {
-// //
-// // Function expressions were allowed to have names at one point, but this is now illegal.
-// //
-// reportError(ParserErrorCode.NAMED_FUNCTION_EXPRESSION, getAndAdvance());
-// return parseFunctionExpression();
-// }
- return _parsePrefixedIdentifierUnchecked();
- }
- TokenType type = _currentToken.type;
- if (type == TokenType.STRING) {
- return parseStringLiteral();
- } else if (type == TokenType.INT) {
- Token token = getAndAdvance();
- int value = null;
- try {
- value = int.parse(token.lexeme);
- } on FormatException {
- // The invalid format should have been reported by the scanner.
- }
- return new IntegerLiteral(token, value);
- }
- Keyword keyword = _currentToken.keyword;
- if (keyword == Keyword.NULL) {
- return new NullLiteral(getAndAdvance());
- } else if (keyword == Keyword.NEW) {
- return _parseNewExpression();
- } else if (keyword == Keyword.THIS) {
- return new ThisExpression(getAndAdvance());
- } else if (keyword == Keyword.SUPER) {
- // TODO(paulberry): verify with Gilad that "super" must be followed by
- // unconditionalAssignableSelector in this case.
- return _parseAssignableSelector(
- new SuperExpression(getAndAdvance()), false,
- allowConditional: false);
- } else if (keyword == Keyword.FALSE) {
- return new BooleanLiteral(getAndAdvance(), false);
- } else if (keyword == Keyword.TRUE) {
- return new BooleanLiteral(getAndAdvance(), true);
- }
- if (type == TokenType.DOUBLE) {
- Token token = getAndAdvance();
- double value = 0.0;
- try {
- value = double.parse(token.lexeme);
- } on FormatException {
- // The invalid format should have been reported by the scanner.
- }
- return new DoubleLiteral(token, value);
- } else if (type == TokenType.HEXADECIMAL) {
- Token token = getAndAdvance();
- int value = null;
- try {
- value = int.parse(token.lexeme.substring(2), radix: 16);
- } on FormatException {
- // The invalid format should have been reported by the scanner.
- }
- return new IntegerLiteral(token, value);
- } else if (keyword == Keyword.CONST) {
- return _parseConstExpression();
- } else if (type == TokenType.OPEN_PAREN) {
- if (_isFunctionExpression(_currentToken)) {
- return parseFunctionExpression();
- }
- Token leftParenthesis = getAndAdvance();
- bool wasInInitializer = _inInitializer;
- _inInitializer = false;
- try {
- Expression expression = parseExpression2();
- Token rightParenthesis = _expect(TokenType.CLOSE_PAREN);
- return new ParenthesizedExpression(
- leftParenthesis, expression, rightParenthesis);
- } finally {
- _inInitializer = wasInInitializer;
- }
- } else if (type == TokenType.LT || _injectGenericCommentTypeList()) {
- return _parseListOrMapLiteral(null);
- } else if (type == TokenType.OPEN_CURLY_BRACKET) {
- return _parseMapLiteral(null, null);
- } else if (type == TokenType.OPEN_SQUARE_BRACKET ||
- type == TokenType.INDEX) {
- return _parseListLiteral(null, null);
- } else if (type == TokenType.QUESTION &&
- _tokenMatches(_peek(), TokenType.IDENTIFIER)) {
- _reportErrorForCurrentToken(
- ParserErrorCode.UNEXPECTED_TOKEN, [_currentToken.lexeme]);
- _advance();
- return _parsePrimaryExpression();
- } else if (keyword == Keyword.VOID) {
- //
- // Recover from having a return type of "void" where a return type is not
- // expected.
- //
- // TODO(brianwilkerson) Improve this error message.
- _reportErrorForCurrentToken(
- ParserErrorCode.UNEXPECTED_TOKEN, [_currentToken.lexeme]);
- _advance();
- return _parsePrimaryExpression();
- } else if (type == TokenType.HASH) {
- return _parseSymbolLiteral();
- } else {
- _reportErrorForCurrentToken(ParserErrorCode.MISSING_IDENTIFIER);
- return _createSyntheticIdentifier();
- }
- }
-
- /**
* Parse a redirecting constructor invocation. The flag [hasPeriod] should be
* `true` if the `this` is followed by a period. Return the redirecting
* constructor invocation that was parsed.
@@ -6524,7 +7311,7 @@
constructorName = _parseSimpleIdentifierUnchecked(isDeclaration: false);
} else {
_reportErrorForCurrentToken(ParserErrorCode.MISSING_IDENTIFIER);
- constructorName = _createSyntheticIdentifier(isDeclaration: false);
+ constructorName = createSyntheticIdentifier(isDeclaration: false);
_advance();
}
}
@@ -6534,72 +7321,6 @@
}
/**
- * Parse a relational expression. Return the relational expression that was
- * parsed.
- *
- * relationalExpression ::=
- * bitwiseOrExpression ('is' '!'? type | 'as' type | relationalOperator bitwiseOrExpression)?
- * | 'super' relationalOperator bitwiseOrExpression
- */
- Expression _parseRelationalExpression() {
- if (_currentToken.keyword == Keyword.SUPER &&
- _currentToken.next.type.isRelationalOperator) {
- Expression expression = new SuperExpression(getAndAdvance());
- Token operator = getAndAdvance();
- return new BinaryExpression(
- expression, operator, parseBitwiseOrExpression());
- }
- Expression expression = parseBitwiseOrExpression();
- Keyword keyword = _currentToken.keyword;
- if (keyword == Keyword.AS) {
- Token asOperator = getAndAdvance();
- return new AsExpression(expression, asOperator, parseTypeName());
- } else if (keyword == Keyword.IS) {
- Token isOperator = getAndAdvance();
- Token notOperator = null;
- if (_matches(TokenType.BANG)) {
- notOperator = getAndAdvance();
- }
- return new IsExpression(
- expression, isOperator, notOperator, parseTypeName());
- } else if (_currentToken.type.isRelationalOperator) {
- Token operator = getAndAdvance();
- return new BinaryExpression(
- expression, operator, parseBitwiseOrExpression());
- }
- return expression;
- }
-
- /**
- * Parse a rethrow expression. Return the rethrow expression that was parsed.
- *
- * This method assumes that the current token matches `Keyword.RETHROW`.
- *
- * rethrowExpression ::=
- * 'rethrow'
- */
- Expression _parseRethrowExpression() =>
- new RethrowExpression(getAndAdvance());
-
- /**
- * Parse a return statement. Return the return statement that was parsed.
- *
- * This method assumes that the current token matches `Keyword.RETURN`.
- *
- * returnStatement ::=
- * 'return' expression? ';'
- */
- Statement _parseReturnStatement() {
- Token returnKeyword = getAndAdvance();
- if (_matches(TokenType.SEMICOLON)) {
- return new ReturnStatement(returnKeyword, null, getAndAdvance());
- }
- Expression expression = parseExpression2();
- Token semicolon = _expect(TokenType.SEMICOLON);
- return new ReturnStatement(returnKeyword, expression, semicolon);
- }
-
- /**
* Parse a setter. The [commentAndMetadata] is the documentation comment and
* metadata to be associated with the declaration. The [externalKeyword] is
* the 'external' token. The [staticKeyword] is the static keyword, or `null`
@@ -6621,7 +7342,7 @@
SimpleIdentifier name = parseSimpleIdentifier(isDeclaration: true);
FormalParameterList parameters = parseFormalParameterList();
_validateFormalParameterList(parameters);
- FunctionBody body = _parseFunctionBody(
+ FunctionBody body = parseFunctionBody(
externalKeyword != null || staticKeyword == null,
ParserErrorCode.STATIC_SETTER_WITHOUT_BODY,
false);
@@ -6643,28 +7364,6 @@
}
/**
- * Parse a shift expression. Return the shift expression that was parsed.
- *
- * shiftExpression ::=
- * additiveExpression (shiftOperator additiveExpression)*
- * | 'super' (shiftOperator additiveExpression)+
- */
- Expression _parseShiftExpression() {
- Expression expression;
- if (_currentToken.keyword == Keyword.SUPER &&
- _currentToken.next.type.isShiftOperator) {
- expression = new SuperExpression(getAndAdvance());
- } else {
- expression = _parseAdditiveExpression();
- }
- while (_currentToken.type.isShiftOperator) {
- expression = new BinaryExpression(
- expression, getAndAdvance(), _parseAdditiveExpression());
- }
- return expression;
- }
-
- /**
* Parse a simple identifier. Return the simple identifier that was parsed.
*
* This method assumes that the current token matches an identifier.
@@ -6696,7 +7395,7 @@
TokenType type = _currentToken.type;
while (type != TokenType.EOF &&
type != TokenType.CLOSE_CURLY_BRACKET &&
- !_isSwitchMember()) {
+ !isSwitchMember()) {
statements.add(parseStatement2());
if (identical(_currentToken, statementStart)) {
_reportErrorForToken(ParserErrorCode.UNEXPECTED_TOKEN, _currentToken,
@@ -6720,7 +7419,7 @@
StringInterpolation _parseStringInterpolation(Token string) {
List<InterpolationElement> elements = <InterpolationElement>[
new InterpolationString(
- string, _computeStringValue(string.lexeme, true, false))
+ string, computeStringValue(string.lexeme, true, false))
];
bool hasMore = true;
bool isExpression = _matches(TokenType.STRING_INTERPOLATION_EXPRESSION);
@@ -6753,7 +7452,7 @@
hasMore =
isExpression || _matches(TokenType.STRING_INTERPOLATION_IDENTIFIER);
elements.add(new InterpolationString(
- string, _computeStringValue(string.lexeme, false, !hasMore)));
+ string, computeStringValue(string.lexeme, false, !hasMore)));
} else {
hasMore = false;
}
@@ -6779,269 +7478,13 @@
strings.add(_parseStringInterpolation(string));
} else {
strings.add(new SimpleStringLiteral(
- string, _computeStringValue(string.lexeme, true, true)));
+ string, computeStringValue(string.lexeme, true, true)));
}
} while (_matches(TokenType.STRING));
return strings.length == 1 ? strings[0] : new AdjacentStrings(strings);
}
/**
- * Parse a super constructor invocation. Return the super constructor
- * invocation that was parsed.
- *
- * This method assumes that the current token matches [Keyword.SUPER].
- *
- * superConstructorInvocation ::=
- * 'super' ('.' identifier)? arguments
- */
- SuperConstructorInvocation _parseSuperConstructorInvocation() {
- Token keyword = getAndAdvance();
- Token period = null;
- SimpleIdentifier constructorName = null;
- if (_matches(TokenType.PERIOD)) {
- period = getAndAdvance();
- constructorName = parseSimpleIdentifier();
- }
- ArgumentList argumentList = _parseArgumentListChecked();
- return new SuperConstructorInvocation(
- keyword, period, constructorName, argumentList);
- }
-
- /**
- * Parse a switch statement. Return the switch statement that was parsed.
- *
- * switchStatement ::=
- * 'switch' '(' expression ')' '{' switchCase* defaultCase? '}'
- *
- * switchCase ::=
- * label* ('case' expression ':') statements
- *
- * defaultCase ::=
- * label* 'default' ':' statements
- */
- SwitchStatement _parseSwitchStatement() {
- bool wasInSwitch = _inSwitch;
- _inSwitch = true;
- try {
- HashSet<String> definedLabels = new HashSet<String>();
- Token keyword = _expectKeyword(Keyword.SWITCH);
- Token leftParenthesis = _expect(TokenType.OPEN_PAREN);
- Expression expression = parseExpression2();
- Token rightParenthesis = _expect(TokenType.CLOSE_PAREN);
- Token leftBracket = _expect(TokenType.OPEN_CURLY_BRACKET);
- Token defaultKeyword = null;
- List<SwitchMember> members = <SwitchMember>[];
- TokenType type = _currentToken.type;
- while (type != TokenType.EOF && type != TokenType.CLOSE_CURLY_BRACKET) {
- List<Label> labels = <Label>[];
- while (
- _matchesIdentifier() && _tokenMatches(_peek(), TokenType.COLON)) {
- SimpleIdentifier identifier =
- _parseSimpleIdentifierUnchecked(isDeclaration: true);
- String label = identifier.token.lexeme;
- if (definedLabels.contains(label)) {
- _reportErrorForToken(
- ParserErrorCode.DUPLICATE_LABEL_IN_SWITCH_STATEMENT,
- identifier.token,
- [label]);
- } else {
- definedLabels.add(label);
- }
- Token colon = getAndAdvance();
- labels.add(new Label(identifier, colon));
- }
- Keyword keyword = _currentToken.keyword;
- if (keyword == Keyword.CASE) {
- Token caseKeyword = getAndAdvance();
- Expression caseExpression = parseExpression2();
- Token colon = _expect(TokenType.COLON);
- members.add(new SwitchCase(labels, caseKeyword, caseExpression, colon,
- _parseStatementList()));
- if (defaultKeyword != null) {
- _reportErrorForToken(
- ParserErrorCode.SWITCH_HAS_CASE_AFTER_DEFAULT_CASE,
- caseKeyword);
- }
- } else if (keyword == Keyword.DEFAULT) {
- if (defaultKeyword != null) {
- _reportErrorForToken(
- ParserErrorCode.SWITCH_HAS_MULTIPLE_DEFAULT_CASES, _peek());
- }
- defaultKeyword = getAndAdvance();
- Token colon = _expect(TokenType.COLON);
- members.add(new SwitchDefault(
- labels, defaultKeyword, colon, _parseStatementList()));
- } else {
- // We need to advance, otherwise we could end up in an infinite loop,
- // but this could be a lot smarter about recovering from the error.
- _reportErrorForCurrentToken(ParserErrorCode.EXPECTED_CASE_OR_DEFAULT);
- bool atEndOrNextMember() {
- TokenType type = _currentToken.type;
- if (type == TokenType.EOF ||
- type == TokenType.CLOSE_CURLY_BRACKET) {
- return true;
- }
- Keyword keyword = _currentToken.keyword;
- return keyword == Keyword.CASE || keyword == Keyword.DEFAULT;
- }
-
- while (!atEndOrNextMember()) {
- _advance();
- }
- }
- type = _currentToken.type;
- }
- Token rightBracket = _expect(TokenType.CLOSE_CURLY_BRACKET);
- return new SwitchStatement(keyword, leftParenthesis, expression,
- rightParenthesis, leftBracket, members, rightBracket);
- } finally {
- _inSwitch = wasInSwitch;
- }
- }
-
- /**
- * Parse a symbol literal. Return the symbol literal that was parsed.
- *
- * This method assumes that the current token matches [TokenType.HASH].
- *
- * symbolLiteral ::=
- * '#' identifier ('.' identifier)*
- */
- SymbolLiteral _parseSymbolLiteral() {
- Token poundSign = getAndAdvance();
- List<Token> components = <Token>[];
- if (_matchesIdentifier()) {
- components.add(getAndAdvance());
- while (_optional(TokenType.PERIOD)) {
- if (_matchesIdentifier()) {
- components.add(getAndAdvance());
- } else {
- _reportErrorForCurrentToken(ParserErrorCode.MISSING_IDENTIFIER);
- components.add(_createSyntheticToken(TokenType.IDENTIFIER));
- break;
- }
- }
- } else if (_currentToken.isOperator) {
- components.add(getAndAdvance());
- } else if (_matchesKeyword(Keyword.VOID)) {
- components.add(getAndAdvance());
- } else {
- _reportErrorForCurrentToken(ParserErrorCode.MISSING_IDENTIFIER);
- components.add(_createSyntheticToken(TokenType.IDENTIFIER));
- }
- return new SymbolLiteral(poundSign, components);
- }
-
- /**
- * Parse a throw expression. Return the throw expression that was parsed.
- *
- * This method assumes that the current token matches [Keyword.THROW].
- *
- * throwExpression ::=
- * 'throw' expression
- */
- Expression _parseThrowExpression() {
- Token keyword = getAndAdvance();
- TokenType type = _currentToken.type;
- if (type == TokenType.SEMICOLON || type == TokenType.CLOSE_PAREN) {
- _reportErrorForToken(
- ParserErrorCode.MISSING_EXPRESSION_IN_THROW, _currentToken);
- return new ThrowExpression(keyword, _createSyntheticIdentifier());
- }
- Expression expression = parseExpression2();
- return new ThrowExpression(keyword, expression);
- }
-
- /**
- * Parse a throw expression. Return the throw expression that was parsed.
- *
- * This method assumes that the current token matches [Keyword.THROW].
- *
- * throwExpressionWithoutCascade ::=
- * 'throw' expressionWithoutCascade
- */
- Expression _parseThrowExpressionWithoutCascade() {
- Token keyword = getAndAdvance();
- TokenType type = _currentToken.type;
- if (type == TokenType.SEMICOLON || type == TokenType.CLOSE_PAREN) {
- _reportErrorForToken(
- ParserErrorCode.MISSING_EXPRESSION_IN_THROW, _currentToken);
- return new ThrowExpression(keyword, _createSyntheticIdentifier());
- }
- Expression expression = parseExpressionWithoutCascade();
- return new ThrowExpression(keyword, expression);
- }
-
- /**
- * Parse a try statement. Return the try statement that was parsed.
- *
- * This method assumes that the current token matches [Keyword.TRY].
- *
- * tryStatement ::=
- * 'try' block (onPart+ finallyPart? | finallyPart)
- *
- * onPart ::=
- * catchPart block
- * | 'on' type catchPart? block
- *
- * catchPart ::=
- * 'catch' '(' identifier (',' identifier)? ')'
- *
- * finallyPart ::=
- * 'finally' block
- */
- Statement _parseTryStatement() {
- Token tryKeyword = getAndAdvance();
- Block body = _parseBlockChecked();
- List<CatchClause> catchClauses = <CatchClause>[];
- Block finallyClause = null;
- while (_matchesString(_ON) || _matchesKeyword(Keyword.CATCH)) {
- Token onKeyword = null;
- TypeName exceptionType = null;
- if (_matchesString(_ON)) {
- onKeyword = getAndAdvance();
- exceptionType = parseTypeName();
- }
- Token catchKeyword = null;
- Token leftParenthesis = null;
- SimpleIdentifier exceptionParameter = null;
- Token comma = null;
- SimpleIdentifier stackTraceParameter = null;
- Token rightParenthesis = null;
- if (_matchesKeyword(Keyword.CATCH)) {
- catchKeyword = getAndAdvance();
- leftParenthesis = _expect(TokenType.OPEN_PAREN);
- exceptionParameter = parseSimpleIdentifier(isDeclaration: true);
- if (_matches(TokenType.COMMA)) {
- comma = getAndAdvance();
- stackTraceParameter = parseSimpleIdentifier(isDeclaration: true);
- }
- rightParenthesis = _expect(TokenType.CLOSE_PAREN);
- }
- Block catchBody = _parseBlockChecked();
- catchClauses.add(new CatchClause(
- onKeyword,
- exceptionType,
- catchKeyword,
- leftParenthesis,
- exceptionParameter,
- comma,
- stackTraceParameter,
- rightParenthesis,
- catchBody));
- }
- Token finallyKeyword = null;
- if (_matchesKeyword(Keyword.FINALLY)) {
- finallyKeyword = getAndAdvance();
- finallyClause = _parseBlockChecked();
- } else if (catchClauses.isEmpty) {
- _reportErrorForCurrentToken(ParserErrorCode.MISSING_CATCH_OR_FINALLY);
- }
- return new TryStatement(
- tryKeyword, body, catchClauses, finallyKeyword, finallyClause);
- }
-
- /**
* Parse a type alias. The [commentAndMetadata] is the metadata to be
* associated with the member. Return the type alias that was parsed.
*
@@ -7074,14 +7517,14 @@
next = _skipTypeParameterList(next);
if (next != null && _tokenMatches(next, TokenType.EQ)) {
TypeAlias typeAlias =
- _parseClassTypeAlias(commentAndMetadata, null, keyword);
+ parseClassTypeAlias(commentAndMetadata, null, keyword);
_reportErrorForToken(
ParserErrorCode.DEPRECATED_CLASS_TYPE_ALIAS, keyword);
return typeAlias;
}
} else if (_tokenMatches(next, TokenType.EQ)) {
TypeAlias typeAlias =
- _parseClassTypeAlias(commentAndMetadata, null, keyword);
+ parseClassTypeAlias(commentAndMetadata, null, keyword);
_reportErrorForToken(
ParserErrorCode.DEPRECATED_CLASS_TYPE_ALIAS, keyword);
return typeAlias;
@@ -7090,7 +7533,7 @@
return _parseFunctionTypeAlias(commentAndMetadata, keyword);
}
- TypeName _parseTypeName() {
+ TypeName _parseTypeName(bool inExpression) {
Identifier typeName;
if (_matchesIdentifier()) {
typeName = _parsePrefixedIdentifierUnchecked();
@@ -7098,11 +7541,17 @@
_reportErrorForCurrentToken(ParserErrorCode.VAR_AS_TYPE_NAME);
typeName = new SimpleIdentifier(getAndAdvance());
} else {
- typeName = _createSyntheticIdentifier();
+ typeName = createSyntheticIdentifier();
_reportErrorForCurrentToken(ParserErrorCode.EXPECTED_TYPE_NAME);
}
TypeArgumentList typeArguments = _parseOptionalTypeArguments();
- return new TypeName(typeName, typeArguments);
+ Token question = null;
+ if (enableNnbd && _matches(TokenType.QUESTION)) {
+ if (!inExpression || !_isConditionalOperator()) {
+ question = getAndAdvance();
+ }
+ }
+ return new TypeName(typeName, typeArguments, question: question);
}
/**
@@ -7125,82 +7574,6 @@
}
/**
- * Parse a unary expression. Return the unary expression that was parsed.
- *
- * unaryExpression ::=
- * prefixOperator unaryExpression
- * | awaitExpression
- * | postfixExpression
- * | unaryOperator 'super'
- * | '-' 'super'
- * | incrementOperator assignableExpression
- */
- Expression _parseUnaryExpression() {
- TokenType type = _currentToken.type;
- if (type == TokenType.MINUS ||
- type == TokenType.BANG ||
- type == TokenType.TILDE) {
- Token operator = getAndAdvance();
- if (_matchesKeyword(Keyword.SUPER)) {
- TokenType nextType = _peek().type;
- if (nextType == TokenType.OPEN_SQUARE_BRACKET ||
- nextType == TokenType.PERIOD) {
- // "prefixOperator unaryExpression"
- // --> "prefixOperator postfixExpression"
- // --> "prefixOperator primary selector*"
- // --> "prefixOperator 'super' assignableSelector selector*"
- return new PrefixExpression(operator, _parseUnaryExpression());
- }
- return new PrefixExpression(
- operator, new SuperExpression(getAndAdvance()));
- }
- return new PrefixExpression(operator, _parseUnaryExpression());
- } else if (_currentToken.type.isIncrementOperator) {
- Token operator = getAndAdvance();
- if (_matchesKeyword(Keyword.SUPER)) {
- TokenType nextType = _peek().type;
- if (nextType == TokenType.OPEN_SQUARE_BRACKET ||
- nextType == TokenType.PERIOD) {
- // --> "prefixOperator 'super' assignableSelector selector*"
- return new PrefixExpression(operator, _parseUnaryExpression());
- }
- //
- // Even though it is not valid to use an incrementing operator
- // ('++' or '--') before 'super', we can (and therefore must) interpret
- // "--super" as semantically equivalent to "-(-super)". Unfortunately,
- // we cannot do the same for "++super" because "+super" is also not
- // valid.
- //
- if (type == TokenType.MINUS_MINUS) {
- Token firstOperator = _createToken(operator, TokenType.MINUS);
- Token secondOperator =
- new Token(TokenType.MINUS, operator.offset + 1);
- secondOperator.setNext(_currentToken);
- firstOperator.setNext(secondOperator);
- operator.previous.setNext(firstOperator);
- return new PrefixExpression(
- firstOperator,
- new PrefixExpression(
- secondOperator, new SuperExpression(getAndAdvance())));
- }
- // Invalid operator before 'super'
- _reportErrorForCurrentToken(
- ParserErrorCode.INVALID_OPERATOR_FOR_SUPER, [operator.lexeme]);
- return new PrefixExpression(
- operator, new SuperExpression(getAndAdvance()));
- }
- return new PrefixExpression(
- operator, _parseAssignableExpressionNotStartingWithSuper(false));
- } else if (type == TokenType.PLUS) {
- _reportErrorForCurrentToken(ParserErrorCode.MISSING_IDENTIFIER);
- return _createSyntheticIdentifier();
- } else if (_inAsync && _matchesString(_AWAIT)) {
- return _parseAwaitExpression();
- }
- return _parsePostfixExpression();
- }
-
- /**
* Parse a string literal representing a URI. Return the string literal that
* was parsed.
*/
@@ -7261,100 +7634,6 @@
}
/**
- * Parse a variable declaration. Return the variable declaration that was
- * parsed.
- *
- * variableDeclaration ::=
- * identifier ('=' expression)?
- */
- VariableDeclaration _parseVariableDeclaration() {
- // TODO(paulberry): prior to the fix for bug 23204, we permitted
- // annotations before variable declarations (e.g. "String @deprecated s;").
- // Although such constructions are prohibited by the spec, we may want to
- // consider handling them anyway to allow for better parser recovery in the
- // event that the user erroneously tries to use them. However, as a
- // counterargument, this would likely degrade parser recovery in the event
- // of a construct like "class C { int @deprecated foo() {} }" (i.e. the
- // user is in the middle of inserting "int bar;" prior to
- // "@deprecated foo() {}").
- SimpleIdentifier name = parseSimpleIdentifier(isDeclaration: true);
- Token equals = null;
- Expression initializer = null;
- if (_matches(TokenType.EQ)) {
- equals = getAndAdvance();
- initializer = parseExpression2();
- }
- return new VariableDeclaration(name, equals, initializer);
- }
-
- /**
- * Parse a variable declaration list. The [commentAndMetadata] is the metadata
- * to be associated with the variable declaration list. Return the variable
- * declaration list that was parsed.
- *
- * variableDeclarationList ::=
- * finalConstVarOrType variableDeclaration (',' variableDeclaration)*
- */
- VariableDeclarationList _parseVariableDeclarationListAfterMetadata(
- CommentAndMetadata commentAndMetadata) {
- FinalConstVarOrType holder = _parseFinalConstVarOrType(false);
- return _parseVariableDeclarationListAfterType(
- commentAndMetadata, holder.keyword, holder.type);
- }
-
- /**
- * Parse a variable declaration list. The [commentAndMetadata] is the metadata
- * to be associated with the variable declaration list, or `null` if there is
- * no attempt at parsing the comment and metadata. The [keyword] is the token
- * representing the 'final', 'const' or 'var' keyword, or `null` if there is
- * no keyword. The [type] is the type of the variables in the list. Return the
- * variable declaration list that was parsed.
- *
- * variableDeclarationList ::=
- * finalConstVarOrType variableDeclaration (',' variableDeclaration)*
- */
- VariableDeclarationList _parseVariableDeclarationListAfterType(
- CommentAndMetadata commentAndMetadata, Token keyword, TypeName type) {
- if (type != null &&
- keyword != null &&
- _tokenMatchesKeyword(keyword, Keyword.VAR)) {
- _reportErrorForToken(ParserErrorCode.VAR_AND_TYPE, keyword);
- }
- List<VariableDeclaration> variables = <VariableDeclaration>[
- _parseVariableDeclaration()
- ];
- while (_optional(TokenType.COMMA)) {
- variables.add(_parseVariableDeclaration());
- }
- return new VariableDeclarationList(commentAndMetadata?.comment,
- commentAndMetadata?.metadata, keyword, type, variables);
- }
-
- /**
- * Parse a variable declaration statement. The [commentAndMetadata] is the
- * metadata to be associated with the variable declaration statement, or
- * `null` if there is no attempt at parsing the comment and metadata. Return
- * the variable declaration statement that was parsed.
- *
- * variableDeclarationStatement ::=
- * variableDeclarationList ';'
- */
- VariableDeclarationStatement _parseVariableDeclarationStatementAfterMetadata(
- CommentAndMetadata commentAndMetadata) {
- // Token startToken = currentToken;
- VariableDeclarationList variableList =
- _parseVariableDeclarationListAfterMetadata(commentAndMetadata);
-// if (!matches(TokenType.SEMICOLON)) {
-// if (matches(startToken, Keyword.VAR) && isTypedIdentifier(startToken.getNext())) {
-// // TODO(brianwilkerson) This appears to be of the form "var type variable". We should do
-// // a better job of recovering in this case.
-// }
-// }
- Token semicolon = _expect(TokenType.SEMICOLON);
- return new VariableDeclarationStatement(variableList, semicolon);
- }
-
- /**
* Parse a variable declaration statement. The [commentAndMetadata] is the
* metadata to be associated with the variable declaration statement, or
* `null` if there is no attempt at parsing the comment and metadata. The
@@ -7368,56 +7647,13 @@
VariableDeclarationStatement _parseVariableDeclarationStatementAfterType(
CommentAndMetadata commentAndMetadata, Token keyword, TypeName type) {
VariableDeclarationList variableList =
- _parseVariableDeclarationListAfterType(
+ parseVariableDeclarationListAfterType(
commentAndMetadata, keyword, type);
Token semicolon = _expect(TokenType.SEMICOLON);
return new VariableDeclarationStatement(variableList, semicolon);
}
/**
- * Parse a while statement. Return the while statement that was parsed.
- *
- * This method assumes that the current token matches [Keyword.WHILE].
- *
- * whileStatement ::=
- * 'while' '(' expression ')' statement
- */
- Statement _parseWhileStatement() {
- bool wasInLoop = _inLoop;
- _inLoop = true;
- try {
- Token keyword = getAndAdvance();
- Token leftParenthesis = _expect(TokenType.OPEN_PAREN);
- Expression condition = parseExpression2();
- Token rightParenthesis = _expect(TokenType.CLOSE_PAREN);
- Statement body = parseStatement2();
- return new WhileStatement(
- keyword, leftParenthesis, condition, rightParenthesis, body);
- } finally {
- _inLoop = wasInLoop;
- }
- }
-
- /**
- * Parse a yield statement. Return the yield statement that was parsed.
- *
- * This method assumes that the current token matches [Keyword.YIELD].
- *
- * yieldStatement ::=
- * 'yield' '*'? expression ';'
- */
- YieldStatement _parseYieldStatement() {
- Token yieldToken = getAndAdvance();
- Token star = null;
- if (_matches(TokenType.STAR)) {
- star = getAndAdvance();
- }
- Expression expression = parseExpression2();
- Token semicolon = _expect(TokenType.SEMICOLON);
- return new YieldStatement(yieldToken, star, expression, semicolon);
- }
-
- /**
* Return the token that is immediately after the current token. This is
* equivalent to [_peekAt](1).
*/
@@ -7514,6 +7750,40 @@
}
/**
+ * Execute the given [parseOperation] in a temporary parser whose current
+ * token has been set to the given [startToken]. If the parse does not
+ * generate any errors or exceptions, then return the token following the
+ * matching portion of the token stream. Otherwise, return `null`.
+ *
+ * Note: This is an extremely inefficient way of testing whether the tokens in
+ * the token stream match a given production. It should not be used for
+ * production code.
+ */
+ Token _skip(Token startToken, parseOperation(Parser parser)) {
+ BooleanErrorListener listener = new BooleanErrorListener();
+ Parser parser = new Parser(_source, listener);
+ parser._currentToken = _cloneTokens(startToken);
+ parser._enableAssertInitializer = _enableAssertInitializer;
+ parser._enableNnbd = _enableNnbd;
+ parser._inAsync = _inAsync;
+ parser._inGenerator = _inGenerator;
+ parser._inInitializer = _inInitializer;
+ parser._inLoop = _inLoop;
+ parser._inSwitch = _inSwitch;
+ parser._parseAsync = _parseAsync;
+ parser._parseFunctionBodies = _parseFunctionBodies;
+ try {
+ parseOperation(parser);
+ } catch (exception) {
+ return null;
+ }
+ if (listener.errorReported) {
+ return null;
+ }
+ return parser._currentToken;
+ }
+
+ /**
* Skips a block with all containing blocks.
*/
void _skipBlock() {
@@ -7555,7 +7825,7 @@
if (_tokenMatchesIdentifier(next2) ||
_tokenMatches(next2, TokenType.LT) ||
_tokenMatches(next2, TokenType.PERIOD)) {
- return _skipTypeName(next);
+ return skipTypeName(next);
}
// "parameter"
return next;
@@ -7572,7 +7842,7 @@
(_tokenMatchesIdentifier(next.next.next) ||
_tokenMatches(next.next.next, TokenType.LT) ||
_tokenMatchesKeyword(next.next.next, Keyword.THIS)))) {
- return _skipReturnType(startToken);
+ return skipReturnType(startToken);
}
}
return null;
@@ -7656,7 +7926,7 @@
if (afterType == null) {
return null;
}
- if (_skipSimpleIdentifier(afterType) == null) {
+ if (skipSimpleIdentifier(afterType) == null) {
return null;
}
return _skipPastMatchingToken(startToken);
@@ -7678,77 +7948,6 @@
}
/**
- * Parse a prefixed identifier, starting at the [startToken], without actually
- * creating a prefixed identifier or changing the current token. Return the
- * token following the prefixed identifier that was parsed, or `null` if the
- * given token is not the first token in a valid prefixed identifier.
- *
- * This method must be kept in sync with [parsePrefixedIdentifier].
- *
- * prefixedIdentifier ::=
- * identifier ('.' identifier)?
- */
- Token _skipPrefixedIdentifier(Token startToken) {
- Token token = _skipSimpleIdentifier(startToken);
- if (token == null) {
- return null;
- } else if (!_tokenMatches(token, TokenType.PERIOD)) {
- return token;
- }
- token = token.next;
- Token nextToken = _skipSimpleIdentifier(token);
- if (nextToken != null) {
- return nextToken;
- } else if (_tokenMatches(token, TokenType.CLOSE_PAREN) ||
- _tokenMatches(token, TokenType.COMMA)) {
- // If the `id.` is followed by something that cannot produce a valid
- // structure then assume this is a prefixed identifier but missing the
- // trailing identifier
- return token;
- }
- return null;
- }
-
- /**
- * Parse a return type, starting at the [startToken], without actually
- * creating a return type or changing the current token. Return the token
- * following the return type that was parsed, or `null` if the given token is
- * not the first token in a valid return type.
- *
- * This method must be kept in sync with [parseReturnType].
- *
- * returnType ::=
- * 'void'
- * | type
- */
- Token _skipReturnType(Token startToken) {
- if (_tokenMatchesKeyword(startToken, Keyword.VOID)) {
- return startToken.next;
- } else {
- return _skipTypeName(startToken);
- }
- }
-
- /**
- * Parse a simple identifier, starting at the [startToken], without actually
- * creating a simple identifier or changing the current token. Return the
- * token following the simple identifier that was parsed, or `null` if the
- * given token is not the first token in a valid simple identifier.
- *
- * This method must be kept in sync with [parseSimpleIdentifier].
- *
- * identifier ::=
- * IDENTIFIER
- */
- Token _skipSimpleIdentifier(Token startToken) {
- if (_tokenMatches(startToken, TokenType.IDENTIFIER) ||
- _tokenMatchesPseudoKeyword(startToken)) {
- return startToken.next;
- }
- return null;
- }
-
- /**
* Parse a string literal that contains interpolations, starting at the
* [startToken], without actually creating a string literal or changing the
* current token. Return the token following the string literal that was
@@ -7781,7 +7980,7 @@
bracketNestingLevel--;
token = token.next;
} else if (type == TokenType.STRING) {
- token = _skipStringLiteral(token);
+ token = skipStringLiteral(token);
if (token == null) {
return null;
}
@@ -7809,103 +8008,6 @@
}
/**
- * Parse a string literal, starting at the [startToken], without actually
- * creating a string literal or changing the current token. Return the token
- * following the string literal that was parsed, or `null` if the given token
- * is not the first token in a valid string literal.
- *
- * This method must be kept in sync with [parseStringLiteral].
- *
- * stringLiteral ::=
- * MULTI_LINE_STRING+
- * | SINGLE_LINE_STRING+
- */
- Token _skipStringLiteral(Token startToken) {
- Token token = startToken;
- while (token != null && _tokenMatches(token, TokenType.STRING)) {
- token = token.next;
- TokenType type = token.type;
- if (type == TokenType.STRING_INTERPOLATION_EXPRESSION ||
- type == TokenType.STRING_INTERPOLATION_IDENTIFIER) {
- token = _skipStringInterpolation(token);
- }
- }
- if (identical(token, startToken)) {
- return null;
- }
- return token;
- }
-
- /**
- * Parse a list of type arguments, starting at the [startToken], without
- * actually creating a type argument list or changing the current token.
- * Return the token following the type argument list that was parsed, or
- * `null` if the given token is not the first token in a valid type argument
- * list.
- *
- * This method must be kept in sync with [parseTypeArgumentList].
- *
- * typeArguments ::=
- * '<' typeList '>'
- *
- * typeList ::=
- * type (',' type)*
- */
- Token _skipTypeArgumentList(Token startToken) {
- Token token = startToken;
- if (!_tokenMatches(token, TokenType.LT) &&
- !_injectGenericCommentTypeList()) {
- return null;
- }
- token = _skipTypeName(token.next);
- if (token == null) {
- // If the start token '<' is followed by '>'
- // then assume this should be type argument list but is missing a type
- token = startToken.next;
- if (_tokenMatches(token, TokenType.GT)) {
- return token.next;
- }
- return null;
- }
- while (_tokenMatches(token, TokenType.COMMA)) {
- token = _skipTypeName(token.next);
- if (token == null) {
- return null;
- }
- }
- if (token.type == TokenType.GT) {
- return token.next;
- } else if (token.type == TokenType.GT_GT) {
- Token second = new Token(TokenType.GT, token.offset + 1);
- second.setNextWithoutSettingPrevious(token.next);
- return second;
- }
- return null;
- }
-
- /**
- * Parse a type name, starting at the [startToken], without actually creating
- * a type name or changing the current token. Return the token following the
- * type name that was parsed, or `null` if the given token is not the first
- * token in a valid type name.
- *
- * This method must be kept in sync with [parseTypeName].
- *
- * type ::=
- * qualified typeArguments?
- */
- Token _skipTypeName(Token startToken) {
- Token token = _skipPrefixedIdentifier(startToken);
- if (token == null) {
- return null;
- }
- if (_tokenMatches(token, TokenType.LT)) {
- token = _skipTypeArgumentList(token);
- }
- return token;
- }
-
- /**
* Parse a list of type parameters, starting at the [startToken], without
* actually creating a type parameter list or changing the current token.
* Return the token following the type parameter list that was parsed, or
diff --git a/pkg/analyzer/lib/src/generated/resolver.dart b/pkg/analyzer/lib/src/generated/resolver.dart
index 208c15c..a24bd1e 100644
--- a/pkg/analyzer/lib/src/generated/resolver.dart
+++ b/pkg/analyzer/lib/src/generated/resolver.dart
@@ -12,6 +12,8 @@
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/type.dart';
import 'package:analyzer/dart/element/visitor.dart';
+import 'package:analyzer/error/error.dart';
+import 'package:analyzer/error/listener.dart';
import 'package:analyzer/exception/exception.dart';
import 'package:analyzer/src/dart/ast/ast.dart';
import 'package:analyzer/src/dart/ast/utilities.dart';
@@ -20,10 +22,10 @@
import 'package:analyzer/src/dart/element/utilities.dart';
import 'package:analyzer/src/dart/resolver/inheritance_manager.dart';
import 'package:analyzer/src/dart/resolver/scope.dart';
+import 'package:analyzer/src/error/codes.dart';
import 'package:analyzer/src/generated/constant.dart';
import 'package:analyzer/src/generated/element_resolver.dart';
import 'package:analyzer/src/generated/engine.dart';
-import 'package:analyzer/src/generated/error.dart';
import 'package:analyzer/src/generated/error_verifier.dart';
import 'package:analyzer/src/generated/java_core.dart';
import 'package:analyzer/src/generated/source.dart';
@@ -7282,7 +7284,7 @@
originalType.typeFormals.isNotEmpty &&
ts is StrongTypeSystemImpl) {
contextType = ts.inferGenericFunctionCall(typeProvider, originalType,
- DartType.EMPTY_LIST, DartType.EMPTY_LIST, returnContextType);
+ DartType.EMPTY_LIST, DartType.EMPTY_LIST, originalType.returnType, returnContextType);
}
InferenceContext.setType(node.argumentList, contextType);
@@ -7334,7 +7336,8 @@
!FunctionTypeImpl.relate(
expectedClosureType,
staticClosureType,
- (DartType t, DartType s) => (t as TypeImpl).isMoreSpecificThan(s),
+ (DartType t, DartType s, _, __) =>
+ (t as TypeImpl).isMoreSpecificThan(s),
new TypeSystemImpl().instantiateToBounds,
returnRelation: (s, t) => true)) {
return;
diff --git a/pkg/analyzer/lib/src/generated/static_type_analyzer.dart b/pkg/analyzer/lib/src/generated/static_type_analyzer.dart
index b7d45f7..fafb7b9 100644
--- a/pkg/analyzer/lib/src/generated/static_type_analyzer.dart
+++ b/pkg/analyzer/lib/src/generated/static_type_analyzer.dart
@@ -623,46 +623,45 @@
return null;
}
+ DartType listDynamicType =
+ _typeProvider.listType.instantiate(<DartType>[_dynamicType]);
+
// If there are no type arguments and we are in strong mode, try to infer
// some arguments.
if (_strongMode) {
DartType contextType = InferenceContext.getType(node);
- // If we have a type from the context, use it.
- if (contextType is InterfaceType &&
- contextType.typeArguments.length == 1 &&
- contextType.element == _typeProvider.listType.element) {
- _resolver.inferenceContext.recordInference(node, contextType);
- _recordStaticType(node, contextType);
- return null;
- }
+ // Use both downwards and upwards information to infer the type.
+ var ts = _typeSystem as StrongTypeSystemImpl;
+ var elementTypes = node.elements
+ .map((e) => e.staticType)
+ .where((t) => t != null)
+ .toList();
+ var listTypeParam = _typeProvider.listType.typeParameters[0].type;
- // If we don't have a type from the context, try to infer from the
- // elements
- if (node.elements.isNotEmpty) {
- // Infer the list type from the arguments.
- Iterable<DartType> types =
- node.elements.map((e) => e.staticType).where((t) => t != null);
- if (types.isEmpty) {
- return null;
- }
- DartType staticType = types.reduce(_leastUpperBound);
- if (staticType.isBottom) {
- staticType = _dynamicType;
- }
- DartType listLiteralType =
- _typeProvider.listType.instantiate(<DartType>[staticType]);
- if (!staticType.isDynamic) {
- _resolver.inferenceContext.recordInference(node, listLiteralType);
- }
- _recordStaticType(node, listLiteralType);
+ DartType inferred = ts.inferGenericFunctionCall(
+ _typeProvider,
+ _typeProvider.listType,
+ new List.filled(elementTypes.length, listTypeParam),
+ elementTypes,
+ _typeProvider.listType,
+ contextType,
+ errorReporter: _resolver.errorReporter,
+ errorNode: node);
+
+ if (inferred != listDynamicType) {
+ // TODO(jmesserly): this results in an "inferred" message even when we
+ // in fact had an error above, because it will still attempt to return
+ // a type. Perhaps we should record inference from TypeSystem if
+ // everything was successful?
+ _resolver.inferenceContext.recordInference(node, inferred);
+ _recordStaticType(node, inferred);
return null;
}
}
// If we have no type arguments and couldn't infer any, use dynamic.
- _recordStaticType(
- node, _typeProvider.listType.instantiate(<DartType>[_dynamicType]));
+ _recordStaticType(node, listDynamicType);
return null;
}
@@ -682,6 +681,9 @@
Object visitMapLiteral(MapLiteral node) {
TypeArgumentList typeArguments = node.typeArguments;
+ DartType mapDynamicType = _typeProvider.mapType
+ .instantiate(<DartType>[_dynamicType, _dynamicType]);
+
// If we have type arguments, use them
if (typeArguments != null) {
DartType staticKeyType = _dynamicType;
@@ -710,43 +712,40 @@
// then try to infer type arguments.
if (_strongMode) {
DartType contextType = InferenceContext.getType(node);
- // If we have a context type, use that for inference.
- if (contextType is InterfaceType &&
- contextType.typeArguments.length == 2 &&
- contextType.element == _typeProvider.mapType.element) {
- _resolver.inferenceContext.recordInference(node, contextType);
- _recordStaticType(node, contextType);
- return null;
- }
- // Otherwise, try to infer a type from the keys and values.
- if (node.entries.isNotEmpty) {
- DartType staticKeyType =
- node.entries.map((e) => e.key.staticType).reduce(_leastUpperBound);
- DartType staticValueType = node.entries
- .map((e) => e.value.staticType)
- .reduce(_leastUpperBound);
- if (staticKeyType.isBottom) {
- staticKeyType = _dynamicType;
- }
- if (staticValueType.isBottom) {
- staticValueType = _dynamicType;
- }
- DartType mapLiteralType = _typeProvider.mapType
- .instantiate(<DartType>[staticKeyType, staticValueType]);
- if (!(staticValueType.isDynamic && staticKeyType.isDynamic)) {
- _resolver.inferenceContext.recordInference(node, mapLiteralType);
- }
- _recordStaticType(node, mapLiteralType);
+ // Use both downwards and upwards information to infer the type.
+ var ts = _typeSystem as StrongTypeSystemImpl;
+ var keyTypes =
+ node.entries.map((e) => e.key.staticType).where((t) => t != null);
+ var valueTypes =
+ node.entries.map((e) => e.value.staticType).where((t) => t != null);
+ var keyTypeParam = _typeProvider.mapType.typeParameters[0].type;
+ var valueTypeParam = _typeProvider.mapType.typeParameters[1].type;
+
+ DartType inferred = ts.inferGenericFunctionCall(
+ _typeProvider,
+ _typeProvider.mapType,
+ new List.filled(keyTypes.length, keyTypeParam, growable: true)
+ ..addAll(new List.filled(valueTypes.length, valueTypeParam)),
+ new List.from(keyTypes)..addAll(valueTypes),
+ _typeProvider.mapType,
+ contextType,
+ errorReporter: _resolver.errorReporter,
+ errorNode: node);
+
+ if (inferred != mapDynamicType) {
+ // TODO(jmesserly): this results in an "inferred" message even when we
+ // in fact had an error above, because it will still attempt to return
+ // a type. Perhaps we should record inference from TypeSystem if
+ // everything was successful?
+ _resolver.inferenceContext.recordInference(node, inferred);
+ _recordStaticType(node, inferred);
return null;
}
}
// If no type arguments and no inference, use dynamic
- _recordStaticType(
- node,
- _typeProvider.mapType
- .instantiate(<DartType>[_dynamicType, _dynamicType]));
+ _recordStaticType(node, mapDynamicType);
return null;
}
@@ -1986,7 +1985,7 @@
}
}
return ts.inferGenericFunctionCall(_typeProvider, fnType, paramTypes,
- argTypes, InferenceContext.getContext(node),
+ argTypes, fnType.returnType, InferenceContext.getContext(node),
errorReporter: _resolver.errorReporter, errorNode: errorNode);
}
return null;
@@ -2251,14 +2250,6 @@
}
/**
- * Computes the least upper bound between two types.
- *
- * See [TypeSystem.getLeastUpperBound].
- */
- DartType _leastUpperBound(DartType s, DartType t) =>
- _typeSystem.getLeastUpperBound(_typeProvider, s, t);
-
- /**
* Record that the propagated type of the given node is the given type.
*
* @param expression the node whose type is to be recorded
diff --git a/pkg/analyzer/lib/src/generated/type_system.dart b/pkg/analyzer/lib/src/generated/type_system.dart
index dfc5282..0488553 100644
--- a/pkg/analyzer/lib/src/generated/type_system.dart
+++ b/pkg/analyzer/lib/src/generated/type_system.dart
@@ -11,12 +11,12 @@
import 'package:analyzer/dart/ast/token.dart' show TokenType;
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/type.dart';
+import 'package:analyzer/error/listener.dart' show ErrorReporter;
import 'package:analyzer/src/dart/element/element.dart';
import 'package:analyzer/src/dart/element/type.dart';
+import 'package:analyzer/src/error/codes.dart' show StrongModeCode;
import 'package:analyzer/src/generated/engine.dart'
show AnalysisContext, AnalysisOptionsImpl;
-import 'package:analyzer/src/generated/error.dart'
- show ErrorReporter, StrongModeCode;
import 'package:analyzer/src/generated/resolver.dart' show TypeProvider;
import 'package:analyzer/src/generated/utilities_dart.dart' show ParameterKind;
import 'package:analyzer/src/generated/utilities_general.dart'
@@ -363,7 +363,8 @@
}
// Try to infer and instantiate the resulting type.
- var resultType = inferringTypeSystem._infer(fnType);
+ var resultType = inferringTypeSystem._infer(
+ fnType, fnType.typeFormals, fnType.returnType);
// If the instantiation failed (because some type variable constraints
// could not be solved, in other words, we could not find a valid subtype),
@@ -393,26 +394,21 @@
/// As a simplification, we do not actually store all constraints on each type
/// parameter Tj. Instead we track Uj and Lj where U is the upper bound and
/// L is the lower bound of that type parameter.
- FunctionType inferGenericFunctionCall(
+ /*=T*/ inferGenericFunctionCall/*<T extends ParameterizedType>*/(
TypeProvider typeProvider,
- FunctionType fnType,
- List<DartType> correspondingParameterTypes,
+ /*=T*/ genericType,
+ List<DartType> declaredParameterTypes,
List<DartType> argumentTypes,
+ DartType declaredReturnType,
DartType returnContextType,
{ErrorReporter errorReporter,
AstNode errorNode}) {
- if (fnType.typeFormals.isEmpty) {
- return fnType;
- }
-
- // If we're in a future union context, choose either the Future<T> or the T
- // based on the function's return type.
- if (returnContextType is FutureUnionType) {
- var futureUnion = returnContextType as FutureUnionType;
- returnContextType =
- isSubtypeOf(fnType.returnType, typeProvider.futureDynamicType)
- ? futureUnion.futureOfType
- : futureUnion.type;
+ // TODO(jmesserly): expose typeFormals on ParameterizedType.
+ List<TypeParameterElement> typeFormals = genericType is FunctionType
+ ? genericType.typeFormals
+ : genericType.typeParameters;
+ if (typeFormals.isEmpty) {
+ return genericType;
}
// Create a TypeSystem that will allow certain type parameters to be
@@ -420,20 +416,31 @@
// subtypes (or supertypes) as necessary, and track the constraints that
// are implied by this.
var inferringTypeSystem =
- new _StrongInferenceTypeSystem(typeProvider, this, fnType.typeFormals);
+ new _StrongInferenceTypeSystem(typeProvider, this, typeFormals);
if (returnContextType != null) {
- inferringTypeSystem.isSubtypeOf(fnType.returnType, returnContextType);
+ // If we're in a future union context, choose either the Future<T>
+ // or the T based on the declared return type.
+ if (returnContextType is FutureUnionType) {
+ var futureUnion = returnContextType as FutureUnionType;
+ returnContextType =
+ isSubtypeOf(declaredReturnType, typeProvider.futureDynamicType)
+ ? futureUnion.futureOfType
+ : futureUnion.type;
+ }
+
+ inferringTypeSystem.isSubtypeOf(declaredReturnType, returnContextType);
}
for (int i = 0; i < argumentTypes.length; i++) {
// Try to pass each argument to each parameter, recording any type
// parameter bounds that were implied by this assignment.
inferringTypeSystem.isSubtypeOf(
- argumentTypes[i], correspondingParameterTypes[i]);
+ argumentTypes[i], declaredParameterTypes[i]);
}
- return inferringTypeSystem._infer(fnType, errorReporter, errorNode);
+ return inferringTypeSystem._infer(
+ genericType, typeFormals, declaredReturnType, errorReporter, errorNode);
}
/**
@@ -566,6 +573,21 @@
!nonnullableTypes.contains(_getTypeFullyQualifiedName(type));
}
+ /// Check that [f1] is a subtype of [f2] for an override.
+ ///
+ /// This is different from the normal function subtyping in two ways:
+ /// - we know the function types are strict arrows,
+ /// - it allows opt-in covariant parameters.
+ bool isOverrideSubtypeOf(FunctionType f1, FunctionType f2) {
+ return FunctionTypeImpl.relate(
+ f1,
+ f2,
+ (t1, t2, t1Covariant, _) =>
+ isSubtypeOf(t2, t1) || t1Covariant && isSubtypeOf(t1, t2),
+ instantiateToBounds,
+ returnRelation: isSubtypeOf);
+ }
+
@override
bool isSubtypeOf(DartType leftType, DartType rightType) {
return _isSubtypeOf(leftType, rightType, null);
@@ -811,18 +833,15 @@
provider.dynamicType;
}
- /**
- * Check that [f1] is a subtype of [f2].
- *
- * This will always assume function types use fuzzy arrows, in other words
- * that dynamic parameters of f1 and f2 are treated as bottom.
- */
+ /// Check that [f1] is a subtype of [f2].
+ ///
+ /// This will always assume function types use fuzzy arrows, in other words
+ /// that dynamic parameters of f1 and f2 are treated as bottom.
bool _isFunctionSubtypeOf(FunctionType f1, FunctionType f2) {
return FunctionTypeImpl.relate(
f1,
f2,
- (DartType t1, DartType t2) =>
- _isSubtypeOf(t2, t1, null, dynamicIsBottom: true),
+ (t1, t2, _, __) => _isSubtypeOf(t2, t1, null, dynamicIsBottom: true),
instantiateToBounds,
returnRelation: isSubtypeOf);
}
@@ -1499,10 +1518,11 @@
/// Given the constraints that were given by calling [isSubtypeOf], find the
/// instantiation of the generic function that satisfies these constraints.
- FunctionType _infer(FunctionType fnType,
+ /*=T*/ _infer/*<T extends ParameterizedType>*/(/*=T*/ genericType,
+ List<TypeParameterElement> typeFormals, DartType declaredReturnType,
[ErrorReporter errorReporter, AstNode errorNode]) {
List<TypeParameterType> fnTypeParams =
- TypeParameterTypeImpl.getTypes(fnType.typeFormals);
+ TypeParameterTypeImpl.getTypes(typeFormals);
// Initialize the inferred type array.
//
@@ -1549,7 +1569,7 @@
//
// Otherwise we choose the more precise lower bound.
_TypeParameterVariance variance =
- new _TypeParameterVariance.from(typeParam, fnType.returnType);
+ new _TypeParameterVariance.from(typeParam, declaredReturnType);
_TypeParameterBound bound = _bounds[typeParam];
DartType lowerBound = bound.lower;
@@ -1584,11 +1604,13 @@
}
inferredTypes[i] =
- variance.passedIn || lowerBound.isBottom ? upperBound : lowerBound;
+ variance.passedIn && !upperBound.isDynamic || lowerBound.isBottom
+ ? upperBound
+ : lowerBound;
}
// Return the instantiated type.
- return fnType.instantiate(inferredTypes);
+ return genericType.instantiate(inferredTypes) as dynamic/*=T*/;
}
@override
diff --git a/pkg/analyzer/lib/src/plugin/engine_plugin.dart b/pkg/analyzer/lib/src/plugin/engine_plugin.dart
index ecf2e36..8166178 100644
--- a/pkg/analyzer/lib/src/plugin/engine_plugin.dart
+++ b/pkg/analyzer/lib/src/plugin/engine_plugin.dart
@@ -4,10 +4,10 @@
library analyzer.src.plugin.engine_plugin;
+import 'package:analyzer/error/error.dart' show AnalysisError;
import 'package:analyzer/plugin/task.dart';
import 'package:analyzer/src/generated/engine.dart'
show InternalAnalysisContext;
-import 'package:analyzer/src/generated/error.dart' show AnalysisError;
import 'package:analyzer/src/task/dart.dart';
import 'package:analyzer/src/task/dart_work_manager.dart';
import 'package:analyzer/src/task/general.dart';
diff --git a/pkg/analyzer/lib/src/services/lint.dart b/pkg/analyzer/lib/src/services/lint.dart
index 3eea1b7..795b032 100644
--- a/pkg/analyzer/lib/src/services/lint.dart
+++ b/pkg/analyzer/lib/src/services/lint.dart
@@ -7,8 +7,8 @@
import 'dart:collection';
import 'package:analyzer/dart/ast/ast.dart';
+import 'package:analyzer/error/listener.dart';
import 'package:analyzer/src/generated/engine.dart';
-import 'package:analyzer/src/generated/error.dart';
import 'package:analyzer/src/task/model.dart';
import 'package:analyzer/task/model.dart';
diff --git a/pkg/analyzer/lib/src/summary/format.dart b/pkg/analyzer/lib/src/summary/format.dart
index 641287e..2f7fc97 100644
--- a/pkg/analyzer/lib/src/summary/format.dart
+++ b/pkg/analyzer/lib/src/summary/format.dart
@@ -12,19 +12,6 @@
import 'dart:convert' as convert;
import 'api_signature.dart' as api_sig;
-class _CacheSourceKindReader extends fb.Reader<idl.CacheSourceKind> {
- const _CacheSourceKindReader() : super();
-
- @override
- int get size => 1;
-
- @override
- idl.CacheSourceKind read(fb.BufferContext bc, int offset) {
- int index = const fb.Uint8Reader().read(bc, offset);
- return index < idl.CacheSourceKind.values.length ? idl.CacheSourceKind.values[index] : idl.CacheSourceKind.library;
- }
-}
-
class _IndexNameKindReader extends fb.Reader<idl.IndexNameKind> {
const _IndexNameKindReader() : super();
@@ -142,497 +129,6 @@
}
}
-class CacheAnalysisErrorBuilder extends Object with _CacheAnalysisErrorMixin implements idl.CacheAnalysisError {
- String _correction;
- String _errorCodeUniqueName;
- int _length;
- String _message;
- int _offset;
-
- @override
- String get correction => _correction ??= '';
-
- /**
- * The correction to be displayed for this error, or `null` if there is no
- * correction information for this error. The correction should indicate how
- * the user can fix the error.
- */
- void set correction(String _value) {
- _correction = _value;
- }
-
- @override
- String get errorCodeUniqueName => _errorCodeUniqueName ??= '';
-
- /**
- * The unique name of the error code.
- */
- void set errorCodeUniqueName(String _value) {
- _errorCodeUniqueName = _value;
- }
-
- @override
- int get length => _length ??= 0;
-
- /**
- * Length of the error range.
- */
- void set length(int _value) {
- assert(_value == null || _value >= 0);
- _length = _value;
- }
-
- @override
- String get message => _message ??= '';
-
- /**
- * The message to be displayed for this error. The message should indicate
- * what is wrong and why it is wrong.
- */
- void set message(String _value) {
- _message = _value;
- }
-
- @override
- int get offset => _offset ??= 0;
-
- /**
- * Offset of the error range relative to the beginning of the file.
- */
- void set offset(int _value) {
- assert(_value == null || _value >= 0);
- _offset = _value;
- }
-
- CacheAnalysisErrorBuilder({String correction, String errorCodeUniqueName, int length, String message, int offset})
- : _correction = correction,
- _errorCodeUniqueName = errorCodeUniqueName,
- _length = length,
- _message = message,
- _offset = offset;
-
- /**
- * Flush [informative] data recursively.
- */
- void flushInformative() {
- }
-
- /**
- * Accumulate non-[informative] data into [signature].
- */
- void collectApiSignature(api_sig.ApiSignature signature) {
- signature.addString(this._errorCodeUniqueName ?? '');
- signature.addInt(this._offset ?? 0);
- signature.addInt(this._length ?? 0);
- signature.addString(this._message ?? '');
- signature.addString(this._correction ?? '');
- }
-
- fb.Offset finish(fb.Builder fbBuilder) {
- fb.Offset offset_correction;
- fb.Offset offset_errorCodeUniqueName;
- fb.Offset offset_message;
- if (_correction != null) {
- offset_correction = fbBuilder.writeString(_correction);
- }
- if (_errorCodeUniqueName != null) {
- offset_errorCodeUniqueName = fbBuilder.writeString(_errorCodeUniqueName);
- }
- if (_message != null) {
- offset_message = fbBuilder.writeString(_message);
- }
- fbBuilder.startTable();
- if (offset_correction != null) {
- fbBuilder.addOffset(4, offset_correction);
- }
- if (offset_errorCodeUniqueName != null) {
- fbBuilder.addOffset(0, offset_errorCodeUniqueName);
- }
- if (_length != null && _length != 0) {
- fbBuilder.addUint32(2, _length);
- }
- if (offset_message != null) {
- fbBuilder.addOffset(3, offset_message);
- }
- if (_offset != null && _offset != 0) {
- fbBuilder.addUint32(1, _offset);
- }
- return fbBuilder.endTable();
- }
-}
-
-class _CacheAnalysisErrorReader extends fb.TableReader<_CacheAnalysisErrorImpl> {
- const _CacheAnalysisErrorReader();
-
- @override
- _CacheAnalysisErrorImpl createObject(fb.BufferContext bc, int offset) => new _CacheAnalysisErrorImpl(bc, offset);
-}
-
-class _CacheAnalysisErrorImpl extends Object with _CacheAnalysisErrorMixin implements idl.CacheAnalysisError {
- final fb.BufferContext _bc;
- final int _bcOffset;
-
- _CacheAnalysisErrorImpl(this._bc, this._bcOffset);
-
- String _correction;
- String _errorCodeUniqueName;
- int _length;
- String _message;
- int _offset;
-
- @override
- String get correction {
- _correction ??= const fb.StringReader().vTableGet(_bc, _bcOffset, 4, '');
- return _correction;
- }
-
- @override
- String get errorCodeUniqueName {
- _errorCodeUniqueName ??= const fb.StringReader().vTableGet(_bc, _bcOffset, 0, '');
- return _errorCodeUniqueName;
- }
-
- @override
- int get length {
- _length ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 2, 0);
- return _length;
- }
-
- @override
- String get message {
- _message ??= const fb.StringReader().vTableGet(_bc, _bcOffset, 3, '');
- return _message;
- }
-
- @override
- int get offset {
- _offset ??= const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 1, 0);
- return _offset;
- }
-}
-
-abstract class _CacheAnalysisErrorMixin implements idl.CacheAnalysisError {
- @override
- Map<String, Object> toJson() {
- Map<String, Object> _result = <String, Object>{};
- if (correction != '') _result["correction"] = correction;
- if (errorCodeUniqueName != '') _result["errorCodeUniqueName"] = errorCodeUniqueName;
- if (length != 0) _result["length"] = length;
- if (message != '') _result["message"] = message;
- if (offset != 0) _result["offset"] = offset;
- return _result;
- }
-
- @override
- Map<String, Object> toMap() => {
- "correction": correction,
- "errorCodeUniqueName": errorCodeUniqueName,
- "length": length,
- "message": message,
- "offset": offset,
- };
-
- @override
- String toString() => convert.JSON.encode(toJson());
-}
-
-class CacheSourceContentBuilder extends Object with _CacheSourceContentMixin implements idl.CacheSourceContent {
- List<String> _exportedUris;
- List<String> _importedUris;
- idl.CacheSourceKind _kind;
- List<String> _partUris;
-
- @override
- List<String> get exportedUris => _exportedUris ??= <String>[];
-
- /**
- * The list of exported URIs, e.g. `dart:core`, or `foo/bar.dart`,
- * or `package:foo/bar.dart`. Empty if [kind] is [CacheSourceKind.part].
- */
- void set exportedUris(List<String> _value) {
- _exportedUris = _value;
- }
-
- @override
- List<String> get importedUris => _importedUris ??= <String>[];
-
- /**
- * The list of explicitly imported URIs, e.g. `dart:core`, or `foo/bar.dart`,
- * or `package:foo/bar.dart`. Empty if [kind] is [CacheSourceKind.part].
- */
- void set importedUris(List<String> _value) {
- _importedUris = _value;
- }
-
- @override
- idl.CacheSourceKind get kind => _kind ??= idl.CacheSourceKind.library;
-
- /**
- * The kind of the source.
- */
- void set kind(idl.CacheSourceKind _value) {
- _kind = _value;
- }
-
- @override
- List<String> get partUris => _partUris ??= <String>[];
-
- /**
- * The list of part URIs, e.g. `foo/bar.dart`. Empty if [kind] is
- * [CacheSourceKind.part].
- */
- void set partUris(List<String> _value) {
- _partUris = _value;
- }
-
- CacheSourceContentBuilder({List<String> exportedUris, List<String> importedUris, idl.CacheSourceKind kind, List<String> partUris})
- : _exportedUris = exportedUris,
- _importedUris = importedUris,
- _kind = kind,
- _partUris = partUris;
-
- /**
- * Flush [informative] data recursively.
- */
- void flushInformative() {
- }
-
- /**
- * Accumulate non-[informative] data into [signature].
- */
- void collectApiSignature(api_sig.ApiSignature signature) {
- signature.addInt(this._kind == null ? 0 : this._kind.index);
- if (this._importedUris == null) {
- signature.addInt(0);
- } else {
- signature.addInt(this._importedUris.length);
- for (var x in this._importedUris) {
- signature.addString(x);
- }
- }
- if (this._exportedUris == null) {
- signature.addInt(0);
- } else {
- signature.addInt(this._exportedUris.length);
- for (var x in this._exportedUris) {
- signature.addString(x);
- }
- }
- if (this._partUris == null) {
- signature.addInt(0);
- } else {
- signature.addInt(this._partUris.length);
- for (var x in this._partUris) {
- signature.addString(x);
- }
- }
- }
-
- List<int> toBuffer() {
- fb.Builder fbBuilder = new fb.Builder();
- return fbBuilder.finish(finish(fbBuilder), "CaSS");
- }
-
- fb.Offset finish(fb.Builder fbBuilder) {
- fb.Offset offset_exportedUris;
- fb.Offset offset_importedUris;
- fb.Offset offset_partUris;
- if (!(_exportedUris == null || _exportedUris.isEmpty)) {
- offset_exportedUris = fbBuilder.writeList(_exportedUris.map((b) => fbBuilder.writeString(b)).toList());
- }
- if (!(_importedUris == null || _importedUris.isEmpty)) {
- offset_importedUris = fbBuilder.writeList(_importedUris.map((b) => fbBuilder.writeString(b)).toList());
- }
- if (!(_partUris == null || _partUris.isEmpty)) {
- offset_partUris = fbBuilder.writeList(_partUris.map((b) => fbBuilder.writeString(b)).toList());
- }
- fbBuilder.startTable();
- if (offset_exportedUris != null) {
- fbBuilder.addOffset(2, offset_exportedUris);
- }
- if (offset_importedUris != null) {
- fbBuilder.addOffset(1, offset_importedUris);
- }
- if (_kind != null && _kind != idl.CacheSourceKind.library) {
- fbBuilder.addUint8(0, _kind.index);
- }
- if (offset_partUris != null) {
- fbBuilder.addOffset(3, offset_partUris);
- }
- return fbBuilder.endTable();
- }
-}
-
-idl.CacheSourceContent readCacheSourceContent(List<int> buffer) {
- fb.BufferContext rootRef = new fb.BufferContext.fromBytes(buffer);
- return const _CacheSourceContentReader().read(rootRef, 0);
-}
-
-class _CacheSourceContentReader extends fb.TableReader<_CacheSourceContentImpl> {
- const _CacheSourceContentReader();
-
- @override
- _CacheSourceContentImpl createObject(fb.BufferContext bc, int offset) => new _CacheSourceContentImpl(bc, offset);
-}
-
-class _CacheSourceContentImpl extends Object with _CacheSourceContentMixin implements idl.CacheSourceContent {
- final fb.BufferContext _bc;
- final int _bcOffset;
-
- _CacheSourceContentImpl(this._bc, this._bcOffset);
-
- List<String> _exportedUris;
- List<String> _importedUris;
- idl.CacheSourceKind _kind;
- List<String> _partUris;
-
- @override
- List<String> get exportedUris {
- _exportedUris ??= const fb.ListReader<String>(const fb.StringReader()).vTableGet(_bc, _bcOffset, 2, const <String>[]);
- return _exportedUris;
- }
-
- @override
- List<String> get importedUris {
- _importedUris ??= const fb.ListReader<String>(const fb.StringReader()).vTableGet(_bc, _bcOffset, 1, const <String>[]);
- return _importedUris;
- }
-
- @override
- idl.CacheSourceKind get kind {
- _kind ??= const _CacheSourceKindReader().vTableGet(_bc, _bcOffset, 0, idl.CacheSourceKind.library);
- return _kind;
- }
-
- @override
- List<String> get partUris {
- _partUris ??= const fb.ListReader<String>(const fb.StringReader()).vTableGet(_bc, _bcOffset, 3, const <String>[]);
- return _partUris;
- }
-}
-
-abstract class _CacheSourceContentMixin implements idl.CacheSourceContent {
- @override
- Map<String, Object> toJson() {
- Map<String, Object> _result = <String, Object>{};
- if (exportedUris.isNotEmpty) _result["exportedUris"] = exportedUris;
- if (importedUris.isNotEmpty) _result["importedUris"] = importedUris;
- if (kind != idl.CacheSourceKind.library) _result["kind"] = kind.toString().split('.')[1];
- if (partUris.isNotEmpty) _result["partUris"] = partUris;
- return _result;
- }
-
- @override
- Map<String, Object> toMap() => {
- "exportedUris": exportedUris,
- "importedUris": importedUris,
- "kind": kind,
- "partUris": partUris,
- };
-
- @override
- String toString() => convert.JSON.encode(toJson());
-}
-
-class CacheSourceErrorsInLibraryBuilder extends Object with _CacheSourceErrorsInLibraryMixin implements idl.CacheSourceErrorsInLibrary {
- List<CacheAnalysisErrorBuilder> _errors;
-
- @override
- List<CacheAnalysisErrorBuilder> get errors => _errors ??= <CacheAnalysisErrorBuilder>[];
-
- /**
- * The list of errors in the source in the library.
- */
- void set errors(List<CacheAnalysisErrorBuilder> _value) {
- _errors = _value;
- }
-
- CacheSourceErrorsInLibraryBuilder({List<CacheAnalysisErrorBuilder> errors})
- : _errors = errors;
-
- /**
- * Flush [informative] data recursively.
- */
- void flushInformative() {
- _errors?.forEach((b) => b.flushInformative());
- }
-
- /**
- * Accumulate non-[informative] data into [signature].
- */
- void collectApiSignature(api_sig.ApiSignature signature) {
- if (this._errors == null) {
- signature.addInt(0);
- } else {
- signature.addInt(this._errors.length);
- for (var x in this._errors) {
- x?.collectApiSignature(signature);
- }
- }
- }
-
- List<int> toBuffer() {
- fb.Builder fbBuilder = new fb.Builder();
- return fbBuilder.finish(finish(fbBuilder), "CSEL");
- }
-
- fb.Offset finish(fb.Builder fbBuilder) {
- fb.Offset offset_errors;
- if (!(_errors == null || _errors.isEmpty)) {
- offset_errors = fbBuilder.writeList(_errors.map((b) => b.finish(fbBuilder)).toList());
- }
- fbBuilder.startTable();
- if (offset_errors != null) {
- fbBuilder.addOffset(0, offset_errors);
- }
- return fbBuilder.endTable();
- }
-}
-
-idl.CacheSourceErrorsInLibrary readCacheSourceErrorsInLibrary(List<int> buffer) {
- fb.BufferContext rootRef = new fb.BufferContext.fromBytes(buffer);
- return const _CacheSourceErrorsInLibraryReader().read(rootRef, 0);
-}
-
-class _CacheSourceErrorsInLibraryReader extends fb.TableReader<_CacheSourceErrorsInLibraryImpl> {
- const _CacheSourceErrorsInLibraryReader();
-
- @override
- _CacheSourceErrorsInLibraryImpl createObject(fb.BufferContext bc, int offset) => new _CacheSourceErrorsInLibraryImpl(bc, offset);
-}
-
-class _CacheSourceErrorsInLibraryImpl extends Object with _CacheSourceErrorsInLibraryMixin implements idl.CacheSourceErrorsInLibrary {
- final fb.BufferContext _bc;
- final int _bcOffset;
-
- _CacheSourceErrorsInLibraryImpl(this._bc, this._bcOffset);
-
- List<idl.CacheAnalysisError> _errors;
-
- @override
- List<idl.CacheAnalysisError> get errors {
- _errors ??= const fb.ListReader<idl.CacheAnalysisError>(const _CacheAnalysisErrorReader()).vTableGet(_bc, _bcOffset, 0, const <idl.CacheAnalysisError>[]);
- return _errors;
- }
-}
-
-abstract class _CacheSourceErrorsInLibraryMixin implements idl.CacheSourceErrorsInLibrary {
- @override
- Map<String, Object> toJson() {
- Map<String, Object> _result = <String, Object>{};
- if (errors.isNotEmpty) _result["errors"] = errors.map((_value) => _value.toJson()).toList();
- return _result;
- }
-
- @override
- Map<String, Object> toMap() => {
- "errors": errors,
- };
-
- @override
- String toString() => convert.JSON.encode(toJson());
-}
-
class CodeRangeBuilder extends Object with _CodeRangeMixin implements idl.CodeRange {
int _length;
int _offset;
@@ -643,9 +139,9 @@
/**
* Length of the element code.
*/
- void set length(int _value) {
- assert(_value == null || _value >= 0);
- _length = _value;
+ void set length(int value) {
+ assert(value == null || value >= 0);
+ this._length = value;
}
@override
@@ -654,9 +150,9 @@
/**
* Offset of the element code relative to the beginning of the file.
*/
- void set offset(int _value) {
- assert(_value == null || _value >= 0);
- _offset = _value;
+ void set offset(int value) {
+ assert(value == null || value >= 0);
+ this._offset = value;
}
CodeRangeBuilder({int length, int offset})
@@ -771,9 +267,9 @@
* generic class, then the type arguments in [typeArguments] are applied
* first to the class and then to the method.
*/
- void set implicitFunctionTypeIndices(List<int> _value) {
- assert(_value == null || _value.every((e) => e >= 0));
- _implicitFunctionTypeIndices = _value;
+ void set implicitFunctionTypeIndices(List<int> value) {
+ assert(value == null || value.every((e) => e >= 0));
+ this._implicitFunctionTypeIndices = value;
}
@override
@@ -798,9 +294,9 @@
* If the type being referred to is not a type parameter, [paramReference] is
* zero.
*/
- void set paramReference(int _value) {
- assert(_value == null || _value >= 0);
- _paramReference = _value;
+ void set paramReference(int value) {
+ assert(value == null || value >= 0);
+ this._paramReference = value;
}
@override
@@ -810,9 +306,9 @@
* Index into [UnlinkedUnit.references] for the entity being referred to, or
* zero if this is a reference to a type parameter.
*/
- void set reference(int _value) {
- assert(_value == null || _value >= 0);
- _reference = _value;
+ void set reference(int value) {
+ assert(value == null || value >= 0);
+ this._reference = value;
}
@override
@@ -825,9 +321,9 @@
*
* Otherwise zero.
*/
- void set slot(int _value) {
- assert(_value == null || _value >= 0);
- _slot = _value;
+ void set slot(int value) {
+ assert(value == null || value >= 0);
+ this._slot = value;
}
@override
@@ -839,8 +335,8 @@
* synthesized by a LUB computation), the function parameters. Otherwise
* empty.
*/
- void set syntheticParams(List<UnlinkedParamBuilder> _value) {
- _syntheticParams = _value;
+ void set syntheticParams(List<UnlinkedParamBuilder> value) {
+ this._syntheticParams = value;
}
@override
@@ -852,8 +348,8 @@
* synthesized by a LUB computation), the return type of the function.
* Otherwise `null`.
*/
- void set syntheticReturnType(EntityRefBuilder _value) {
- _syntheticReturnType = _value;
+ void set syntheticReturnType(EntityRefBuilder value) {
+ this._syntheticReturnType = value;
}
@override
@@ -863,8 +359,8 @@
* If this is an instantiation of a generic type or generic executable, the
* type arguments used to instantiate it (if any).
*/
- void set typeArguments(List<EntityRefBuilder> _value) {
- _typeArguments = _value;
+ void set typeArguments(List<EntityRefBuilder> value) {
+ this._typeArguments = value;
}
EntityRefBuilder({List<int> implicitFunctionTypeIndices, int paramReference, int reference, int slot, List<UnlinkedParamBuilder> syntheticParams, EntityRefBuilder syntheticReturnType, List<EntityRefBuilder> typeArguments})
@@ -1067,8 +563,8 @@
* URI for the compilation units listed in the library's `part` declarations.
* These URIs are relative to the importing library.
*/
- void set parts(List<String> _value) {
- _parts = _value;
+ void set parts(List<String> value) {
+ this._parts = value;
}
@override
@@ -1081,8 +577,8 @@
* `d/e.dart`, the URI listed for `a.dart`'s dependency on `e.dart` will be
* `b/d/e.dart`.
*/
- void set uri(String _value) {
- _uri = _value;
+ void set uri(String value) {
+ this._uri = value;
}
LinkedDependencyBuilder({List<String> parts, String uri})
@@ -1191,9 +687,9 @@
* Index into [LinkedLibrary.dependencies] for the library in which the
* entity is defined.
*/
- void set dependency(int _value) {
- assert(_value == null || _value >= 0);
- _dependency = _value;
+ void set dependency(int value) {
+ assert(value == null || value >= 0);
+ this._dependency = value;
}
@override
@@ -1202,8 +698,8 @@
/**
* The kind of the entity being referred to.
*/
- void set kind(idl.ReferenceKind _value) {
- _kind = _value;
+ void set kind(idl.ReferenceKind value) {
+ this._kind = value;
}
@override
@@ -1213,8 +709,8 @@
* Name of the exported entity. For an exported setter, this name includes
* the trailing '='.
*/
- void set name(String _value) {
- _name = _value;
+ void set name(String value) {
+ this._name = value;
}
@override
@@ -1226,9 +722,9 @@
* zero represents the defining compilation unit, and nonzero values
* represent parts in the order of the corresponding `part` declarations.
*/
- void set unit(int _value) {
- assert(_value == null || _value >= 0);
- _unit = _value;
+ void set unit(int value) {
+ assert(value == null || value >= 0);
+ this._unit = value;
}
LinkedExportNameBuilder({int dependency, idl.ReferenceKind kind, String name, int unit})
@@ -1369,8 +865,8 @@
* anti-dependency (e.g. the result of type propagation or type inference
* depends on the lack of a certain declaration in the library).
*/
- void set dependencies(List<LinkedDependencyBuilder> _value) {
- _dependencies = _value;
+ void set dependencies(List<LinkedDependencyBuilder> value) {
+ this._dependencies = value;
}
@override
@@ -1380,9 +876,9 @@
* For each export in [UnlinkedUnit.exports], an index into [dependencies]
* of the library being exported.
*/
- void set exportDependencies(List<int> _value) {
- assert(_value == null || _value.every((e) => e >= 0));
- _exportDependencies = _value;
+ void set exportDependencies(List<int> value) {
+ assert(value == null || value.every((e) => e >= 0));
+ this._exportDependencies = value;
}
@override
@@ -1395,8 +891,8 @@
*
* Sorted by name.
*/
- void set exportNames(List<LinkedExportNameBuilder> _value) {
- _exportNames = _value;
+ void set exportNames(List<LinkedExportNameBuilder> value) {
+ this._exportNames = value;
}
@override
@@ -1406,8 +902,8 @@
* Indicates whether this library was summarized in "fallback mode". If
* true, all other fields in the data structure have their default values.
*/
- void set fallbackMode(bool _value) {
- _fallbackMode = _value;
+ void set fallbackMode(bool value) {
+ this._fallbackMode = value;
}
@override
@@ -1417,9 +913,9 @@
* For each import in [UnlinkedUnit.imports], an index into [dependencies]
* of the library being imported.
*/
- void set importDependencies(List<int> _value) {
- assert(_value == null || _value.every((e) => e >= 0));
- _importDependencies = _value;
+ void set importDependencies(List<int> value) {
+ assert(value == null || value.every((e) => e >= 0));
+ this._importDependencies = value;
}
@override
@@ -1430,9 +926,9 @@
* dependencies (that is, the number of libraries in the direct imports plus
* the transitive closure of exports, plus the library itself).
*/
- void set numPrelinkedDependencies(int _value) {
- assert(_value == null || _value >= 0);
- _numPrelinkedDependencies = _value;
+ void set numPrelinkedDependencies(int value) {
+ assert(value == null || value >= 0);
+ this._numPrelinkedDependencies = value;
}
@override
@@ -1444,8 +940,8 @@
* followed by the summary of each part, in the order of the `part`
* declarations in the defining compilation unit.
*/
- void set units(List<LinkedUnitBuilder> _value) {
- _units = _value;
+ void set units(List<LinkedUnitBuilder> value) {
+ this._units = value;
}
LinkedLibraryBuilder({List<LinkedDependencyBuilder> dependencies, List<int> exportDependencies, List<LinkedExportNameBuilder> exportNames, bool fallbackMode, List<int> importDependencies, int numPrelinkedDependencies, List<LinkedUnitBuilder> units})
@@ -1687,9 +1183,9 @@
* LinkedUnit.references[i].containingReference != 0, then
* LinkedUnit.references[i].containingReference < i.
*/
- void set containingReference(int _value) {
- assert(_value == null || _value >= 0);
- _containingReference = _value;
+ void set containingReference(int value) {
+ assert(value == null || value >= 0);
+ this._containingReference = value;
}
@override
@@ -1702,9 +1198,9 @@
* Zero if this entity is contained within another entity (e.g. a class
* member), or if [kind] is [ReferenceKind.prefix].
*/
- void set dependency(int _value) {
- assert(_value == null || _value >= 0);
- _dependency = _value;
+ void set dependency(int value) {
+ assert(value == null || value >= 0);
+ this._dependency = value;
}
@override
@@ -1714,8 +1210,8 @@
* The kind of the entity being referred to. For the pseudo-types `dynamic`
* and `void`, the kind is [ReferenceKind.classOrEnum].
*/
- void set kind(idl.ReferenceKind _value) {
- _kind = _value;
+ void set kind(idl.ReferenceKind value) {
+ this._kind = value;
}
@override
@@ -1728,9 +1224,9 @@
* [ReferenceKind.variable], the index of the variable within
* [UnlinkedExecutable.localVariables]. Otherwise zero.
*/
- void set localIndex(int _value) {
- assert(_value == null || _value >= 0);
- _localIndex = _value;
+ void set localIndex(int value) {
+ assert(value == null || value >= 0);
+ this._localIndex = value;
}
@override
@@ -1741,8 +1237,8 @@
* name of the entity being referred to. For the pseudo-type `dynamic`, the
* string is "dynamic". For the pseudo-type `void`, the string is "void".
*/
- void set name(String _value) {
- _name = _value;
+ void set name(String value) {
+ this._name = value;
}
@override
@@ -1753,9 +1249,9 @@
* it declares (does not include type parameters of enclosing entities).
* Otherwise zero.
*/
- void set numTypeParameters(int _value) {
- assert(_value == null || _value >= 0);
- _numTypeParameters = _value;
+ void set numTypeParameters(int value) {
+ assert(value == null || value >= 0);
+ this._numTypeParameters = value;
}
@override
@@ -1770,9 +1266,9 @@
* Zero if this entity is contained within another entity (e.g. a class
* member).
*/
- void set unit(int _value) {
- assert(_value == null || _value >= 0);
- _unit = _value;
+ void set unit(int value) {
+ assert(value == null || value >= 0);
+ this._unit = value;
}
LinkedReferenceBuilder({int containingReference, int dependency, idl.ReferenceKind kind, int localIndex, String name, int numTypeParameters, int unit})
@@ -1939,9 +1435,9 @@
* List of slot ids (referring to [UnlinkedExecutable.constCycleSlot])
* corresponding to const constructors that are part of cycles.
*/
- void set constCycles(List<int> _value) {
- assert(_value == null || _value.every((e) => e >= 0));
- _constCycles = _value;
+ void set constCycles(List<int> value) {
+ assert(value == null || value.every((e) => e >= 0));
+ this._constCycles = value;
}
@override
@@ -1955,8 +1451,8 @@
* additional elements are references that are only referred to implicitly
* (e.g. elements involved in inferred or propagated types).
*/
- void set references(List<LinkedReferenceBuilder> _value) {
- _references = _value;
+ void set references(List<LinkedReferenceBuilder> value) {
+ this._references = value;
}
@override
@@ -1966,8 +1462,8 @@
* List associating slot ids found inside the unlinked summary for the
* compilation unit with propagated and inferred types.
*/
- void set types(List<EntityRefBuilder> _value) {
- _types = _value;
+ void set types(List<EntityRefBuilder> value) {
+ this._types = value;
}
LinkedUnitBuilder({List<int> constCycles, List<LinkedReferenceBuilder> references, List<EntityRefBuilder> types})
@@ -2116,8 +1612,8 @@
* including this one). This can be used to identify when the API of a
* package may have changed.
*/
- void set apiSignature(String _value) {
- _apiSignature = _value;
+ void set apiSignature(String value) {
+ this._apiSignature = value;
}
@override
@@ -2126,8 +1622,8 @@
/**
* Information about the packages this package depends on, if known.
*/
- void set dependencies(List<PackageDependencyInfoBuilder> _value) {
- _dependencies = _value;
+ void set dependencies(List<PackageDependencyInfoBuilder> value) {
+ this._dependencies = value;
}
@override
@@ -2136,8 +1632,8 @@
/**
* Linked libraries.
*/
- void set linkedLibraries(List<LinkedLibraryBuilder> _value) {
- _linkedLibraries = _value;
+ void set linkedLibraries(List<LinkedLibraryBuilder> value) {
+ this._linkedLibraries = value;
}
@override
@@ -2147,8 +1643,8 @@
* The list of URIs of items in [linkedLibraries], e.g. `dart:core` or
* `package:foo/bar.dart`.
*/
- void set linkedLibraryUris(List<String> _value) {
- _linkedLibraryUris = _value;
+ void set linkedLibraryUris(List<String> value) {
+ this._linkedLibraryUris = value;
}
@override
@@ -2158,9 +1654,9 @@
* Major version of the summary format. See
* [PackageBundleAssembler.currentMajorVersion].
*/
- void set majorVersion(int _value) {
- assert(_value == null || _value >= 0);
- _majorVersion = _value;
+ void set majorVersion(int value) {
+ assert(value == null || value >= 0);
+ this._majorVersion = value;
}
@override
@@ -2170,9 +1666,9 @@
* Minor version of the summary format. See
* [PackageBundleAssembler.currentMinorVersion].
*/
- void set minorVersion(int _value) {
- assert(_value == null || _value >= 0);
- _minorVersion = _value;
+ void set minorVersion(int value) {
+ assert(value == null || value >= 0);
+ this._minorVersion = value;
}
@override
@@ -2182,8 +1678,8 @@
* List of MD5 hashes of the files listed in [unlinkedUnitUris]. Each hash
* is encoded as a hexadecimal string using lower case letters.
*/
- void set unlinkedUnitHashes(List<String> _value) {
- _unlinkedUnitHashes = _value;
+ void set unlinkedUnitHashes(List<String> value) {
+ this._unlinkedUnitHashes = value;
}
@override
@@ -2192,8 +1688,8 @@
/**
* Unlinked information for the compilation units constituting the package.
*/
- void set unlinkedUnits(List<UnlinkedUnitBuilder> _value) {
- _unlinkedUnits = _value;
+ void set unlinkedUnits(List<UnlinkedUnitBuilder> value) {
+ this._unlinkedUnits = value;
}
@override
@@ -2202,8 +1698,8 @@
/**
* The list of URIs of items in [unlinkedUnits], e.g. `dart:core/bool.dart`.
*/
- void set unlinkedUnitUris(List<String> _value) {
- _unlinkedUnitUris = _value;
+ void set unlinkedUnitUris(List<String> value) {
+ this._unlinkedUnitUris = value;
}
PackageBundleBuilder({String apiSignature, List<PackageDependencyInfoBuilder> dependencies, List<LinkedLibraryBuilder> linkedLibraries, List<String> linkedLibraryUris, int majorVersion, int minorVersion, List<String> unlinkedUnitHashes, List<UnlinkedUnitBuilder> unlinkedUnits, List<String> unlinkedUnitUris})
@@ -2463,8 +1959,8 @@
/**
* API signature of this dependency.
*/
- void set apiSignature(String _value) {
- _apiSignature = _value;
+ void set apiSignature(String value) {
+ this._apiSignature = value;
}
@override
@@ -2475,8 +1971,8 @@
* "package:<package_name>/...", a list of all such package names, sorted
* lexicographically. Otherwise empty.
*/
- void set includedPackageNames(List<String> _value) {
- _includedPackageNames = _value;
+ void set includedPackageNames(List<String> value) {
+ this._includedPackageNames = value;
}
@override
@@ -2486,8 +1982,8 @@
* Indicates whether this dependency summarizes any files whose URI takes the
* form "dart:...".
*/
- void set includesDartUris(bool _value) {
- _includesDartUris = _value;
+ void set includesDartUris(bool value) {
+ this._includesDartUris = value;
}
@override
@@ -2497,8 +1993,8 @@
* Indicates whether this dependency summarizes any files whose URI takes the
* form "file:...".
*/
- void set includesFileUris(bool _value) {
- _includesFileUris = _value;
+ void set includesFileUris(bool value) {
+ this._includesFileUris = value;
}
@override
@@ -2513,8 +2009,8 @@
*
* Absent if the path is not known.
*/
- void set summaryPath(String _value) {
- _summaryPath = _value;
+ void set summaryPath(String value) {
+ this._summaryPath = value;
}
PackageDependencyInfoBuilder({String apiSignature, List<String> includedPackageNames, bool includesDartUris, bool includesFileUris, String summaryPath})
@@ -2674,8 +2170,8 @@
* Each item of this list corresponds to a unique referenced element. It is
* the kind of the synthetic element.
*/
- void set elementKinds(List<idl.IndexSyntheticElementKind> _value) {
- _elementKinds = _value;
+ void set elementKinds(List<idl.IndexSyntheticElementKind> value) {
+ this._elementKinds = value;
}
@override
@@ -2688,9 +2184,9 @@
* client can quickly check whether an element is referenced in this
* [PackageIndex].
*/
- void set elementNameClassMemberIds(List<int> _value) {
- assert(_value == null || _value.every((e) => e >= 0));
- _elementNameClassMemberIds = _value;
+ void set elementNameClassMemberIds(List<int> value) {
+ assert(value == null || value.every((e) => e >= 0));
+ this._elementNameClassMemberIds = value;
}
@override
@@ -2703,9 +2199,9 @@
* client can quickly check whether an element is referenced in this
* [PackageIndex].
*/
- void set elementNameParameterIds(List<int> _value) {
- assert(_value == null || _value.every((e) => e >= 0));
- _elementNameParameterIds = _value;
+ void set elementNameParameterIds(List<int> value) {
+ assert(value == null || value.every((e) => e >= 0));
+ this._elementNameParameterIds = value;
}
@override
@@ -2717,9 +2213,9 @@
* the unit. The list is sorted in ascending order, so that the client can
* quickly check whether an element is referenced in this [PackageIndex].
*/
- void set elementNameUnitMemberIds(List<int> _value) {
- assert(_value == null || _value.every((e) => e >= 0));
- _elementNameUnitMemberIds = _value;
+ void set elementNameUnitMemberIds(List<int> value) {
+ assert(value == null || value.every((e) => e >= 0));
+ this._elementNameUnitMemberIds = value;
}
@override
@@ -2730,9 +2226,9 @@
* the index into [unitLibraryUris] and [unitUnitUris] for the library
* specific unit where the element is declared.
*/
- void set elementUnits(List<int> _value) {
- assert(_value == null || _value.every((e) => e >= 0));
- _elementUnits = _value;
+ void set elementUnits(List<int> value) {
+ assert(value == null || value.every((e) => e >= 0));
+ this._elementUnits = value;
}
@override
@@ -2743,8 +2239,8 @@
* sorted in ascending order, so that the client can quickly check the
* presence of a string in this [PackageIndex].
*/
- void set strings(List<String> _value) {
- _strings = _value;
+ void set strings(List<String> value) {
+ this._strings = value;
}
@override
@@ -2755,9 +2251,9 @@
* specific unit referenced in the [PackageIndex]. It is an index into
* [strings] list.
*/
- void set unitLibraryUris(List<int> _value) {
- assert(_value == null || _value.every((e) => e >= 0));
- _unitLibraryUris = _value;
+ void set unitLibraryUris(List<int> value) {
+ assert(value == null || value.every((e) => e >= 0));
+ this._unitLibraryUris = value;
}
@override
@@ -2766,8 +2262,8 @@
/**
* List of indexes of each unit in this [PackageIndex].
*/
- void set units(List<UnitIndexBuilder> _value) {
- _units = _value;
+ void set units(List<UnitIndexBuilder> value) {
+ this._units = value;
}
@override
@@ -2778,9 +2274,9 @@
* specific unit referenced in the [PackageIndex]. It is an index into
* [strings] list.
*/
- void set unitUnitUris(List<int> _value) {
- assert(_value == null || _value.every((e) => e >= 0));
- _unitUnitUris = _value;
+ void set unitUnitUris(List<int> value) {
+ assert(value == null || value.every((e) => e >= 0));
+ this._unitUnitUris = value;
}
PackageIndexBuilder({List<idl.IndexSyntheticElementKind> elementKinds, List<int> elementNameClassMemberIds, List<int> elementNameParameterIds, List<int> elementNameUnitMemberIds, List<int> elementUnits, List<String> strings, List<int> unitLibraryUris, List<UnitIndexBuilder> units, List<int> unitUnitUris})
@@ -3090,8 +2586,8 @@
/**
* Each item of this list is the kind of an element defined in this unit.
*/
- void set definedNameKinds(List<idl.IndexNameKind> _value) {
- _definedNameKinds = _value;
+ void set definedNameKinds(List<idl.IndexNameKind> value) {
+ this._definedNameKinds = value;
}
@override
@@ -3101,9 +2597,9 @@
* Each item of this list is the name offset of an element defined in this
* unit relative to the beginning of the file.
*/
- void set definedNameOffsets(List<int> _value) {
- assert(_value == null || _value.every((e) => e >= 0));
- _definedNameOffsets = _value;
+ void set definedNameOffsets(List<int> value) {
+ assert(value == null || value.every((e) => e >= 0));
+ this._definedNameOffsets = value;
}
@override
@@ -3115,9 +2611,9 @@
* ascending order, so that the client can quickly find name definitions in
* this [UnitIndex].
*/
- void set definedNames(List<int> _value) {
- assert(_value == null || _value.every((e) => e >= 0));
- _definedNames = _value;
+ void set definedNames(List<int> value) {
+ assert(value == null || value.every((e) => e >= 0));
+ this._definedNames = value;
}
@override
@@ -3127,9 +2623,9 @@
* Index into [PackageIndex.unitLibraryUris] and [PackageIndex.unitUnitUris]
* for the library specific unit that corresponds to this [UnitIndex].
*/
- void set unit(int _value) {
- assert(_value == null || _value >= 0);
- _unit = _value;
+ void set unit(int value) {
+ assert(value == null || value >= 0);
+ this._unit = value;
}
@override
@@ -3139,8 +2635,8 @@
* Each item of this list is the `true` if the corresponding element usage
* is qualified with some prefix.
*/
- void set usedElementIsQualifiedFlags(List<bool> _value) {
- _usedElementIsQualifiedFlags = _value;
+ void set usedElementIsQualifiedFlags(List<bool> value) {
+ this._usedElementIsQualifiedFlags = value;
}
@override
@@ -3149,8 +2645,8 @@
/**
* Each item of this list is the kind of the element usage.
*/
- void set usedElementKinds(List<idl.IndexRelationKind> _value) {
- _usedElementKinds = _value;
+ void set usedElementKinds(List<idl.IndexRelationKind> value) {
+ this._usedElementKinds = value;
}
@override
@@ -3159,9 +2655,9 @@
/**
* Each item of this list is the length of the element usage.
*/
- void set usedElementLengths(List<int> _value) {
- assert(_value == null || _value.every((e) => e >= 0));
- _usedElementLengths = _value;
+ void set usedElementLengths(List<int> value) {
+ assert(value == null || value.every((e) => e >= 0));
+ this._usedElementLengths = value;
}
@override
@@ -3171,9 +2667,9 @@
* Each item of this list is the offset of the element usage relative to the
* beginning of the file.
*/
- void set usedElementOffsets(List<int> _value) {
- assert(_value == null || _value.every((e) => e >= 0));
- _usedElementOffsets = _value;
+ void set usedElementOffsets(List<int> value) {
+ assert(value == null || value.every((e) => e >= 0));
+ this._usedElementOffsets = value;
}
@override
@@ -3184,9 +2680,9 @@
* [PackageIndex.elementOffsets]. The list is sorted in ascending order, so
* that the client can quickly find element references in this [UnitIndex].
*/
- void set usedElements(List<int> _value) {
- assert(_value == null || _value.every((e) => e >= 0));
- _usedElements = _value;
+ void set usedElements(List<int> value) {
+ assert(value == null || value.every((e) => e >= 0));
+ this._usedElements = value;
}
@override
@@ -3196,8 +2692,8 @@
* Each item of this list is the `true` if the corresponding name usage
* is qualified with some prefix.
*/
- void set usedNameIsQualifiedFlags(List<bool> _value) {
- _usedNameIsQualifiedFlags = _value;
+ void set usedNameIsQualifiedFlags(List<bool> value) {
+ this._usedNameIsQualifiedFlags = value;
}
@override
@@ -3206,8 +2702,8 @@
/**
* Each item of this list is the kind of the name usage.
*/
- void set usedNameKinds(List<idl.IndexRelationKind> _value) {
- _usedNameKinds = _value;
+ void set usedNameKinds(List<idl.IndexRelationKind> value) {
+ this._usedNameKinds = value;
}
@override
@@ -3217,9 +2713,9 @@
* Each item of this list is the offset of the name usage relative to the
* beginning of the file.
*/
- void set usedNameOffsets(List<int> _value) {
- assert(_value == null || _value.every((e) => e >= 0));
- _usedNameOffsets = _value;
+ void set usedNameOffsets(List<int> value) {
+ assert(value == null || value.every((e) => e >= 0));
+ this._usedNameOffsets = value;
}
@override
@@ -3230,9 +2726,9 @@
* used name. The list is sorted in ascending order, so that the client can
* quickly find name uses in this [UnitIndex].
*/
- void set usedNames(List<int> _value) {
- assert(_value == null || _value.every((e) => e >= 0));
- _usedNames = _value;
+ void set usedNames(List<int> value) {
+ assert(value == null || value.every((e) => e >= 0));
+ this._usedNames = value;
}
UnitIndexBuilder({List<idl.IndexNameKind> definedNameKinds, List<int> definedNameOffsets, List<int> definedNames, int unit, List<bool> usedElementIsQualifiedFlags, List<idl.IndexRelationKind> usedElementKinds, List<int> usedElementLengths, List<int> usedElementOffsets, List<int> usedElements, List<bool> usedNameIsQualifiedFlags, List<idl.IndexRelationKind> usedNameKinds, List<int> usedNameOffsets, List<int> usedNames})
@@ -3621,8 +3117,8 @@
/**
* Annotations for this class.
*/
- void set annotations(List<UnlinkedConstBuilder> _value) {
- _annotations = _value;
+ void set annotations(List<UnlinkedConstBuilder> value) {
+ this._annotations = value;
}
@override
@@ -3631,8 +3127,8 @@
/**
* Code range of the class.
*/
- void set codeRange(CodeRangeBuilder _value) {
- _codeRange = _value;
+ void set codeRange(CodeRangeBuilder value) {
+ this._codeRange = value;
}
@override
@@ -3642,8 +3138,8 @@
* Documentation comment for the class, or `null` if there is no
* documentation comment.
*/
- void set documentationComment(UnlinkedDocumentationCommentBuilder _value) {
- _documentationComment = _value;
+ void set documentationComment(UnlinkedDocumentationCommentBuilder value) {
+ this._documentationComment = value;
}
@override
@@ -3652,8 +3148,8 @@
/**
* Executable objects (methods, getters, and setters) contained in the class.
*/
- void set executables(List<UnlinkedExecutableBuilder> _value) {
- _executables = _value;
+ void set executables(List<UnlinkedExecutableBuilder> value) {
+ this._executables = value;
}
@override
@@ -3662,8 +3158,8 @@
/**
* Field declarations contained in the class.
*/
- void set fields(List<UnlinkedVariableBuilder> _value) {
- _fields = _value;
+ void set fields(List<UnlinkedVariableBuilder> value) {
+ this._fields = value;
}
@override
@@ -3673,8 +3169,8 @@
* Indicates whether this class is the core "Object" class (and hence has no
* supertype)
*/
- void set hasNoSupertype(bool _value) {
- _hasNoSupertype = _value;
+ void set hasNoSupertype(bool value) {
+ this._hasNoSupertype = value;
}
@override
@@ -3683,8 +3179,8 @@
/**
* Interfaces appearing in an `implements` clause, if any.
*/
- void set interfaces(List<EntityRefBuilder> _value) {
- _interfaces = _value;
+ void set interfaces(List<EntityRefBuilder> value) {
+ this._interfaces = value;
}
@override
@@ -3693,8 +3189,8 @@
/**
* Indicates whether the class is declared with the `abstract` keyword.
*/
- void set isAbstract(bool _value) {
- _isAbstract = _value;
+ void set isAbstract(bool value) {
+ this._isAbstract = value;
}
@override
@@ -3703,8 +3199,8 @@
/**
* Indicates whether the class is declared using mixin application syntax.
*/
- void set isMixinApplication(bool _value) {
- _isMixinApplication = _value;
+ void set isMixinApplication(bool value) {
+ this._isMixinApplication = value;
}
@override
@@ -3713,8 +3209,8 @@
/**
* Mixins appearing in a `with` clause, if any.
*/
- void set mixins(List<EntityRefBuilder> _value) {
- _mixins = _value;
+ void set mixins(List<EntityRefBuilder> value) {
+ this._mixins = value;
}
@override
@@ -3723,8 +3219,8 @@
/**
* Name of the class.
*/
- void set name(String _value) {
- _name = _value;
+ void set name(String value) {
+ this._name = value;
}
@override
@@ -3733,9 +3229,9 @@
/**
* Offset of the class name relative to the beginning of the file.
*/
- void set nameOffset(int _value) {
- assert(_value == null || _value >= 0);
- _nameOffset = _value;
+ void set nameOffset(int value) {
+ assert(value == null || value >= 0);
+ this._nameOffset = value;
}
@override
@@ -3746,8 +3242,8 @@
* explicitly declare a supertype (and hence has supertype `Object`), or (b)
* the class *is* `Object` (and hence has no supertype).
*/
- void set supertype(EntityRefBuilder _value) {
- _supertype = _value;
+ void set supertype(EntityRefBuilder value) {
+ this._supertype = value;
}
@override
@@ -3756,8 +3252,8 @@
/**
* Type parameters of the class, if any.
*/
- void set typeParameters(List<UnlinkedTypeParamBuilder> _value) {
- _typeParameters = _value;
+ void set typeParameters(List<UnlinkedTypeParamBuilder> value) {
+ this._typeParameters = value;
}
UnlinkedClassBuilder({List<UnlinkedConstBuilder> annotations, CodeRangeBuilder codeRange, UnlinkedDocumentationCommentBuilder documentationComment, List<UnlinkedExecutableBuilder> executables, List<UnlinkedVariableBuilder> fields, bool hasNoSupertype, List<EntityRefBuilder> interfaces, bool isAbstract, bool isMixinApplication, List<EntityRefBuilder> mixins, String name, int nameOffset, EntityRefBuilder supertype, List<UnlinkedTypeParamBuilder> typeParameters})
@@ -4109,9 +3605,9 @@
* If this is a `show` combinator, offset of the end of the list of shown
* names. Otherwise zero.
*/
- void set end(int _value) {
- assert(_value == null || _value >= 0);
- _end = _value;
+ void set end(int value) {
+ assert(value == null || value >= 0);
+ this._end = value;
}
@override
@@ -4120,8 +3616,8 @@
/**
* List of names which are hidden. Empty if this is a `show` combinator.
*/
- void set hides(List<String> _value) {
- _hides = _value;
+ void set hides(List<String> value) {
+ this._hides = value;
}
@override
@@ -4131,9 +3627,9 @@
* If this is a `show` combinator, offset of the `show` keyword. Otherwise
* zero.
*/
- void set offset(int _value) {
- assert(_value == null || _value >= 0);
- _offset = _value;
+ void set offset(int value) {
+ assert(value == null || value >= 0);
+ this._offset = value;
}
@override
@@ -4142,8 +3638,8 @@
/**
* List of names which are shown. Empty if this is a `hide` combinator.
*/
- void set shows(List<String> _value) {
- _shows = _value;
+ void set shows(List<String> value) {
+ this._shows = value;
}
UnlinkedCombinatorBuilder({int end, List<String> hides, int offset, List<String> shows})
@@ -4274,6 +3770,147 @@
String toString() => convert.JSON.encode(toJson());
}
+class UnlinkedConfigurationBuilder extends Object with _UnlinkedConfigurationMixin implements idl.UnlinkedConfiguration {
+ String _name;
+ String _uri;
+ String _value;
+
+ @override
+ String get name => _name ??= '';
+
+ /**
+ * The name of the declared variable whose value is being used in the
+ * condition.
+ */
+ void set name(String value) {
+ this._name = value;
+ }
+
+ @override
+ String get uri => _uri ??= '';
+
+ /**
+ * The URI of the implementation library to be used if the condition is true.
+ */
+ void set uri(String value) {
+ this._uri = value;
+ }
+
+ @override
+ String get value => _value ??= '';
+
+ /**
+ * The value to which the value of the declared variable will be compared,
+ * or `true` if the condition does not include an equality test.
+ */
+ void set value(String value) {
+ this._value = value;
+ }
+
+ UnlinkedConfigurationBuilder({String name, String uri, String value})
+ : _name = name,
+ _uri = uri,
+ _value = value;
+
+ /**
+ * Flush [informative] data recursively.
+ */
+ void flushInformative() {
+ }
+
+ /**
+ * Accumulate non-[informative] data into [signature].
+ */
+ void collectApiSignature(api_sig.ApiSignature signature) {
+ signature.addString(this._name ?? '');
+ signature.addString(this._value ?? '');
+ signature.addString(this._uri ?? '');
+ }
+
+ fb.Offset finish(fb.Builder fbBuilder) {
+ fb.Offset offset_name;
+ fb.Offset offset_uri;
+ fb.Offset offset_value;
+ if (_name != null) {
+ offset_name = fbBuilder.writeString(_name);
+ }
+ if (_uri != null) {
+ offset_uri = fbBuilder.writeString(_uri);
+ }
+ if (_value != null) {
+ offset_value = fbBuilder.writeString(_value);
+ }
+ fbBuilder.startTable();
+ if (offset_name != null) {
+ fbBuilder.addOffset(0, offset_name);
+ }
+ if (offset_uri != null) {
+ fbBuilder.addOffset(2, offset_uri);
+ }
+ if (offset_value != null) {
+ fbBuilder.addOffset(1, offset_value);
+ }
+ return fbBuilder.endTable();
+ }
+}
+
+class _UnlinkedConfigurationReader extends fb.TableReader<_UnlinkedConfigurationImpl> {
+ const _UnlinkedConfigurationReader();
+
+ @override
+ _UnlinkedConfigurationImpl createObject(fb.BufferContext bc, int offset) => new _UnlinkedConfigurationImpl(bc, offset);
+}
+
+class _UnlinkedConfigurationImpl extends Object with _UnlinkedConfigurationMixin implements idl.UnlinkedConfiguration {
+ final fb.BufferContext _bc;
+ final int _bcOffset;
+
+ _UnlinkedConfigurationImpl(this._bc, this._bcOffset);
+
+ String _name;
+ String _uri;
+ String _value;
+
+ @override
+ String get name {
+ _name ??= const fb.StringReader().vTableGet(_bc, _bcOffset, 0, '');
+ return _name;
+ }
+
+ @override
+ String get uri {
+ _uri ??= const fb.StringReader().vTableGet(_bc, _bcOffset, 2, '');
+ return _uri;
+ }
+
+ @override
+ String get value {
+ _value ??= const fb.StringReader().vTableGet(_bc, _bcOffset, 1, '');
+ return _value;
+ }
+}
+
+abstract class _UnlinkedConfigurationMixin implements idl.UnlinkedConfiguration {
+ @override
+ Map<String, Object> toJson() {
+ Map<String, Object> _result = <String, Object>{};
+ if (name != '') _result["name"] = name;
+ if (uri != '') _result["uri"] = uri;
+ if (value != '') _result["value"] = value;
+ return _result;
+ }
+
+ @override
+ Map<String, Object> toMap() => {
+ "name": name,
+ "uri": uri,
+ "value": value,
+ };
+
+ @override
+ String toString() => convert.JSON.encode(toJson());
+}
+
class UnlinkedConstBuilder extends Object with _UnlinkedConstMixin implements idl.UnlinkedConst {
List<idl.UnlinkedExprAssignOperator> _assignmentOperators;
List<double> _doubles;
@@ -4289,8 +3926,8 @@
/**
* Sequence of operators used by assignment operations.
*/
- void set assignmentOperators(List<idl.UnlinkedExprAssignOperator> _value) {
- _assignmentOperators = _value;
+ void set assignmentOperators(List<idl.UnlinkedExprAssignOperator> value) {
+ this._assignmentOperators = value;
}
@override
@@ -4299,8 +3936,8 @@
/**
* Sequence of 64-bit doubles consumed by the operation `pushDouble`.
*/
- void set doubles(List<double> _value) {
- _doubles = _value;
+ void set doubles(List<double> value) {
+ this._doubles = value;
}
@override
@@ -4311,9 +3948,9 @@
* `pushArgument`, `pushInt`, `shiftOr`, `concatenate`, `invokeConstructor`,
* `makeList`, and `makeMap`.
*/
- void set ints(List<int> _value) {
- assert(_value == null || _value.every((e) => e >= 0));
- _ints = _value;
+ void set ints(List<int> value) {
+ assert(value == null || value.every((e) => e >= 0));
+ this._ints = value;
}
@override
@@ -4323,8 +3960,8 @@
* Indicates whether the expression is a valid potentially constant
* expression.
*/
- void set isValidConst(bool _value) {
- _isValidConst = _value;
+ void set isValidConst(bool value) {
+ this._isValidConst = value;
}
@override
@@ -4334,8 +3971,8 @@
* Sequence of operations to execute (starting with an empty stack) to form
* the constant value.
*/
- void set operations(List<idl.UnlinkedConstOperation> _value) {
- _operations = _value;
+ void set operations(List<idl.UnlinkedConstOperation> value) {
+ this._operations = value;
}
@override
@@ -4347,8 +3984,8 @@
* that in the case of `pushReference` (and sometimes `invokeConstructor` the
* actual entity being referred to may be something other than a type.
*/
- void set references(List<EntityRefBuilder> _value) {
- _references = _value;
+ void set references(List<EntityRefBuilder> value) {
+ this._references = value;
}
@override
@@ -4358,8 +3995,8 @@
* Sequence of strings consumed by the operations `pushString` and
* `invokeConstructor`.
*/
- void set strings(List<String> _value) {
- _strings = _value;
+ void set strings(List<String> value) {
+ this._strings = value;
}
UnlinkedConstBuilder({List<idl.UnlinkedExprAssignOperator> assignmentOperators, List<double> doubles, List<int> ints, bool isValidConst, List<idl.UnlinkedConstOperation> operations, List<EntityRefBuilder> references, List<String> strings})
@@ -4592,8 +4229,8 @@
* from [arguments] with index `i` such that `n + i - m >= 0`, should be used
* with the name at `n + i - m`.
*/
- void set argumentNames(List<String> _value) {
- _argumentNames = _value;
+ void set argumentNames(List<String> value) {
+ this._argumentNames = value;
}
@override
@@ -4603,8 +4240,8 @@
* If [kind] is `thisInvocation` or `superInvocation`, the arguments of the
* invocation. Otherwise empty.
*/
- void set arguments(List<UnlinkedConstBuilder> _value) {
- _arguments = _value;
+ void set arguments(List<UnlinkedConstBuilder> value) {
+ this._arguments = value;
}
@override
@@ -4614,8 +4251,8 @@
* If [kind] is `field`, the expression of the field initializer.
* Otherwise `null`.
*/
- void set expression(UnlinkedConstBuilder _value) {
- _expression = _value;
+ void set expression(UnlinkedConstBuilder value) {
+ this._expression = value;
}
@override
@@ -4624,8 +4261,8 @@
/**
* The kind of the constructor initializer (field, redirect, super).
*/
- void set kind(idl.UnlinkedConstructorInitializerKind _value) {
- _kind = _value;
+ void set kind(idl.UnlinkedConstructorInitializerKind value) {
+ this._kind = value;
}
@override
@@ -4637,8 +4274,8 @@
* class, to redirect to. If [kind] is `superInvocation`, the name of the
* constructor, declared in the superclass, to invoke.
*/
- void set name(String _value) {
- _name = _value;
+ void set name(String value) {
+ this._name = value;
}
UnlinkedConstructorInitializerBuilder({List<String> argumentNames, List<UnlinkedConstBuilder> arguments, UnlinkedConstBuilder expression, idl.UnlinkedConstructorInitializerKind kind, String name})
@@ -4812,8 +4449,8 @@
* References appearing within the doc comment in square brackets are not
* specially encoded.
*/
- void set text(String _value) {
- _text = _value;
+ void set text(String value) {
+ this._text = value;
}
UnlinkedDocumentationCommentBuilder({String text})
@@ -4904,8 +4541,8 @@
/**
* Annotations for this enum.
*/
- void set annotations(List<UnlinkedConstBuilder> _value) {
- _annotations = _value;
+ void set annotations(List<UnlinkedConstBuilder> value) {
+ this._annotations = value;
}
@override
@@ -4914,8 +4551,8 @@
/**
* Code range of the enum.
*/
- void set codeRange(CodeRangeBuilder _value) {
- _codeRange = _value;
+ void set codeRange(CodeRangeBuilder value) {
+ this._codeRange = value;
}
@override
@@ -4925,8 +4562,8 @@
* Documentation comment for the enum, or `null` if there is no documentation
* comment.
*/
- void set documentationComment(UnlinkedDocumentationCommentBuilder _value) {
- _documentationComment = _value;
+ void set documentationComment(UnlinkedDocumentationCommentBuilder value) {
+ this._documentationComment = value;
}
@override
@@ -4935,8 +4572,8 @@
/**
* Name of the enum type.
*/
- void set name(String _value) {
- _name = _value;
+ void set name(String value) {
+ this._name = value;
}
@override
@@ -4945,9 +4582,9 @@
/**
* Offset of the enum name relative to the beginning of the file.
*/
- void set nameOffset(int _value) {
- assert(_value == null || _value >= 0);
- _nameOffset = _value;
+ void set nameOffset(int value) {
+ assert(value == null || value >= 0);
+ this._nameOffset = value;
}
@override
@@ -4956,8 +4593,8 @@
/**
* Values listed in the enum declaration, in declaration order.
*/
- void set values(List<UnlinkedEnumValueBuilder> _value) {
- _values = _value;
+ void set values(List<UnlinkedEnumValueBuilder> value) {
+ this._values = value;
}
UnlinkedEnumBuilder({List<UnlinkedConstBuilder> annotations, CodeRangeBuilder codeRange, UnlinkedDocumentationCommentBuilder documentationComment, String name, int nameOffset, List<UnlinkedEnumValueBuilder> values})
@@ -5142,8 +4779,8 @@
* Documentation comment for the enum value, or `null` if there is no
* documentation comment.
*/
- void set documentationComment(UnlinkedDocumentationCommentBuilder _value) {
- _documentationComment = _value;
+ void set documentationComment(UnlinkedDocumentationCommentBuilder value) {
+ this._documentationComment = value;
}
@override
@@ -5152,8 +4789,8 @@
/**
* Name of the enumerated value.
*/
- void set name(String _value) {
- _name = _value;
+ void set name(String value) {
+ this._name = value;
}
@override
@@ -5162,9 +4799,9 @@
/**
* Offset of the enum value name relative to the beginning of the file.
*/
- void set nameOffset(int _value) {
- assert(_value == null || _value >= 0);
- _nameOffset = _value;
+ void set nameOffset(int value) {
+ assert(value == null || value >= 0);
+ this._nameOffset = value;
}
UnlinkedEnumValueBuilder({UnlinkedDocumentationCommentBuilder documentationComment, String name, int nameOffset})
@@ -5305,8 +4942,8 @@
/**
* Annotations for this executable.
*/
- void set annotations(List<UnlinkedConstBuilder> _value) {
- _annotations = _value;
+ void set annotations(List<UnlinkedConstBuilder> value) {
+ this._annotations = value;
}
@override
@@ -5317,8 +4954,8 @@
* to the right of the `=>`. May be omitted if neither type inference nor
* constant evaluation depends on the function body.
*/
- void set bodyExpr(UnlinkedConstBuilder _value) {
- _bodyExpr = _value;
+ void set bodyExpr(UnlinkedConstBuilder value) {
+ this._bodyExpr = value;
}
@override
@@ -5327,8 +4964,8 @@
/**
* Code range of the executable.
*/
- void set codeRange(CodeRangeBuilder _value) {
- _codeRange = _value;
+ void set codeRange(CodeRangeBuilder value) {
+ this._codeRange = value;
}
@override
@@ -5338,8 +4975,8 @@
* If a constant [UnlinkedExecutableKind.constructor], the constructor
* initializers. Otherwise empty.
*/
- void set constantInitializers(List<UnlinkedConstructorInitializerBuilder> _value) {
- _constantInitializers = _value;
+ void set constantInitializers(List<UnlinkedConstructorInitializerBuilder> value) {
+ this._constantInitializers = value;
}
@override
@@ -5353,9 +4990,9 @@
*
* Otherwise, zero.
*/
- void set constCycleSlot(int _value) {
- assert(_value == null || _value >= 0);
- _constCycleSlot = _value;
+ void set constCycleSlot(int value) {
+ assert(value == null || value >= 0);
+ this._constCycleSlot = value;
}
@override
@@ -5365,8 +5002,8 @@
* Documentation comment for the executable, or `null` if there is no
* documentation comment.
*/
- void set documentationComment(UnlinkedDocumentationCommentBuilder _value) {
- _documentationComment = _value;
+ void set documentationComment(UnlinkedDocumentationCommentBuilder value) {
+ this._documentationComment = value;
}
@override
@@ -5379,9 +5016,9 @@
* no return type was inferred for this variable, so its static type is
* `dynamic`.
*/
- void set inferredReturnTypeSlot(int _value) {
- assert(_value == null || _value >= 0);
- _inferredReturnTypeSlot = _value;
+ void set inferredReturnTypeSlot(int value) {
+ assert(value == null || value >= 0);
+ this._inferredReturnTypeSlot = value;
}
@override
@@ -5390,8 +5027,8 @@
/**
* Indicates whether the executable is declared using the `abstract` keyword.
*/
- void set isAbstract(bool _value) {
- _isAbstract = _value;
+ void set isAbstract(bool value) {
+ this._isAbstract = value;
}
@override
@@ -5400,8 +5037,8 @@
/**
* Indicates whether the executable has body marked as being asynchronous.
*/
- void set isAsynchronous(bool _value) {
- _isAsynchronous = _value;
+ void set isAsynchronous(bool value) {
+ this._isAsynchronous = value;
}
@override
@@ -5410,8 +5047,8 @@
/**
* Indicates whether the executable is declared using the `const` keyword.
*/
- void set isConst(bool _value) {
- _isConst = _value;
+ void set isConst(bool value) {
+ this._isConst = value;
}
@override
@@ -5420,8 +5057,8 @@
/**
* Indicates whether the executable is declared using the `external` keyword.
*/
- void set isExternal(bool _value) {
- _isExternal = _value;
+ void set isExternal(bool value) {
+ this._isExternal = value;
}
@override
@@ -5430,8 +5067,8 @@
/**
* Indicates whether the executable is declared using the `factory` keyword.
*/
- void set isFactory(bool _value) {
- _isFactory = _value;
+ void set isFactory(bool value) {
+ this._isFactory = value;
}
@override
@@ -5440,8 +5077,8 @@
/**
* Indicates whether the executable has body marked as being a generator.
*/
- void set isGenerator(bool _value) {
- _isGenerator = _value;
+ void set isGenerator(bool value) {
+ this._isGenerator = value;
}
@override
@@ -5450,8 +5087,8 @@
/**
* Indicates whether the executable is a redirected constructor.
*/
- void set isRedirectedConstructor(bool _value) {
- _isRedirectedConstructor = _value;
+ void set isRedirectedConstructor(bool value) {
+ this._isRedirectedConstructor = value;
}
@override
@@ -5464,8 +5101,8 @@
* not declared using the `static` keyword (even though they are considered
* static for semantic purposes).
*/
- void set isStatic(bool _value) {
- _isStatic = _value;
+ void set isStatic(bool value) {
+ this._isStatic = value;
}
@override
@@ -5475,8 +5112,8 @@
* The kind of the executable (function/method, getter, setter, or
* constructor).
*/
- void set kind(idl.UnlinkedExecutableKind _value) {
- _kind = _value;
+ void set kind(idl.UnlinkedExecutableKind value) {
+ this._kind = value;
}
@override
@@ -5485,8 +5122,8 @@
/**
* The list of local functions.
*/
- void set localFunctions(List<UnlinkedExecutableBuilder> _value) {
- _localFunctions = _value;
+ void set localFunctions(List<UnlinkedExecutableBuilder> value) {
+ this._localFunctions = value;
}
@override
@@ -5495,8 +5132,8 @@
/**
* The list of local labels.
*/
- void set localLabels(List<UnlinkedLabelBuilder> _value) {
- _localLabels = _value;
+ void set localLabels(List<UnlinkedLabelBuilder> value) {
+ this._localLabels = value;
}
@override
@@ -5505,8 +5142,8 @@
/**
* The list of local variables.
*/
- void set localVariables(List<UnlinkedVariableBuilder> _value) {
- _localVariables = _value;
+ void set localVariables(List<UnlinkedVariableBuilder> value) {
+ this._localVariables = value;
}
@override
@@ -5517,8 +5154,8 @@
* named constructors, this excludes the class name and excludes the ".".
* For unnamed constructors, this is the empty string.
*/
- void set name(String _value) {
- _name = _value;
+ void set name(String value) {
+ this._name = value;
}
@override
@@ -5528,9 +5165,9 @@
* If [kind] is [UnlinkedExecutableKind.constructor] and [name] is not empty,
* the offset of the end of the constructor name. Otherwise zero.
*/
- void set nameEnd(int _value) {
- assert(_value == null || _value >= 0);
- _nameEnd = _value;
+ void set nameEnd(int value) {
+ assert(value == null || value >= 0);
+ this._nameEnd = value;
}
@override
@@ -5542,9 +5179,9 @@
* For unnamed constructors, this is the offset of the class name (i.e. the
* offset of the second "C" in "class C { C(); }").
*/
- void set nameOffset(int _value) {
- assert(_value == null || _value >= 0);
- _nameOffset = _value;
+ void set nameOffset(int value) {
+ assert(value == null || value >= 0);
+ this._nameOffset = value;
}
@override
@@ -5555,8 +5192,8 @@
* parameters (hence this will be the empty list), and setters have a single
* parameter.
*/
- void set parameters(List<UnlinkedParamBuilder> _value) {
- _parameters = _value;
+ void set parameters(List<UnlinkedParamBuilder> value) {
+ this._parameters = value;
}
@override
@@ -5566,9 +5203,9 @@
* If [kind] is [UnlinkedExecutableKind.constructor] and [name] is not empty,
* the offset of the period before the constructor name. Otherwise zero.
*/
- void set periodOffset(int _value) {
- assert(_value == null || _value >= 0);
- _periodOffset = _value;
+ void set periodOffset(int value) {
+ assert(value == null || value >= 0);
+ this._periodOffset = value;
}
@override
@@ -5578,8 +5215,8 @@
* If [isRedirectedConstructor] and [isFactory] are both `true`, the
* constructor to which this constructor redirects; otherwise empty.
*/
- void set redirectedConstructor(EntityRefBuilder _value) {
- _redirectedConstructor = _value;
+ void set redirectedConstructor(EntityRefBuilder value) {
+ this._redirectedConstructor = value;
}
@override
@@ -5590,8 +5227,8 @@
* name of the constructor that this constructor redirects to; otherwise
* empty.
*/
- void set redirectedConstructorName(String _value) {
- _redirectedConstructorName = _value;
+ void set redirectedConstructorName(String value) {
+ this._redirectedConstructorName = value;
}
@override
@@ -5604,8 +5241,8 @@
* executables may have return types that are not accessible via direct
* imports.
*/
- void set returnType(EntityRefBuilder _value) {
- _returnType = _value;
+ void set returnType(EntityRefBuilder value) {
+ this._returnType = value;
}
@override
@@ -5615,8 +5252,8 @@
* Type parameters of the executable, if any. Empty if support for generic
* method syntax is disabled.
*/
- void set typeParameters(List<UnlinkedTypeParamBuilder> _value) {
- _typeParameters = _value;
+ void set typeParameters(List<UnlinkedTypeParamBuilder> value) {
+ this._typeParameters = value;
}
@override
@@ -5625,9 +5262,9 @@
/**
* If a local function, the length of the visible range; zero otherwise.
*/
- void set visibleLength(int _value) {
- assert(_value == null || _value >= 0);
- _visibleLength = _value;
+ void set visibleLength(int value) {
+ assert(value == null || value >= 0);
+ this._visibleLength = value;
}
@override
@@ -5636,9 +5273,9 @@
/**
* If a local function, the beginning of the visible range; zero otherwise.
*/
- void set visibleOffset(int _value) {
- assert(_value == null || _value >= 0);
- _visibleOffset = _value;
+ void set visibleOffset(int value) {
+ assert(value == null || value >= 0);
+ this._visibleOffset = value;
}
UnlinkedExecutableBuilder({List<UnlinkedConstBuilder> annotations, UnlinkedConstBuilder bodyExpr, CodeRangeBuilder codeRange, List<UnlinkedConstructorInitializerBuilder> constantInitializers, int constCycleSlot, UnlinkedDocumentationCommentBuilder documentationComment, int inferredReturnTypeSlot, bool isAbstract, bool isAsynchronous, bool isConst, bool isExternal, bool isFactory, bool isGenerator, bool isRedirectedConstructor, bool isStatic, idl.UnlinkedExecutableKind kind, List<UnlinkedExecutableBuilder> localFunctions, List<UnlinkedLabelBuilder> localLabels, List<UnlinkedVariableBuilder> localVariables, String name, int nameEnd, int nameOffset, List<UnlinkedParamBuilder> parameters, int periodOffset, EntityRefBuilder redirectedConstructor, String redirectedConstructorName, EntityRefBuilder returnType, List<UnlinkedTypeParamBuilder> typeParameters, int visibleLength, int visibleOffset})
@@ -6225,8 +5862,8 @@
/**
* Annotations for this export directive.
*/
- void set annotations(List<UnlinkedConstBuilder> _value) {
- _annotations = _value;
+ void set annotations(List<UnlinkedConstBuilder> value) {
+ this._annotations = value;
}
@override
@@ -6235,9 +5872,9 @@
/**
* Offset of the "export" keyword.
*/
- void set offset(int _value) {
- assert(_value == null || _value >= 0);
- _offset = _value;
+ void set offset(int value) {
+ assert(value == null || value >= 0);
+ this._offset = value;
}
@override
@@ -6247,9 +5884,9 @@
* End of the URI string (including quotes) relative to the beginning of the
* file.
*/
- void set uriEnd(int _value) {
- assert(_value == null || _value >= 0);
- _uriEnd = _value;
+ void set uriEnd(int value) {
+ assert(value == null || value >= 0);
+ this._uriEnd = value;
}
@override
@@ -6259,9 +5896,9 @@
* Offset of the URI string (including quotes) relative to the beginning of
* the file.
*/
- void set uriOffset(int _value) {
- assert(_value == null || _value >= 0);
- _uriOffset = _value;
+ void set uriOffset(int value) {
+ assert(value == null || value >= 0);
+ this._uriOffset = value;
}
UnlinkedExportNonPublicBuilder({List<UnlinkedConstBuilder> annotations, int offset, int uriEnd, int uriOffset})
@@ -6384,16 +6021,28 @@
class UnlinkedExportPublicBuilder extends Object with _UnlinkedExportPublicMixin implements idl.UnlinkedExportPublic {
List<UnlinkedCombinatorBuilder> _combinators;
+ List<UnlinkedConfigurationBuilder> _configurations;
String _uri;
@override
List<UnlinkedCombinatorBuilder> get combinators => _combinators ??= <UnlinkedCombinatorBuilder>[];
/**
- * Combinators contained in this import declaration.
+ * Combinators contained in this export declaration.
*/
- void set combinators(List<UnlinkedCombinatorBuilder> _value) {
- _combinators = _value;
+ void set combinators(List<UnlinkedCombinatorBuilder> value) {
+ this._combinators = value;
+ }
+
+ @override
+ List<UnlinkedConfigurationBuilder> get configurations => _configurations ??= <UnlinkedConfigurationBuilder>[];
+
+ /**
+ * Configurations used to control which library will actually be loaded at
+ * run-time.
+ */
+ void set configurations(List<UnlinkedConfigurationBuilder> value) {
+ this._configurations = value;
}
@override
@@ -6402,12 +6051,13 @@
/**
* URI used in the source code to reference the exported library.
*/
- void set uri(String _value) {
- _uri = _value;
+ void set uri(String value) {
+ this._uri = value;
}
- UnlinkedExportPublicBuilder({List<UnlinkedCombinatorBuilder> combinators, String uri})
+ UnlinkedExportPublicBuilder({List<UnlinkedCombinatorBuilder> combinators, List<UnlinkedConfigurationBuilder> configurations, String uri})
: _combinators = combinators,
+ _configurations = configurations,
_uri = uri;
/**
@@ -6415,6 +6065,7 @@
*/
void flushInformative() {
_combinators?.forEach((b) => b.flushInformative());
+ _configurations?.forEach((b) => b.flushInformative());
}
/**
@@ -6430,14 +6081,26 @@
x?.collectApiSignature(signature);
}
}
+ if (this._configurations == null) {
+ signature.addInt(0);
+ } else {
+ signature.addInt(this._configurations.length);
+ for (var x in this._configurations) {
+ x?.collectApiSignature(signature);
+ }
+ }
}
fb.Offset finish(fb.Builder fbBuilder) {
fb.Offset offset_combinators;
+ fb.Offset offset_configurations;
fb.Offset offset_uri;
if (!(_combinators == null || _combinators.isEmpty)) {
offset_combinators = fbBuilder.writeList(_combinators.map((b) => b.finish(fbBuilder)).toList());
}
+ if (!(_configurations == null || _configurations.isEmpty)) {
+ offset_configurations = fbBuilder.writeList(_configurations.map((b) => b.finish(fbBuilder)).toList());
+ }
if (_uri != null) {
offset_uri = fbBuilder.writeString(_uri);
}
@@ -6445,6 +6108,9 @@
if (offset_combinators != null) {
fbBuilder.addOffset(1, offset_combinators);
}
+ if (offset_configurations != null) {
+ fbBuilder.addOffset(2, offset_configurations);
+ }
if (offset_uri != null) {
fbBuilder.addOffset(0, offset_uri);
}
@@ -6466,6 +6132,7 @@
_UnlinkedExportPublicImpl(this._bc, this._bcOffset);
List<idl.UnlinkedCombinator> _combinators;
+ List<idl.UnlinkedConfiguration> _configurations;
String _uri;
@override
@@ -6475,6 +6142,12 @@
}
@override
+ List<idl.UnlinkedConfiguration> get configurations {
+ _configurations ??= const fb.ListReader<idl.UnlinkedConfiguration>(const _UnlinkedConfigurationReader()).vTableGet(_bc, _bcOffset, 2, const <idl.UnlinkedConfiguration>[]);
+ return _configurations;
+ }
+
+ @override
String get uri {
_uri ??= const fb.StringReader().vTableGet(_bc, _bcOffset, 0, '');
return _uri;
@@ -6486,6 +6159,7 @@
Map<String, Object> toJson() {
Map<String, Object> _result = <String, Object>{};
if (combinators.isNotEmpty) _result["combinators"] = combinators.map((_value) => _value.toJson()).toList();
+ if (configurations.isNotEmpty) _result["configurations"] = configurations.map((_value) => _value.toJson()).toList();
if (uri != '') _result["uri"] = uri;
return _result;
}
@@ -6493,6 +6167,7 @@
@override
Map<String, Object> toMap() => {
"combinators": combinators,
+ "configurations": configurations,
"uri": uri,
};
@@ -6503,6 +6178,7 @@
class UnlinkedImportBuilder extends Object with _UnlinkedImportMixin implements idl.UnlinkedImport {
List<UnlinkedConstBuilder> _annotations;
List<UnlinkedCombinatorBuilder> _combinators;
+ List<UnlinkedConfigurationBuilder> _configurations;
bool _isDeferred;
bool _isImplicit;
int _offset;
@@ -6518,8 +6194,8 @@
/**
* Annotations for this import declaration.
*/
- void set annotations(List<UnlinkedConstBuilder> _value) {
- _annotations = _value;
+ void set annotations(List<UnlinkedConstBuilder> value) {
+ this._annotations = value;
}
@override
@@ -6528,8 +6204,19 @@
/**
* Combinators contained in this import declaration.
*/
- void set combinators(List<UnlinkedCombinatorBuilder> _value) {
- _combinators = _value;
+ void set combinators(List<UnlinkedCombinatorBuilder> value) {
+ this._combinators = value;
+ }
+
+ @override
+ List<UnlinkedConfigurationBuilder> get configurations => _configurations ??= <UnlinkedConfigurationBuilder>[];
+
+ /**
+ * Configurations used to control which library will actually be loaded at
+ * run-time.
+ */
+ void set configurations(List<UnlinkedConfigurationBuilder> value) {
+ this._configurations = value;
}
@override
@@ -6538,8 +6225,8 @@
/**
* Indicates whether the import declaration uses the `deferred` keyword.
*/
- void set isDeferred(bool _value) {
- _isDeferred = _value;
+ void set isDeferred(bool value) {
+ this._isDeferred = value;
}
@override
@@ -6548,8 +6235,8 @@
/**
* Indicates whether the import declaration is implicit.
*/
- void set isImplicit(bool _value) {
- _isImplicit = _value;
+ void set isImplicit(bool value) {
+ this._isImplicit = value;
}
@override
@@ -6559,9 +6246,9 @@
* If [isImplicit] is false, offset of the "import" keyword. If [isImplicit]
* is true, zero.
*/
- void set offset(int _value) {
- assert(_value == null || _value >= 0);
- _offset = _value;
+ void set offset(int value) {
+ assert(value == null || value >= 0);
+ this._offset = value;
}
@override
@@ -6571,9 +6258,9 @@
* Offset of the prefix name relative to the beginning of the file, or zero
* if there is no prefix.
*/
- void set prefixOffset(int _value) {
- assert(_value == null || _value >= 0);
- _prefixOffset = _value;
+ void set prefixOffset(int value) {
+ assert(value == null || value >= 0);
+ this._prefixOffset = value;
}
@override
@@ -6585,9 +6272,9 @@
*
* Note that multiple imports can declare the same prefix.
*/
- void set prefixReference(int _value) {
- assert(_value == null || _value >= 0);
- _prefixReference = _value;
+ void set prefixReference(int value) {
+ assert(value == null || value >= 0);
+ this._prefixReference = value;
}
@override
@@ -6596,8 +6283,8 @@
/**
* URI used in the source code to reference the imported library.
*/
- void set uri(String _value) {
- _uri = _value;
+ void set uri(String value) {
+ this._uri = value;
}
@override
@@ -6607,9 +6294,9 @@
* End of the URI string (including quotes) relative to the beginning of the
* file. If [isImplicit] is true, zero.
*/
- void set uriEnd(int _value) {
- assert(_value == null || _value >= 0);
- _uriEnd = _value;
+ void set uriEnd(int value) {
+ assert(value == null || value >= 0);
+ this._uriEnd = value;
}
@override
@@ -6619,14 +6306,15 @@
* Offset of the URI string (including quotes) relative to the beginning of
* the file. If [isImplicit] is true, zero.
*/
- void set uriOffset(int _value) {
- assert(_value == null || _value >= 0);
- _uriOffset = _value;
+ void set uriOffset(int value) {
+ assert(value == null || value >= 0);
+ this._uriOffset = value;
}
- UnlinkedImportBuilder({List<UnlinkedConstBuilder> annotations, List<UnlinkedCombinatorBuilder> combinators, bool isDeferred, bool isImplicit, int offset, int prefixOffset, int prefixReference, String uri, int uriEnd, int uriOffset})
+ UnlinkedImportBuilder({List<UnlinkedConstBuilder> annotations, List<UnlinkedCombinatorBuilder> combinators, List<UnlinkedConfigurationBuilder> configurations, bool isDeferred, bool isImplicit, int offset, int prefixOffset, int prefixReference, String uri, int uriEnd, int uriOffset})
: _annotations = annotations,
_combinators = combinators,
+ _configurations = configurations,
_isDeferred = isDeferred,
_isImplicit = isImplicit,
_offset = offset,
@@ -6642,6 +6330,7 @@
void flushInformative() {
_annotations?.forEach((b) => b.flushInformative());
_combinators?.forEach((b) => b.flushInformative());
+ _configurations?.forEach((b) => b.flushInformative());
_offset = null;
_prefixOffset = null;
_uriEnd = null;
@@ -6672,11 +6361,20 @@
}
}
signature.addBool(this._isDeferred == true);
+ if (this._configurations == null) {
+ signature.addInt(0);
+ } else {
+ signature.addInt(this._configurations.length);
+ for (var x in this._configurations) {
+ x?.collectApiSignature(signature);
+ }
+ }
}
fb.Offset finish(fb.Builder fbBuilder) {
fb.Offset offset_annotations;
fb.Offset offset_combinators;
+ fb.Offset offset_configurations;
fb.Offset offset_uri;
if (!(_annotations == null || _annotations.isEmpty)) {
offset_annotations = fbBuilder.writeList(_annotations.map((b) => b.finish(fbBuilder)).toList());
@@ -6684,6 +6382,9 @@
if (!(_combinators == null || _combinators.isEmpty)) {
offset_combinators = fbBuilder.writeList(_combinators.map((b) => b.finish(fbBuilder)).toList());
}
+ if (!(_configurations == null || _configurations.isEmpty)) {
+ offset_configurations = fbBuilder.writeList(_configurations.map((b) => b.finish(fbBuilder)).toList());
+ }
if (_uri != null) {
offset_uri = fbBuilder.writeString(_uri);
}
@@ -6694,6 +6395,9 @@
if (offset_combinators != null) {
fbBuilder.addOffset(4, offset_combinators);
}
+ if (offset_configurations != null) {
+ fbBuilder.addOffset(10, offset_configurations);
+ }
if (_isDeferred == true) {
fbBuilder.addBool(9, true);
}
@@ -6737,6 +6441,7 @@
List<idl.UnlinkedConst> _annotations;
List<idl.UnlinkedCombinator> _combinators;
+ List<idl.UnlinkedConfiguration> _configurations;
bool _isDeferred;
bool _isImplicit;
int _offset;
@@ -6759,6 +6464,12 @@
}
@override
+ List<idl.UnlinkedConfiguration> get configurations {
+ _configurations ??= const fb.ListReader<idl.UnlinkedConfiguration>(const _UnlinkedConfigurationReader()).vTableGet(_bc, _bcOffset, 10, const <idl.UnlinkedConfiguration>[]);
+ return _configurations;
+ }
+
+ @override
bool get isDeferred {
_isDeferred ??= const fb.BoolReader().vTableGet(_bc, _bcOffset, 9, false);
return _isDeferred;
@@ -6813,6 +6524,7 @@
Map<String, Object> _result = <String, Object>{};
if (annotations.isNotEmpty) _result["annotations"] = annotations.map((_value) => _value.toJson()).toList();
if (combinators.isNotEmpty) _result["combinators"] = combinators.map((_value) => _value.toJson()).toList();
+ if (configurations.isNotEmpty) _result["configurations"] = configurations.map((_value) => _value.toJson()).toList();
if (isDeferred != false) _result["isDeferred"] = isDeferred;
if (isImplicit != false) _result["isImplicit"] = isImplicit;
if (offset != 0) _result["offset"] = offset;
@@ -6828,6 +6540,7 @@
Map<String, Object> toMap() => {
"annotations": annotations,
"combinators": combinators,
+ "configurations": configurations,
"isDeferred": isDeferred,
"isImplicit": isImplicit,
"offset": offset,
@@ -6855,8 +6568,8 @@
* Return `true` if this label is associated with a `switch` member (`case` or
* `default`).
*/
- void set isOnSwitchMember(bool _value) {
- _isOnSwitchMember = _value;
+ void set isOnSwitchMember(bool value) {
+ this._isOnSwitchMember = value;
}
@override
@@ -6865,8 +6578,8 @@
/**
* Return `true` if this label is associated with a `switch` statement.
*/
- void set isOnSwitchStatement(bool _value) {
- _isOnSwitchStatement = _value;
+ void set isOnSwitchStatement(bool value) {
+ this._isOnSwitchStatement = value;
}
@override
@@ -6875,8 +6588,8 @@
/**
* Name of the label.
*/
- void set name(String _value) {
- _name = _value;
+ void set name(String value) {
+ this._name = value;
}
@override
@@ -6885,9 +6598,9 @@
/**
* Offset of the label relative to the beginning of the file.
*/
- void set nameOffset(int _value) {
- assert(_value == null || _value >= 0);
- _nameOffset = _value;
+ void set nameOffset(int value) {
+ assert(value == null || value >= 0);
+ this._nameOffset = value;
}
UnlinkedLabelBuilder({bool isOnSwitchMember, bool isOnSwitchStatement, String name, int nameOffset})
@@ -7022,8 +6735,8 @@
/**
* Annotations for this parameter.
*/
- void set annotations(List<UnlinkedConstBuilder> _value) {
- _annotations = _value;
+ void set annotations(List<UnlinkedConstBuilder> value) {
+ this._annotations = value;
}
@override
@@ -7032,8 +6745,8 @@
/**
* Code range of the parameter.
*/
- void set codeRange(CodeRangeBuilder _value) {
- _codeRange = _value;
+ void set codeRange(CodeRangeBuilder value) {
+ this._codeRange = value;
}
@override
@@ -7043,8 +6756,8 @@
* If the parameter has a default value, the source text of the constant
* expression in the default value. Otherwise the empty string.
*/
- void set defaultValueCode(String _value) {
- _defaultValueCode = _value;
+ void set defaultValueCode(String value) {
+ this._defaultValueCode = value;
}
@override
@@ -7061,9 +6774,9 @@
* not specified, they always inherit the static type of the corresponding
* field.
*/
- void set inferredTypeSlot(int _value) {
- assert(_value == null || _value >= 0);
- _inferredTypeSlot = _value;
+ void set inferredTypeSlot(int value) {
+ assert(value == null || value >= 0);
+ this._inferredTypeSlot = value;
}
@override
@@ -7073,8 +6786,8 @@
* The synthetic initializer function of the parameter. Absent if the variable
* does not have an initializer.
*/
- void set initializer(UnlinkedExecutableBuilder _value) {
- _initializer = _value;
+ void set initializer(UnlinkedExecutableBuilder value) {
+ this._initializer = value;
}
@override
@@ -7083,8 +6796,8 @@
/**
* Indicates whether this is a function-typed parameter.
*/
- void set isFunctionTyped(bool _value) {
- _isFunctionTyped = _value;
+ void set isFunctionTyped(bool value) {
+ this._isFunctionTyped = value;
}
@override
@@ -7094,8 +6807,8 @@
* Indicates whether this is an initializing formal parameter (i.e. it is
* declared using `this.` syntax).
*/
- void set isInitializingFormal(bool _value) {
- _isInitializingFormal = _value;
+ void set isInitializingFormal(bool value) {
+ this._isInitializingFormal = value;
}
@override
@@ -7104,8 +6817,8 @@
/**
* Kind of the parameter.
*/
- void set kind(idl.UnlinkedParamKind _value) {
- _kind = _value;
+ void set kind(idl.UnlinkedParamKind value) {
+ this._kind = value;
}
@override
@@ -7114,8 +6827,8 @@
/**
* Name of the parameter.
*/
- void set name(String _value) {
- _name = _value;
+ void set name(String value) {
+ this._name = value;
}
@override
@@ -7124,9 +6837,9 @@
/**
* Offset of the parameter name relative to the beginning of the file.
*/
- void set nameOffset(int _value) {
- assert(_value == null || _value >= 0);
- _nameOffset = _value;
+ void set nameOffset(int value) {
+ assert(value == null || value >= 0);
+ this._nameOffset = value;
}
@override
@@ -7135,8 +6848,8 @@
/**
* If [isFunctionTyped] is `true`, the parameters of the function type.
*/
- void set parameters(List<UnlinkedParamBuilder> _value) {
- _parameters = _value;
+ void set parameters(List<UnlinkedParamBuilder> value) {
+ this._parameters = value;
}
@override
@@ -7147,8 +6860,8 @@
* [isFunctionTyped] is `false`, the declared type. Absent if the type is
* implicit.
*/
- void set type(EntityRefBuilder _value) {
- _type = _value;
+ void set type(EntityRefBuilder value) {
+ this._type = value;
}
@override
@@ -7157,9 +6870,9 @@
/**
* The length of the visible range.
*/
- void set visibleLength(int _value) {
- assert(_value == null || _value >= 0);
- _visibleLength = _value;
+ void set visibleLength(int value) {
+ assert(value == null || value >= 0);
+ this._visibleLength = value;
}
@override
@@ -7168,9 +6881,9 @@
/**
* The beginning of the visible range.
*/
- void set visibleOffset(int _value) {
- assert(_value == null || _value >= 0);
- _visibleOffset = _value;
+ void set visibleOffset(int value) {
+ assert(value == null || value >= 0);
+ this._visibleOffset = value;
}
UnlinkedParamBuilder({List<UnlinkedConstBuilder> annotations, CodeRangeBuilder codeRange, String defaultValueCode, int inferredTypeSlot, UnlinkedExecutableBuilder initializer, bool isFunctionTyped, bool isInitializingFormal, idl.UnlinkedParamKind kind, String name, int nameOffset, List<UnlinkedParamBuilder> parameters, EntityRefBuilder type, int visibleLength, int visibleOffset})
@@ -7478,8 +7191,8 @@
/**
* Annotations for this part declaration.
*/
- void set annotations(List<UnlinkedConstBuilder> _value) {
- _annotations = _value;
+ void set annotations(List<UnlinkedConstBuilder> value) {
+ this._annotations = value;
}
@override
@@ -7489,9 +7202,9 @@
* End of the URI string (including quotes) relative to the beginning of the
* file.
*/
- void set uriEnd(int _value) {
- assert(_value == null || _value >= 0);
- _uriEnd = _value;
+ void set uriEnd(int value) {
+ assert(value == null || value >= 0);
+ this._uriEnd = value;
}
@override
@@ -7501,9 +7214,9 @@
* Offset of the URI string (including quotes) relative to the beginning of
* the file.
*/
- void set uriOffset(int _value) {
- assert(_value == null || _value >= 0);
- _uriOffset = _value;
+ void set uriOffset(int value) {
+ assert(value == null || value >= 0);
+ this._uriOffset = value;
}
UnlinkedPartBuilder({List<UnlinkedConstBuilder> annotations, int uriEnd, int uriOffset})
@@ -7622,8 +7335,8 @@
/**
* The kind of object referred to by the name.
*/
- void set kind(idl.ReferenceKind _value) {
- _kind = _value;
+ void set kind(idl.ReferenceKind value) {
+ this._kind = value;
}
@override
@@ -7637,8 +7350,8 @@
* Unnamed constructors are not included since they do not constitute a
* separate name added to any namespace.
*/
- void set members(List<UnlinkedPublicNameBuilder> _value) {
- _members = _value;
+ void set members(List<UnlinkedPublicNameBuilder> value) {
+ this._members = value;
}
@override
@@ -7647,8 +7360,8 @@
/**
* The name itself.
*/
- void set name(String _value) {
- _name = _value;
+ void set name(String value) {
+ this._name = value;
}
@override
@@ -7658,9 +7371,9 @@
* If the entity being referred to is generic, the number of type parameters
* it accepts. Otherwise zero.
*/
- void set numTypeParameters(int _value) {
- assert(_value == null || _value >= 0);
- _numTypeParameters = _value;
+ void set numTypeParameters(int value) {
+ assert(value == null || value >= 0);
+ this._numTypeParameters = value;
}
UnlinkedPublicNameBuilder({idl.ReferenceKind kind, List<UnlinkedPublicNameBuilder> members, String name, int numTypeParameters})
@@ -7796,8 +7509,8 @@
/**
* Export declarations in the compilation unit.
*/
- void set exports(List<UnlinkedExportPublicBuilder> _value) {
- _exports = _value;
+ void set exports(List<UnlinkedExportPublicBuilder> value) {
+ this._exports = value;
}
@override
@@ -7809,8 +7522,8 @@
* TODO(paulberry): consider sorting these names to reduce unnecessary
* relinking.
*/
- void set names(List<UnlinkedPublicNameBuilder> _value) {
- _names = _value;
+ void set names(List<UnlinkedPublicNameBuilder> value) {
+ this._names = value;
}
@override
@@ -7819,8 +7532,8 @@
/**
* URIs referenced by part declarations in the compilation unit.
*/
- void set parts(List<String> _value) {
- _parts = _value;
+ void set parts(List<String> value) {
+ this._parts = value;
}
UnlinkedPublicNamespaceBuilder({List<UnlinkedExportPublicBuilder> exports, List<UnlinkedPublicNameBuilder> names, List<String> parts})
@@ -7972,8 +7685,8 @@
* string is "dynamic". For the pseudo-type `void`, the string is "void".
* For the pseudo-type `bottom`, the string is "*bottom*".
*/
- void set name(String _value) {
- _name = _value;
+ void set name(String value) {
+ this._name = value;
}
@override
@@ -7987,9 +7700,9 @@
* UnlinkedUnit.references[i].prefixReference != 0, then
* UnlinkedUnit.references[i].prefixReference < i.
*/
- void set prefixReference(int _value) {
- assert(_value == null || _value >= 0);
- _prefixReference = _value;
+ void set prefixReference(int value) {
+ assert(value == null || value >= 0);
+ this._prefixReference = value;
}
UnlinkedReferenceBuilder({String name, int prefixReference})
@@ -8090,8 +7803,8 @@
/**
* Annotations for this typedef.
*/
- void set annotations(List<UnlinkedConstBuilder> _value) {
- _annotations = _value;
+ void set annotations(List<UnlinkedConstBuilder> value) {
+ this._annotations = value;
}
@override
@@ -8100,8 +7813,8 @@
/**
* Code range of the typedef.
*/
- void set codeRange(CodeRangeBuilder _value) {
- _codeRange = _value;
+ void set codeRange(CodeRangeBuilder value) {
+ this._codeRange = value;
}
@override
@@ -8111,8 +7824,8 @@
* Documentation comment for the typedef, or `null` if there is no
* documentation comment.
*/
- void set documentationComment(UnlinkedDocumentationCommentBuilder _value) {
- _documentationComment = _value;
+ void set documentationComment(UnlinkedDocumentationCommentBuilder value) {
+ this._documentationComment = value;
}
@override
@@ -8121,8 +7834,8 @@
/**
* Name of the typedef.
*/
- void set name(String _value) {
- _name = _value;
+ void set name(String value) {
+ this._name = value;
}
@override
@@ -8131,9 +7844,9 @@
/**
* Offset of the typedef name relative to the beginning of the file.
*/
- void set nameOffset(int _value) {
- assert(_value == null || _value >= 0);
- _nameOffset = _value;
+ void set nameOffset(int value) {
+ assert(value == null || value >= 0);
+ this._nameOffset = value;
}
@override
@@ -8142,8 +7855,8 @@
/**
* Parameters of the executable, if any.
*/
- void set parameters(List<UnlinkedParamBuilder> _value) {
- _parameters = _value;
+ void set parameters(List<UnlinkedParamBuilder> value) {
+ this._parameters = value;
}
@override
@@ -8152,8 +7865,8 @@
/**
* Return type of the typedef.
*/
- void set returnType(EntityRefBuilder _value) {
- _returnType = _value;
+ void set returnType(EntityRefBuilder value) {
+ this._returnType = value;
}
@override
@@ -8162,8 +7875,8 @@
/**
* Type parameters of the typedef, if any.
*/
- void set typeParameters(List<UnlinkedTypeParamBuilder> _value) {
- _typeParameters = _value;
+ void set typeParameters(List<UnlinkedTypeParamBuilder> value) {
+ this._typeParameters = value;
}
UnlinkedTypedefBuilder({List<UnlinkedConstBuilder> annotations, CodeRangeBuilder codeRange, UnlinkedDocumentationCommentBuilder documentationComment, String name, int nameOffset, List<UnlinkedParamBuilder> parameters, EntityRefBuilder returnType, List<UnlinkedTypeParamBuilder> typeParameters})
@@ -8395,8 +8108,8 @@
/**
* Annotations for this type parameter.
*/
- void set annotations(List<UnlinkedConstBuilder> _value) {
- _annotations = _value;
+ void set annotations(List<UnlinkedConstBuilder> value) {
+ this._annotations = value;
}
@override
@@ -8406,8 +8119,8 @@
* Bound of the type parameter, if a bound is explicitly declared. Otherwise
* null.
*/
- void set bound(EntityRefBuilder _value) {
- _bound = _value;
+ void set bound(EntityRefBuilder value) {
+ this._bound = value;
}
@override
@@ -8416,8 +8129,8 @@
/**
* Code range of the type parameter.
*/
- void set codeRange(CodeRangeBuilder _value) {
- _codeRange = _value;
+ void set codeRange(CodeRangeBuilder value) {
+ this._codeRange = value;
}
@override
@@ -8426,8 +8139,8 @@
/**
* Name of the type parameter.
*/
- void set name(String _value) {
- _name = _value;
+ void set name(String value) {
+ this._name = value;
}
@override
@@ -8436,9 +8149,9 @@
/**
* Offset of the type parameter name relative to the beginning of the file.
*/
- void set nameOffset(int _value) {
- assert(_value == null || _value >= 0);
- _nameOffset = _value;
+ void set nameOffset(int value) {
+ assert(value == null || value >= 0);
+ this._nameOffset = value;
}
UnlinkedTypeParamBuilder({List<UnlinkedConstBuilder> annotations, EntityRefBuilder bound, CodeRangeBuilder codeRange, String name, int nameOffset})
@@ -8613,8 +8326,8 @@
/**
* Classes declared in the compilation unit.
*/
- void set classes(List<UnlinkedClassBuilder> _value) {
- _classes = _value;
+ void set classes(List<UnlinkedClassBuilder> value) {
+ this._classes = value;
}
@override
@@ -8623,8 +8336,8 @@
/**
* Code range of the unit.
*/
- void set codeRange(CodeRangeBuilder _value) {
- _codeRange = _value;
+ void set codeRange(CodeRangeBuilder value) {
+ this._codeRange = value;
}
@override
@@ -8633,8 +8346,8 @@
/**
* Enums declared in the compilation unit.
*/
- void set enums(List<UnlinkedEnumBuilder> _value) {
- _enums = _value;
+ void set enums(List<UnlinkedEnumBuilder> value) {
+ this._enums = value;
}
@override
@@ -8644,8 +8357,8 @@
* Top level executable objects (functions, getters, and setters) declared in
* the compilation unit.
*/
- void set executables(List<UnlinkedExecutableBuilder> _value) {
- _executables = _value;
+ void set executables(List<UnlinkedExecutableBuilder> value) {
+ this._executables = value;
}
@override
@@ -8654,8 +8367,8 @@
/**
* Export declarations in the compilation unit.
*/
- void set exports(List<UnlinkedExportNonPublicBuilder> _value) {
- _exports = _value;
+ void set exports(List<UnlinkedExportNonPublicBuilder> value) {
+ this._exports = value;
}
@override
@@ -8668,8 +8381,8 @@
* When this field is non-empty, all other fields in the data structure have
* their default values.
*/
- void set fallbackModePath(String _value) {
- _fallbackModePath = _value;
+ void set fallbackModePath(String value) {
+ this._fallbackModePath = value;
}
@override
@@ -8678,8 +8391,8 @@
/**
* Import declarations in the compilation unit.
*/
- void set imports(List<UnlinkedImportBuilder> _value) {
- _imports = _value;
+ void set imports(List<UnlinkedImportBuilder> value) {
+ this._imports = value;
}
@override
@@ -8689,8 +8402,8 @@
* Annotations for the library declaration, or the empty list if there is no
* library declaration.
*/
- void set libraryAnnotations(List<UnlinkedConstBuilder> _value) {
- _libraryAnnotations = _value;
+ void set libraryAnnotations(List<UnlinkedConstBuilder> value) {
+ this._libraryAnnotations = value;
}
@override
@@ -8700,8 +8413,8 @@
* Documentation comment for the library, or `null` if there is no
* documentation comment.
*/
- void set libraryDocumentationComment(UnlinkedDocumentationCommentBuilder _value) {
- _libraryDocumentationComment = _value;
+ void set libraryDocumentationComment(UnlinkedDocumentationCommentBuilder value) {
+ this._libraryDocumentationComment = value;
}
@override
@@ -8710,8 +8423,8 @@
/**
* Name of the library (from a "library" declaration, if present).
*/
- void set libraryName(String _value) {
- _libraryName = _value;
+ void set libraryName(String value) {
+ this._libraryName = value;
}
@override
@@ -8721,9 +8434,9 @@
* Length of the library name as it appears in the source code (or 0 if the
* library has no name).
*/
- void set libraryNameLength(int _value) {
- assert(_value == null || _value >= 0);
- _libraryNameLength = _value;
+ void set libraryNameLength(int value) {
+ assert(value == null || value >= 0);
+ this._libraryNameLength = value;
}
@override
@@ -8733,9 +8446,9 @@
* Offset of the library name relative to the beginning of the file (or 0 if
* the library has no name).
*/
- void set libraryNameOffset(int _value) {
- assert(_value == null || _value >= 0);
- _libraryNameOffset = _value;
+ void set libraryNameOffset(int value) {
+ assert(value == null || value >= 0);
+ this._libraryNameOffset = value;
}
@override
@@ -8744,9 +8457,9 @@
/**
* Offsets of the first character of each line in the source code.
*/
- void set lineStarts(List<int> _value) {
- assert(_value == null || _value.every((e) => e >= 0));
- _lineStarts = _value;
+ void set lineStarts(List<int> value) {
+ assert(value == null || value.every((e) => e >= 0));
+ this._lineStarts = value;
}
@override
@@ -8755,8 +8468,8 @@
/**
* Part declarations in the compilation unit.
*/
- void set parts(List<UnlinkedPartBuilder> _value) {
- _parts = _value;
+ void set parts(List<UnlinkedPartBuilder> value) {
+ this._parts = value;
}
@override
@@ -8765,8 +8478,8 @@
/**
* Unlinked public namespace of this compilation unit.
*/
- void set publicNamespace(UnlinkedPublicNamespaceBuilder _value) {
- _publicNamespace = _value;
+ void set publicNamespace(UnlinkedPublicNamespaceBuilder value) {
+ this._publicNamespace = value;
}
@override
@@ -8779,8 +8492,8 @@
* example [UnlinkedReference.prefixReference or
* UnlinkedImport.prefixReference]).
*/
- void set references(List<UnlinkedReferenceBuilder> _value) {
- _references = _value;
+ void set references(List<UnlinkedReferenceBuilder> value) {
+ this._references = value;
}
@override
@@ -8789,8 +8502,8 @@
/**
* Typedefs declared in the compilation unit.
*/
- void set typedefs(List<UnlinkedTypedefBuilder> _value) {
- _typedefs = _value;
+ void set typedefs(List<UnlinkedTypedefBuilder> value) {
+ this._typedefs = value;
}
@override
@@ -8799,8 +8512,8 @@
/**
* Top level variables declared in the compilation unit.
*/
- void set variables(List<UnlinkedVariableBuilder> _value) {
- _variables = _value;
+ void set variables(List<UnlinkedVariableBuilder> value) {
+ this._variables = value;
}
UnlinkedUnitBuilder({List<UnlinkedClassBuilder> classes, CodeRangeBuilder codeRange, List<UnlinkedEnumBuilder> enums, List<UnlinkedExecutableBuilder> executables, List<UnlinkedExportNonPublicBuilder> exports, String fallbackModePath, List<UnlinkedImportBuilder> imports, List<UnlinkedConstBuilder> libraryAnnotations, UnlinkedDocumentationCommentBuilder libraryDocumentationComment, String libraryName, int libraryNameLength, int libraryNameOffset, List<int> lineStarts, List<UnlinkedPartBuilder> parts, UnlinkedPublicNamespaceBuilder publicNamespace, List<UnlinkedReferenceBuilder> references, List<UnlinkedTypedefBuilder> typedefs, List<UnlinkedVariableBuilder> variables})
@@ -9283,8 +8996,8 @@
/**
* Annotations for this variable.
*/
- void set annotations(List<UnlinkedConstBuilder> _value) {
- _annotations = _value;
+ void set annotations(List<UnlinkedConstBuilder> value) {
+ this._annotations = value;
}
@override
@@ -9293,8 +9006,8 @@
/**
* Code range of the variable.
*/
- void set codeRange(CodeRangeBuilder _value) {
- _codeRange = _value;
+ void set codeRange(CodeRangeBuilder value) {
+ this._codeRange = value;
}
@override
@@ -9304,8 +9017,8 @@
* Documentation comment for the variable, or `null` if there is no
* documentation comment.
*/
- void set documentationComment(UnlinkedDocumentationCommentBuilder _value) {
- _documentationComment = _value;
+ void set documentationComment(UnlinkedDocumentationCommentBuilder value) {
+ this._documentationComment = value;
}
@override
@@ -9317,9 +9030,9 @@
* there is no matching entry in [LinkedLibrary.types], then no type was
* inferred for this variable, so its static type is `dynamic`.
*/
- void set inferredTypeSlot(int _value) {
- assert(_value == null || _value >= 0);
- _inferredTypeSlot = _value;
+ void set inferredTypeSlot(int value) {
+ assert(value == null || value >= 0);
+ this._inferredTypeSlot = value;
}
@override
@@ -9329,8 +9042,8 @@
* The synthetic initializer function of the variable. Absent if the variable
* does not have an initializer.
*/
- void set initializer(UnlinkedExecutableBuilder _value) {
- _initializer = _value;
+ void set initializer(UnlinkedExecutableBuilder value) {
+ this._initializer = value;
}
@override
@@ -9339,8 +9052,8 @@
/**
* Indicates whether the variable is declared using the `const` keyword.
*/
- void set isConst(bool _value) {
- _isConst = _value;
+ void set isConst(bool value) {
+ this._isConst = value;
}
@override
@@ -9349,8 +9062,8 @@
/**
* Indicates whether the variable is declared using the `final` keyword.
*/
- void set isFinal(bool _value) {
- _isFinal = _value;
+ void set isFinal(bool value) {
+ this._isFinal = value;
}
@override
@@ -9363,8 +9076,8 @@
* declared using the `static` keyword (even though they are considered
* static for semantic purposes).
*/
- void set isStatic(bool _value) {
- _isStatic = _value;
+ void set isStatic(bool value) {
+ this._isStatic = value;
}
@override
@@ -9373,8 +9086,8 @@
/**
* Name of the variable.
*/
- void set name(String _value) {
- _name = _value;
+ void set name(String value) {
+ this._name = value;
}
@override
@@ -9383,9 +9096,9 @@
/**
* Offset of the variable name relative to the beginning of the file.
*/
- void set nameOffset(int _value) {
- assert(_value == null || _value >= 0);
- _nameOffset = _value;
+ void set nameOffset(int value) {
+ assert(value == null || value >= 0);
+ this._nameOffset = value;
}
@override
@@ -9399,9 +9112,9 @@
*
* Non-propagable variables have a [propagatedTypeSlot] of zero.
*/
- void set propagatedTypeSlot(int _value) {
- assert(_value == null || _value >= 0);
- _propagatedTypeSlot = _value;
+ void set propagatedTypeSlot(int value) {
+ assert(value == null || value >= 0);
+ this._propagatedTypeSlot = value;
}
@override
@@ -9410,8 +9123,8 @@
/**
* Declared type of the variable. Absent if the type is implicit.
*/
- void set type(EntityRefBuilder _value) {
- _type = _value;
+ void set type(EntityRefBuilder value) {
+ this._type = value;
}
@override
@@ -9420,9 +9133,9 @@
/**
* If a local variable, the length of the visible range; zero otherwise.
*/
- void set visibleLength(int _value) {
- assert(_value == null || _value >= 0);
- _visibleLength = _value;
+ void set visibleLength(int value) {
+ assert(value == null || value >= 0);
+ this._visibleLength = value;
}
@override
@@ -9431,9 +9144,9 @@
/**
* If a local variable, the beginning of the visible range; zero otherwise.
*/
- void set visibleOffset(int _value) {
- assert(_value == null || _value >= 0);
- _visibleOffset = _value;
+ void set visibleOffset(int value) {
+ assert(value == null || value >= 0);
+ this._visibleOffset = value;
}
UnlinkedVariableBuilder({List<UnlinkedConstBuilder> annotations, CodeRangeBuilder codeRange, UnlinkedDocumentationCommentBuilder documentationComment, int inferredTypeSlot, UnlinkedExecutableBuilder initializer, bool isConst, bool isFinal, bool isStatic, String name, int nameOffset, int propagatedTypeSlot, EntityRefBuilder type, int visibleLength, int visibleOffset})
diff --git a/pkg/analyzer/lib/src/summary/format.fbs b/pkg/analyzer/lib/src/summary/format.fbs
index de2afb2..c7afabc 100644
--- a/pkg/analyzer/lib/src/summary/format.fbs
+++ b/pkg/analyzer/lib/src/summary/format.fbs
@@ -7,15 +7,6 @@
/**
- * Kind of a source in the cache.
- */
-enum CacheSourceKind : byte {
- library,
-
- part
-}
-
-/**
* Enum used to indicate the kind of a name in index.
*/
enum IndexNameKind : byte {
@@ -791,78 +782,6 @@
}
/**
- * Information about an analysis error in a source.
- */
-table CacheAnalysisError {
- /**
- * The correction to be displayed for this error, or `null` if there is no
- * correction information for this error. The correction should indicate how
- * the user can fix the error.
- */
- correction:string (id: 4);
-
- /**
- * The unique name of the error code.
- */
- errorCodeUniqueName:string (id: 0);
-
- /**
- * Length of the error range.
- */
- length:uint (id: 2);
-
- /**
- * The message to be displayed for this error. The message should indicate
- * what is wrong and why it is wrong.
- */
- message:string (id: 3);
-
- /**
- * Offset of the error range relative to the beginning of the file.
- */
- offset:uint (id: 1);
-}
-
-/**
- * Information about a source that depends only on its content.
- */
-table CacheSourceContent {
- /**
- * The list of exported URIs, e.g. `dart:core`, or `foo/bar.dart`,
- * or `package:foo/bar.dart`. Empty if [kind] is [CacheSourceKind.part].
- */
- exportedUris:[string] (id: 2);
-
- /**
- * The list of explicitly imported URIs, e.g. `dart:core`, or `foo/bar.dart`,
- * or `package:foo/bar.dart`. Empty if [kind] is [CacheSourceKind.part].
- */
- importedUris:[string] (id: 1);
-
- /**
- * The kind of the source.
- */
- kind:CacheSourceKind (id: 0);
-
- /**
- * The list of part URIs, e.g. `foo/bar.dart`. Empty if [kind] is
- * [CacheSourceKind.part].
- */
- partUris:[string] (id: 3);
-}
-
-/**
- * Errors of a source in a library, which depends on the import/export closure
- * of the containing library and the source.
- */
-table CacheSourceErrorsInLibrary {
- /**
- * The list of errors in the source in the library.
- */
- errors:[CacheAnalysisError] (id: 0);
-}
-
-/**
* Information about an element code range.
*/
table CodeRange {
@@ -1533,6 +1452,28 @@
}
/**
+ * Unlinked summary information about a single import or export configuration.
+ */
+table UnlinkedConfiguration {
+ /**
+ * The name of the declared variable whose value is being used in the
+ * condition.
+ */
+ name:string (id: 0);
+
+ /**
+ * The URI of the implementation library to be used if the condition is true.
+ */
+ uri:string (id: 2);
+
+ /**
+ * The value to which the value of the declared variable will be compared,
+ * or `true` if the condition does not include an equality test.
+ */
+ value:string (id: 1);
+}
+
+/**
* Unlinked summary information about a compile-time constant expression, or a
* potentially constant expression.
*
@@ -1931,11 +1872,17 @@
*/
table UnlinkedExportPublic {
/**
- * Combinators contained in this import declaration.
+ * Combinators contained in this export declaration.
*/
combinators:[UnlinkedCombinator] (id: 1);
/**
+ * Configurations used to control which library will actually be loaded at
+ * run-time.
+ */
+ configurations:[UnlinkedConfiguration] (id: 2);
+
+ /**
* URI used in the source code to reference the exported library.
*/
uri:string (id: 0);
@@ -1956,6 +1903,12 @@
combinators:[UnlinkedCombinator] (id: 4);
/**
+ * Configurations used to control which library will actually be loaded at
+ * run-time.
+ */
+ configurations:[UnlinkedConfiguration] (id: 10);
+
+ /**
* Indicates whether the import declaration uses the `deferred` keyword.
*/
isDeferred:bool (id: 9);
diff --git a/pkg/analyzer/lib/src/summary/idl.dart b/pkg/analyzer/lib/src/summary/idl.dart
index 3cd6562..4eff005 100644
--- a/pkg/analyzer/lib/src/summary/idl.dart
+++ b/pkg/analyzer/lib/src/summary/idl.dart
@@ -58,100 +58,6 @@
const informative = null;
/**
- * Information about an analysis error in a source.
- */
-abstract class CacheAnalysisError extends base.SummaryClass {
- /**
- * The correction to be displayed for this error, or `null` if there is no
- * correction information for this error. The correction should indicate how
- * the user can fix the error.
- */
- @Id(4)
- String get correction;
-
- /**
- * The unique name of the error code.
- */
- @Id(0)
- String get errorCodeUniqueName;
-
- /**
- * Length of the error range.
- */
- @Id(2)
- int get length;
-
- /**
- * The message to be displayed for this error. The message should indicate
- * what is wrong and why it is wrong.
- */
- @Id(3)
- String get message;
-
- /**
- * Offset of the error range relative to the beginning of the file.
- */
- @Id(1)
- int get offset;
-}
-
-/**
- * Information about a source that depends only on its content.
- */
-@TopLevel('CaSS')
-abstract class CacheSourceContent extends base.SummaryClass {
- factory CacheSourceContent.fromBuffer(List<int> buffer) =>
- generated.readCacheSourceContent(buffer);
-
- /**
- * The list of exported URIs, e.g. `dart:core`, or `foo/bar.dart`,
- * or `package:foo/bar.dart`. Empty if [kind] is [CacheSourceKind.part].
- */
- @Id(2)
- List<String> get exportedUris;
-
- /**
- * The list of explicitly imported URIs, e.g. `dart:core`, or `foo/bar.dart`,
- * or `package:foo/bar.dart`. Empty if [kind] is [CacheSourceKind.part].
- */
- @Id(1)
- List<String> get importedUris;
-
- /**
- * The kind of the source.
- */
- @Id(0)
- CacheSourceKind get kind;
-
- /**
- * The list of part URIs, e.g. `foo/bar.dart`. Empty if [kind] is
- * [CacheSourceKind.part].
- */
- @Id(3)
- List<String> get partUris;
-}
-
-/**
- * Errors of a source in a library, which depends on the import/export closure
- * of the containing library and the source.
- */
-@TopLevel('CSEL')
-abstract class CacheSourceErrorsInLibrary extends base.SummaryClass {
- factory CacheSourceErrorsInLibrary.fromBuffer(List<int> buffer) =>
- generated.readCacheSourceErrorsInLibrary(buffer);
- /**
- * The list of errors in the source in the library.
- */
- @Id(0)
- List<CacheAnalysisError> get errors;
-}
-
-/**
- * Kind of a source in the cache.
- */
-enum CacheSourceKind { library, part }
-
-/**
* Information about an element code range.
*/
abstract class CodeRange extends base.SummaryClass {
@@ -1130,6 +1036,31 @@
}
/**
+ * Unlinked summary information about a single import or export configuration.
+ */
+abstract class UnlinkedConfiguration extends base.SummaryClass {
+ /**
+ * The name of the declared variable whose value is being used in the
+ * condition.
+ */
+ @Id(0)
+ String get name;
+
+ /**
+ * The URI of the implementation library to be used if the condition is true.
+ */
+ @Id(2)
+ String get uri;
+
+ /**
+ * The value to which the value of the declared variable will be compared,
+ * or `true` if the condition does not include an equality test.
+ */
+ @Id(1)
+ String get value;
+}
+
+/**
* Unlinked summary information about a compile-time constant expression, or a
* potentially constant expression.
*
@@ -2063,12 +1994,19 @@
*/
abstract class UnlinkedExportPublic extends base.SummaryClass {
/**
- * Combinators contained in this import declaration.
+ * Combinators contained in this export declaration.
*/
@Id(1)
List<UnlinkedCombinator> get combinators;
/**
+ * Configurations used to control which library will actually be loaded at
+ * run-time.
+ */
+ @Id(2)
+ List<UnlinkedConfiguration> get configurations;
+
+ /**
* URI used in the source code to reference the exported library.
*/
@Id(0)
@@ -2186,6 +2124,13 @@
List<UnlinkedCombinator> get combinators;
/**
+ * Configurations used to control which library will actually be loaded at
+ * run-time.
+ */
+ @Id(10)
+ List<UnlinkedConfiguration> get configurations;
+
+ /**
* Indicates whether the import declaration uses the `deferred` keyword.
*/
@Id(9)
diff --git a/pkg/analyzer/lib/src/summary/incremental_cache.dart b/pkg/analyzer/lib/src/summary/incremental_cache.dart
deleted file mode 100644
index 6b1b1ae..0000000
--- a/pkg/analyzer/lib/src/summary/incremental_cache.dart
+++ /dev/null
@@ -1,656 +0,0 @@
-// Copyright (c) 2016, 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:collection';
-import 'dart:convert';
-import 'dart:core';
-
-import 'package:analyzer/dart/element/element.dart';
-import 'package:analyzer/file_system/file_system.dart';
-import 'package:analyzer/src/generated/engine.dart';
-import 'package:analyzer/src/generated/error.dart';
-import 'package:analyzer/src/generated/source.dart';
-import 'package:analyzer/src/summary/format.dart';
-import 'package:analyzer/src/summary/idl.dart';
-import 'package:analyzer/src/summary/summarize_elements.dart';
-import 'package:convert/convert.dart';
-import 'package:crypto/crypto.dart';
-
-/**
- * The version of the incremental cache. It should be incremented every time
- * when any cache data structure is changed.
- */
-const int _VERSION = 1;
-
-/**
- * Compare the given file paths [a] and [b]. Because paths usually have long
- * equal prefix, comparison is done not as comparision of two generic [String]s.
- * Instead it starts from the ends of each strings.
- *
- * Return `-1` if [a] is ordered before [b], `1` if `this` is ordered after [b],
- * and zero if [a] and [b] are ordered together.
- */
-int comparePaths(String a, String b) {
- int thisLength = a.length;
- int otherLength = b.length;
- int len = (thisLength < otherLength) ? thisLength : otherLength;
- for (int i = 0; i < len; i++) {
- int thisCodeUnit = a.codeUnitAt(thisLength - 1 - i);
- int otherCodeUnit = b.codeUnitAt(otherLength - 1 - i);
- if (thisCodeUnit < otherCodeUnit) {
- return -1;
- }
- if (thisCodeUnit > otherCodeUnit) {
- return 1;
- }
- }
- if (thisLength < otherLength) {
- return -1;
- }
- if (thisLength > otherLength) {
- return 1;
- }
- return 0;
-}
-
-/**
- * Storage for cache data.
- */
-abstract class CacheStorage {
- /**
- * Compact the storage, e.g. remove unused entries.
- */
- void compact();
-
- /**
- * Return bytes for the given [key], `null` if [key] is not in the storage.
- */
- List<int> get(String key);
-
- /**
- * Associate the [key] with the given [bytes].
- *
- * If the [key] was already in the storage, its associated value is changed.
- * Otherwise the key-value pair is added to the storage.
- *
- * It is not guaranteed that data will always be accessible using [get], in
- * some implementations association may silently fail or become inaccessible
- * after some time.
- */
- void put(String key, List<int> bytes);
-}
-
-/**
- * A [Folder] based implementation of [CacheStorage].
- */
-class FolderCacheStorage implements CacheStorage {
- /**
- * The maximum number of entries to keep in the cache.
- */
- static const MAX_ENTRIES = 20000;
-
- /**
- * The folder to read and write files.
- */
- final Folder folder;
-
- /**
- * To ensure that operations of writing files are atomic we create a temporary
- * file with this name in the [folder] and then rename it once we are
- * done writing.
- */
- final String tempFileName;
-
- /**
- * The set of recently used entries, with the most recently used entries
- * on the bottom.
- */
- final LinkedHashSet<String> _recentEntries = new LinkedHashSet<String>();
-
- FolderCacheStorage(this.folder, this.tempFileName) {
- try {
- File file = folder.getChildAssumingFile('.entries');
- if (file.exists) {
- String entriesString = file.readAsStringSync();
- List<String> entriesLists = entriesString.split('\n');
- _recentEntries.addAll(entriesLists);
- }
- } catch (_) {}
- }
-
- @override
- void compact() {
- while (_recentEntries.length > MAX_ENTRIES) {
- String key = _recentEntries.first;
- _recentEntries.remove(key);
- try {
- folder.getChildAssumingFile(key).delete();
- } catch (_) {}
- }
- try {
- List<int> bytes = UTF8.encode(_recentEntries.join('\n'));
- folder.getChildAssumingFile('.entries').writeAsBytesSync(bytes);
- } catch (_) {}
- }
-
- @override
- List<int> get(String key) {
- Resource file = folder.getChild(key);
- if (file is File) {
- try {
- List<int> bytes = file.readAsBytesSync();
- _accessedKey(key);
- return bytes;
- } on FileSystemException {}
- }
- return null;
- }
-
- @override
- void put(String key, List<int> bytes) {
- String absPath = folder.getChild(key).path;
- File tempFile = folder.getChild(tempFileName);
- tempFile.writeAsBytesSync(bytes);
- try {
- tempFile.renameSync(absPath);
- _accessedKey(key);
- } catch (e) {}
- }
-
- /**
- * The given [key] was accessed, update recently used entries.
- */
- void _accessedKey(String key) {
- _recentEntries.remove(key);
- _recentEntries.add(key);
- }
-}
-
-/**
- * Cache of information to support incremental analysis.
- *
- * Note that currently this class is not intended for interactive use.
- */
-class IncrementalCache {
- /**
- * The storage for the cache data.
- */
- final CacheStorage storage;
-
- /**
- * The context in which this cache is used.
- */
- final AnalysisContext context;
-
- /**
- * Opaque data that reflects the current configuration, such as the [context]
- * options, and is mixed into the hashes.
- */
- final List<int> configSalt;
-
- final Map<Source, CacheSourceContent> _sourceContentMap =
- <Source, CacheSourceContent>{};
- final Map<Source, List<Source>> _libraryClosureMap = <Source, List<Source>>{};
- final Map<Source, List<int>> _libraryClosureHashMap = <Source, List<int>>{};
- final Map<Source, List<int>> _sourceContentHashMap = <Source, List<int>>{};
-
- /**
- * Mapping from a library closure key to its [PackageBundle].
- */
- final Map<String, PackageBundle> _bundleMap = <String, PackageBundle>{};
-
- final Map<String, Source> _absoluteUriMap = <String, Source>{};
-
- IncrementalCache(this.storage, this.context, this.configSalt);
-
- /**
- * Clear internal caches so that we read from file system again.
- */
- void clearInternalCaches() {
- _sourceContentMap.clear();
- _libraryClosureMap.clear();
- _sourceContentHashMap.clear();
- _bundleMap.clear();
- }
-
- /**
- * Return all summaries that are required to provide results about the library
- * with the given [librarySource] from its summary. It includes all of the
- * bundles in the import/export closure of the library. If any of the
- * bundles are not in the cache, then `null` is returned. If any of the
- * [LibraryBundleWithId]s were already returned as a part of the closure of
- * another library, they are still included - it is up to the client to
- * decide whether a bundle should be used or not, but it is easy to do
- * using [LibraryBundleWithId.id].
- */
- List<LibraryBundleWithId> getLibraryClosureBundles(Source librarySource) {
- try {
- List<Source> closureSources = _getLibraryClosure(librarySource);
- List<LibraryBundleWithId> closureBundles = <LibraryBundleWithId>[];
- for (Source source in closureSources) {
- if (getSourceKind(source) == SourceKind.PART) {
- continue;
- }
- String key = _getLibraryBundleKey(source);
- PackageBundle bundle = _getLibraryBundle(key);
- if (bundle == null) {
- return null;
- }
- closureBundles.add(new LibraryBundleWithId(source, key, bundle));
- }
- return closureBundles;
- } catch (e) {
- return null;
- }
- }
-
- /**
- * Return the parts of the given [librarySource], or `null` if unknown.
- */
- List<Source> getLibraryParts(Source librarySource) {
- try {
- CacheSourceContent contentSource = _getCacheSourceContent(librarySource);
- if (contentSource != null) {
- return contentSource.partUris.map((String partUri) {
- Source partSource = _resolveUri(librarySource, partUri);
- if (partSource == null) {
- throw new StateError(
- 'Unable to resolve $partUri in $librarySource');
- }
- return partSource;
- }).toList();
- }
- } catch (e) {}
- return null;
- }
-
- /**
- * Return cached errors in the given [source] in the context of the given
- * [librarySource], or `null` if the cache does not have this information.
- */
- List<AnalysisError> getSourceErrorsInLibrary(
- Source librarySource, Source source) {
- try {
- String key = _getSourceErrorsKey(librarySource, source);
- List<int> bytes = storage.get(key);
- if (bytes == null) {
- return null;
- }
- CacheSourceErrorsInLibrary errorsObject =
- new CacheSourceErrorsInLibrary.fromBuffer(bytes);
- return errorsObject.errors
- .map((e) => _convertErrorFromCached(source, e))
- .toList();
- } catch (e) {
- return null;
- }
- }
-
- /**
- * Return the kind of the given [source], or `null` if unknown.
- */
- SourceKind getSourceKind(Source source) {
- try {
- CacheSourceContent contentSource = _getCacheSourceContent(source);
- if (contentSource != null) {
- if (contentSource.kind == CacheSourceKind.library) {
- return SourceKind.LIBRARY;
- }
- if (contentSource.kind == CacheSourceKind.part) {
- return SourceKind.PART;
- }
- }
- } catch (e) {}
- return null;
- }
-
- /**
- * Write information about the [libraryElement] into the cache.
- */
- void putLibrary(LibraryElement libraryElement) {
- _writeCacheSourceContents(libraryElement);
- String key = _getLibraryBundleKey(libraryElement.source);
- PackageBundleAssembler assembler = new PackageBundleAssembler();
- assembler.serializeLibraryElement(libraryElement);
- List<int> bytes = assembler.assemble().toBuffer();
- storage.put(key, bytes);
- }
-
- /**
- * Associate the given [errors] with the [source] in the [librarySource].
- */
- void putSourceErrorsInLibrary(
- Source librarySource, Source source, List<AnalysisError> errors) {
- CacheSourceErrorsInLibraryBuilder builder =
- new CacheSourceErrorsInLibraryBuilder(
- errors: errors.map(_convertErrorToCached).toList());
- String key = _getSourceErrorsKey(librarySource, source);
- List<int> bytes = builder.toBuffer();
- storage.put(key, bytes);
- }
-
- /**
- * Fill the whole source closure of the library with the given
- * [librarySource]. It includes defining units and parts of the library and
- * all its directly or indirectly imported or exported libraries.
- */
- void _appendLibraryClosure(Set<Source> closure, Source librarySource) {
- if (librarySource.isInSystemLibrary) {
- return;
- }
- if (closure.add(librarySource)) {
- CacheSourceContent contentSource = _getCacheSourceContent(librarySource);
- if (contentSource == null) {
- throw new StateError('No structure for $librarySource');
- }
- // Append parts.
- for (String partUri in contentSource.partUris) {
- Source partSource = _resolveUri(librarySource, partUri);
- if (partSource == null) {
- throw new StateError('Unable to resolve $partUri in $librarySource');
- }
- closure.add(partSource);
- }
- // Append imports and exports.
- void appendLibrarySources(String refUri) {
- Source refSource = _resolveUri(librarySource, refUri);
- if (refSource == null) {
- throw new StateError('Unable to resolve $refUri in $librarySource');
- }
- // If we have already the closure for the 'refSource', use it.
- // Otherwise, continue computing recursively.
- // It's not the most efficient algorithm, but in practice we might
- // visit each library multiple times only for the first top-level
- // bundle requested in `getLibraryClosureBundles`.
- List<Source> refClosure = _libraryClosureMap[refSource];
- if (refClosure != null) {
- closure.addAll(refClosure);
- } else {
- _appendLibraryClosure(closure, refSource);
- }
- }
-
- contentSource.importedUris.forEach(appendLibrarySources);
- contentSource.exportedUris.forEach(appendLibrarySources);
- }
- }
-
- List<int> _computeSaltedMD5OfBytes(addData(ByteConversionSink byteSink)) {
- Digest digest;
- ChunkedConversionSink<Digest> digestSink =
- new ChunkedConversionSink<Digest>.withCallback((List<Digest> digests) {
- digest = digests.single;
- });
- ByteConversionSink byteSink = md5.startChunkedConversion(digestSink);
- // Add data.
- addData(byteSink);
- byteSink.add(const <int>[_VERSION]);
- byteSink.add(configSalt);
- // Done.
- byteSink.close();
- return digest.bytes;
- }
-
- /**
- * Return the [AnalysisError] for the given [cachedError].
- */
- AnalysisError _convertErrorFromCached(
- Source source, CacheAnalysisError cachedError) {
- ErrorCode errorCode = _getErrorCode(cachedError);
- return new AnalysisError.forValues(
- source,
- cachedError.offset,
- cachedError.length,
- errorCode,
- cachedError.message,
- cachedError.correction);
- }
-
- /**
- * Return the [CacheAnalysisError] for the given [error].
- */
- CacheAnalysisError _convertErrorToCached(AnalysisError error) {
- return new CacheAnalysisErrorBuilder(
- errorCodeUniqueName: error.errorCode.uniqueName,
- offset: error.offset,
- length: error.length,
- message: error.message,
- correction: error.correction);
- }
-
- /**
- * Get the content based information about the given [source], maybe `null`
- * if the information is not in the cache.
- */
- CacheSourceContent _getCacheSourceContent(Source source) {
- CacheSourceContent content = _sourceContentMap[source];
- if (content == null) {
- String key = _getCacheSourceContentKey(source);
- List<int> bytes = storage.get(key);
- if (bytes == null) {
- return null;
- }
- content = new CacheSourceContent.fromBuffer(bytes);
- _sourceContentMap[source] = content;
- }
- return content;
- }
-
- /**
- * Return the key of the content based [source] information.
- */
- String _getCacheSourceContentKey(Source source) {
- List<int> hash = _getSourceContentHash(source);
- String hashStr = hex.encode(hash);
- return '$hashStr.content';
- }
-
- /**
- * Return the [ErrorCode] of the given [error], throws if not found.
- */
- ErrorCode _getErrorCode(CacheAnalysisError error) {
- String uniqueName = error.errorCodeUniqueName;
- ErrorCode errorCode = ErrorCode.byUniqueName(uniqueName);
- if (errorCode != null) {
- return errorCode;
- }
- throw new StateError('Unable to find ErrorCode: $uniqueName');
- }
-
- /**
- * Get the bundle for the given key.
- */
- PackageBundle _getLibraryBundle(String key) {
- PackageBundle bundle = _bundleMap[key];
- if (bundle == null) {
- List<int> bytes = storage.get(key);
- if (bytes == null) {
- return null;
- }
- bundle = new PackageBundle.fromBuffer(bytes);
- if (bundle.majorVersion != PackageBundleAssembler.currentMajorVersion ||
- bundle.minorVersion != PackageBundleAssembler.currentMinorVersion) {
- return null;
- }
- _bundleMap[key] = bundle;
- }
- return bundle;
- }
-
- /**
- * Return the key of the bundle of the [librarySource].
- */
- String _getLibraryBundleKey(Source librarySource) {
- List<int> hash = _getLibraryClosureHash(librarySource);
- String hashStr = hex.encode(hash);
- return '$hashStr.summary';
- }
-
- /**
- * Return the whole source closure of the library with the given
- * [librarySource]. It includes defining units and parts of the library and
- * of all its directly or indirectly imported or exported libraries.
- */
- List<Source> _getLibraryClosure(Source librarySource) {
- return _libraryClosureMap.putIfAbsent(librarySource, () {
- Set<Source> closureSet = new Set<Source>();
- _appendLibraryClosure(closureSet, librarySource);
- List<Source> closureList = closureSet.toList();
- closureList.sort((a, b) => comparePaths(a.fullName, b.fullName));
- return closureList;
- });
- }
-
- /**
- * Return the [context]-specific hash of the closure of the library with
- * the given [librarySource].
- */
- List<int> _getLibraryClosureHash(Source librarySource) {
- return _libraryClosureHashMap.putIfAbsent(librarySource, () {
- List<Source> closure = _getLibraryClosure(librarySource);
- return _computeSaltedMD5OfBytes((ByteConversionSink byteSink) {
- for (Source source in closure) {
- List<int> sourceHash = _getSourceContentHash(source);
- byteSink.add(sourceHash);
- }
- // When we sort closure sources for two libraries (A, B) we get exactly
- // the same list of sources for both A and B. So, their hash is exactly
- // the same. But we use it to store separate summary bundles for
- // separate libraries. Ideally would be nice to group these libraries
- // into a single summary bundle. But this would require delaying
- // saving bundles until we know all of them.
- // So, for now we make hashes for separate libraries unique be mixing
- // in the library source again.
- byteSink.add(_getSourceContentHash(librarySource));
- });
- });
- }
-
- /**
- * Compute a hash of the given [source] contents.
- */
- List<int> _getSourceContentHash(Source source) {
- return _sourceContentHashMap.putIfAbsent(source, () {
- String sourceText = source.contents.data;
- List<int> sourceBytes = UTF8.encode(sourceText);
- return md5.convert(sourceBytes).bytes;
- });
- }
-
- /**
- * Return the key for errors in the [source] in the [librarySource].
- */
- String _getSourceErrorsKey(Source librarySource, Source source) {
- List<int> hash = _computeSaltedMD5OfBytes((ByteConversionSink byteSink) {
- byteSink.add(_getLibraryClosureHash(librarySource));
- byteSink.add(_getSourceContentHash(source));
- });
- String hashStr = hex.encode(hash);
- return '$hashStr.errorsInLibrary';
- }
-
- /**
- * Return a source representing the URI that results from resolving the given
- * (possibly relative) [containedUri] against the URI associated with the
- * [containingSource], whether or not the resulting source exists, or `null`
- * if either the [containedUri] is invalid or if it cannot be resolved against
- * the [containingSource]'s URI.
- */
- Source _resolveUri(Source containingSource, String containedUri) {
- // Cache absolute URIs.
- if (containedUri.startsWith('dart:') ||
- containedUri.startsWith('package:')) {
- return _absoluteUriMap.putIfAbsent(containedUri, () {
- return context.sourceFactory.resolveUri(containingSource, containedUri);
- });
- }
- // Resolve relative URIs without caching.
- return context.sourceFactory.resolveUri(containingSource, containedUri);
- }
-
- /**
- * Write the content based information about the given [source].
- */
- void _writeCacheSourceContent(Source source, CacheSourceContentBuilder b) {
- if (!_sourceContentMap.containsKey(source)) {
- String key = _getCacheSourceContentKey(source);
- List<int> bytes = b.toBuffer();
- storage.put(key, bytes);
- // Put into the cache to avoid reading it later.
- _sourceContentMap[source] = new CacheSourceContent.fromBuffer(bytes);
- }
- }
-
- /**
- * Write [CacheSourceContent] for every unit of the given [library] and its
- * direct and indirect imports/exports.
- */
- void _writeCacheSourceContents(LibraryElement library,
- [Set<LibraryElement> writtenLibraries]) {
- Source librarySource = library.source;
- // Stop recursion cycle.
- writtenLibraries ??= new Set<LibraryElement>();
- if (!writtenLibraries.add(library)) {
- return;
- }
- // Write parts.
- List<String> partUris = <String>[];
- for (CompilationUnitElement part in library.parts) {
- partUris.add(part.uri);
- Source partSource = part.source;
- if (context.getKindOf(partSource) == SourceKind.PART) {
- _writeCacheSourceContent(partSource,
- new CacheSourceContentBuilder(kind: CacheSourceKind.part));
- }
- }
- // Write imports.
- List<String> importUris = <String>[];
- for (ImportElement element in library.imports) {
- String uri = element.uri;
- if (uri != null) {
- importUris.add(uri);
- _writeCacheSourceContents(element.importedLibrary, writtenLibraries);
- }
- }
- // Write exports.
- List<String> exportUris = <String>[];
- for (ExportElement element in library.exports) {
- String uri = element.uri;
- if (uri != null) {
- exportUris.add(uri);
- _writeCacheSourceContents(element.exportedLibrary, writtenLibraries);
- }
- }
- // Write the library.
- _writeCacheSourceContent(
- librarySource,
- new CacheSourceContentBuilder(
- kind: CacheSourceKind.library,
- importedUris: importUris,
- exportedUris: exportUris,
- partUris: partUris));
- }
-}
-
-/**
- * The bundle for a source in the context.
- */
-class LibraryBundleWithId {
- /**
- * The source of the library this bundle is for.
- */
- final Source source;
-
- /**
- * The unique ID of the [bundle] of the [source] in the context.
- */
- final String id;
-
- /**
- * The payload bundle.
- */
- final PackageBundle bundle;
-
- LibraryBundleWithId(this.source, this.id, this.bundle);
-}
diff --git a/pkg/analyzer/lib/src/summary/link.dart b/pkg/analyzer/lib/src/summary/link.dart
index 7d77fb8..7b49939 100644
--- a/pkg/analyzer/lib/src/summary/link.dart
+++ b/pkg/analyzer/lib/src/summary/link.dart
@@ -100,10 +100,14 @@
* build unit, and whose values are the corresponding
* [LinkedLibraryBuilder]s.
*/
-Map<String, LinkedLibraryBuilder> link(Set<String> libraryUris,
- GetDependencyCallback getDependency, GetUnitCallback getUnit, bool strong) {
+Map<String, LinkedLibraryBuilder> link(
+ Set<String> libraryUris,
+ GetDependencyCallback getDependency,
+ GetUnitCallback getUnit,
+ GetDeclaredVariable getDeclaredVariable,
+ bool strong) {
Map<String, LinkedLibraryBuilder> linkedLibraries =
- setupForLink(libraryUris, getUnit);
+ setupForLink(libraryUris, getUnit, getDeclaredVariable);
relink(linkedLibraries, getDependency, getUnit, strong);
return linkedLibraries;
}
@@ -135,8 +139,8 @@
* the libraries in this build unit, and whose values are the corresponding
* [LinkedLibraryBuilder]s.
*/
-Map<String, LinkedLibraryBuilder> setupForLink(
- Set<String> libraryUris, GetUnitCallback getUnit) {
+Map<String, LinkedLibraryBuilder> setupForLink(Set<String> libraryUris,
+ GetUnitCallback getUnit, GetDeclaredVariable getDeclaredVariable) {
Map<String, LinkedLibraryBuilder> linkedLibraries =
<String, LinkedLibraryBuilder>{};
for (String absoluteUri in libraryUris) {
@@ -146,7 +150,8 @@
linkedLibraries[absoluteUri] = prelink(
getUnit(absoluteUri),
getRelativeUnit,
- (String relativeUri) => getRelativeUnit(relativeUri)?.publicNamespace);
+ (String relativeUri) => getRelativeUnit(relativeUri)?.publicNamespace,
+ getDeclaredVariable);
}
return linkedLibraries;
}
@@ -2624,7 +2629,12 @@
});
// Perform inference.
FunctionType inferred = ts.inferGenericFunctionCall(
- typeProvider, rawMethodType, paramTypes, argTypes, null);
+ typeProvider,
+ rawMethodType,
+ paramTypes,
+ argTypes,
+ rawMethodType.returnType,
+ null);
return inferred;
}
}
@@ -3405,8 +3415,16 @@
* Return the [LibraryElement] corresponding to the given dependency [index].
*/
LibraryElementForLink _getDependency(int index) {
- return _dependencies[index] ??= _linker.getLibrary(resolveRelativeUri(
- _absoluteUri, Uri.parse(_linkedLibrary.dependencies[index].uri)));
+ LibraryElementForLink result = _dependencies[index];
+ if (result == null) {
+ String relativeUri = _linkedLibrary.dependencies[index].uri;
+ Uri absoluteUri = relativeUri.isEmpty
+ ? _absoluteUri
+ : resolveRelativeUri(_absoluteUri, Uri.parse(relativeUri));
+ result = _linker.getLibrary(absoluteUri);
+ _dependencies[index] = result;
+ }
+ return result;
}
/**
@@ -3901,6 +3919,9 @@
DartType _inferredType;
DartType _declaredType;
+ @override
+ bool inheritsCovariant = false;
+
ParameterElementForLink(this.enclosingElement, this._unlinkedParam,
this._typeParameterContext, this.compilationUnit, this._parameterIndex) {
if (_unlinkedParam.initializer?.bodyExpr != null) {
@@ -3916,6 +3937,9 @@
!_unlinkedParam.isFunctionTyped && _unlinkedParam.type == null;
@override
+ bool get isCovariant => false;
+
+ @override
String get name => _unlinkedParam.name;
@override
@@ -3983,9 +4007,15 @@
@override
final PropertyAccessorElementForLink_Variable enclosingElement;
+ @override
+ bool inheritsCovariant = false;
+
ParameterElementForLink_VariableSetter(this.enclosingElement);
@override
+ bool get isCovariant => false;
+
+ @override
bool get isSynthetic => true;
@override
diff --git a/pkg/analyzer/lib/src/summary/prelink.dart b/pkg/analyzer/lib/src/summary/prelink.dart
index ec947f0..062676e 100644
--- a/pkg/analyzer/lib/src/summary/prelink.dart
+++ b/pkg/analyzer/lib/src/summary/prelink.dart
@@ -17,11 +17,18 @@
* declarations) will be retrieved using [getImport].
*/
LinkedLibraryBuilder prelink(UnlinkedUnit definingUnit, GetPartCallback getPart,
- GetImportCallback getImport) {
- return new _Prelinker(definingUnit, getPart, getImport).prelink();
+ GetImportCallback getImport, GetDeclaredVariable getDeclaredVariable) {
+ return new _Prelinker(definingUnit, getPart, getImport, getDeclaredVariable)
+ .prelink();
}
/**
+ * Return the raw string value of the variable with the given [name],
+ * or `null` of the variable is not defined.
+ */
+typedef String GetDeclaredVariable(String name);
+
+/**
* Type of the callback used by the prelinker to obtain public namespace
* information about libraries imported by the library to be prelinked (and
* the transitive closure of parts and exports reachable from those libraries).
@@ -121,6 +128,7 @@
final UnlinkedUnit definingUnit;
final GetPartCallback getPart;
final GetImportCallback getImport;
+ final GetDeclaredVariable getDeclaredVariable;
/**
* Cache of values returned by [getImport].
@@ -161,7 +169,8 @@
final List<Map<String, _Meaning>> dependencyToPublicNamespace =
<Map<String, _Meaning>>[null];
- _Prelinker(this.definingUnit, this.getPart, this.getImport) {
+ _Prelinker(this.definingUnit, this.getPart, this.getImport,
+ this.getDeclaredVariable) {
partCache[null] = definingUnit;
importCache[null] = definingUnit.publicNamespace;
}
@@ -231,7 +240,9 @@
getImportCached(relativeUri);
if (exportedNamespace != null) {
for (UnlinkedExportPublic export in exportedNamespace.exports) {
- String exportUri = resolveUri(relativeUri, export.uri);
+ String relativeExportUri =
+ _selectUri(export.uri, export.configurations);
+ String exportUri = resolveUri(relativeUri, relativeExportUri);
NameFilter newFilter = filter.merge(
new NameFilter.forUnlinkedCombinators(export.combinators));
aggregatePublicNamespace(exportUri)
@@ -247,6 +258,7 @@
seenUris.remove(relativeUri);
}
}
+
chaseExports(NameFilter.identity, relativeUri, new Set<String>());
return exportNamespace;
}
@@ -385,7 +397,9 @@
* return value is the index of the imported library in [dependencies].
*/
int handleImport(UnlinkedImport import) {
- String uri = import.isImplicit ? 'dart:core' : import.uri;
+ String uri = import.isImplicit
+ ? 'dart:core'
+ : _selectUri(import.uri, import.configurations);
Map<String, _Meaning> targetNamespace = null;
if (import.prefixReference != 0) {
// The name introduced by an import declaration can't have a prefix of
@@ -483,9 +497,11 @@
// Fill in imported and exported names.
List<int> importDependencies =
definingUnit.imports.map(handleImport).toList();
- List<int> exportDependencies = definingUnit.publicNamespace.exports
- .map((UnlinkedExportPublic exp) => uriToDependency[exp.uri])
- .toList();
+ List<int> exportDependencies =
+ definingUnit.publicNamespace.exports.map((UnlinkedExportPublic exp) {
+ String uri = _selectUri(exp.uri, exp.configurations);
+ return uriToDependency[uri];
+ }).toList();
// Link each compilation unit.
List<LinkedUnitBuilder> linkedUnits = units.map(linkUnit).toList();
@@ -511,4 +527,18 @@
.toString();
}
}
+
+ /**
+ * Return the URI of the first configuration from the given [configurations]
+ * which condition is satisfied, or the [defaultUri].
+ */
+ String _selectUri(
+ String defaultUri, List<UnlinkedConfiguration> configurations) {
+ for (UnlinkedConfiguration configuration in configurations) {
+ if (getDeclaredVariable(configuration.name) == configuration.value) {
+ return configuration.uri;
+ }
+ }
+ return defaultUri;
+ }
}
diff --git a/pkg/analyzer/lib/src/summary/pub_summary.dart b/pkg/analyzer/lib/src/summary/pub_summary.dart
index ba5b968..5891183 100644
--- a/pkg/analyzer/lib/src/summary/pub_summary.dart
+++ b/pkg/analyzer/lib/src/summary/pub_summary.dart
@@ -8,11 +8,11 @@
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/ast/token.dart';
+import 'package:analyzer/error/listener.dart';
import 'package:analyzer/file_system/file_system.dart';
import 'package:analyzer/src/dart/scanner/reader.dart';
import 'package:analyzer/src/dart/scanner/scanner.dart';
import 'package:analyzer/src/generated/engine.dart';
-import 'package:analyzer/src/generated/error.dart';
import 'package:analyzer/src/generated/parser.dart';
import 'package:analyzer/src/generated/source.dart';
import 'package:analyzer/src/generated/utilities_collection.dart';
@@ -741,6 +741,9 @@
return store.linkedMap[uri];
}, (String uri) {
return store.unlinkedMap[uri];
+ }, (String name) {
+ // TODO(scheglov) decide how to use declared variables in Pub
+ return null;
}, strong);
// Assemble linked bundles and put them into the store.
for (_LinkedNode node in scc) {
diff --git a/pkg/analyzer/lib/src/summary/public_namespace_computer.dart b/pkg/analyzer/lib/src/summary/public_namespace_computer.dart
index 9cd9007..9a8bd50 100644
--- a/pkg/analyzer/lib/src/summary/public_namespace_computer.dart
+++ b/pkg/analyzer/lib/src/summary/public_namespace_computer.dart
@@ -19,6 +19,17 @@
names: visitor.names, exports: visitor.exports, parts: visitor.parts);
}
+/**
+ * Serialize a [Configuration] into a [UnlinkedConfigurationBuilder].
+ */
+UnlinkedConfigurationBuilder serializeConfiguration(
+ Configuration configuration) {
+ return new UnlinkedConfigurationBuilder(
+ name: configuration.name.components.map((i) => i.name).join('.'),
+ value: configuration.value?.stringValue ?? 'true',
+ uri: configuration.uri.stringValue);
+}
+
class _CombinatorEncoder extends SimpleAstVisitor<UnlinkedCombinatorBuilder> {
_CombinatorEncoder();
@@ -140,7 +151,9 @@
uri: node.uri.stringValue,
combinators: node.combinators
.map((Combinator c) => c.accept(new _CombinatorEncoder()))
- .toList()));
+ .toList(),
+ configurations:
+ node.configurations.map(serializeConfiguration).toList()));
}
@override
diff --git a/pkg/analyzer/lib/src/summary/summarize_ast.dart b/pkg/analyzer/lib/src/summary/summarize_ast.dart
index ede1b0a..87bf1d1 100644
--- a/pkg/analyzer/lib/src/summary/summarize_ast.dart
+++ b/pkg/analyzer/lib/src/summary/summarize_ast.dart
@@ -1262,6 +1262,7 @@
}
b.offset = node.offset;
b.combinators = node.combinators.map(serializeCombinator).toList();
+ b.configurations = node.configurations.map(serializeConfiguration).toList();
if (node.prefix != null) {
b.prefixReference = serializeReference(null, node.prefix.name);
b.prefixOffset = node.prefix.offset;
diff --git a/pkg/analyzer/lib/src/summary/summarize_elements.dart b/pkg/analyzer/lib/src/summary/summarize_elements.dart
index 1a0e22d..2af7bde 100644
--- a/pkg/analyzer/lib/src/summary/summarize_elements.dart
+++ b/pkg/analyzer/lib/src/summary/summarize_elements.dart
@@ -6,112 +6,13 @@
import 'dart:convert';
-import 'package:analyzer/dart/ast/ast.dart';
-import 'package:analyzer/dart/element/element.dart';
-import 'package:analyzer/dart/element/type.dart';
-import 'package:analyzer/src/dart/element/element.dart';
-import 'package:analyzer/src/dart/element/member.dart';
-import 'package:analyzer/src/dart/element/type.dart';
-import 'package:analyzer/src/generated/resolver.dart';
import 'package:analyzer/src/generated/source.dart';
-import 'package:analyzer/src/generated/utilities_dart.dart';
import 'package:analyzer/src/summary/api_signature.dart';
import 'package:analyzer/src/summary/format.dart';
import 'package:analyzer/src/summary/idl.dart';
-import 'package:analyzer/src/summary/name_filter.dart';
import 'package:analyzer/src/summary/package_bundle_reader.dart';
-import 'package:analyzer/src/summary/summarize_const_expr.dart';
import 'package:convert/convert.dart';
import 'package:crypto/crypto.dart';
-import 'package:path/path.dart' as path;
-
-/**
- * Serialize all the elements in [lib] to a summary using [ctx] as the context
- * for building the summary, and using [typeProvider] to find built-in types.
- */
-LibrarySerializationResult serializeLibrary(
- LibraryElement lib, TypeProvider typeProvider, bool strongMode) {
- _LibrarySerializer serializer =
- new _LibrarySerializer(lib, typeProvider, strongMode);
- LinkedLibraryBuilder linked = serializer.serializeLibrary();
- return new LibrarySerializationResult(linked, serializer.unlinkedUnits,
- serializer.unitUris, serializer.unitSources);
-}
-
-ReferenceKind _getReferenceKind(Element element) {
- if (element == null ||
- element is ClassElement ||
- element is DynamicElementImpl) {
- return ReferenceKind.classOrEnum;
- } else if (element is ConstructorElement) {
- return ReferenceKind.constructor;
- } else if (element is FunctionElement) {
- if (element.enclosingElement is CompilationUnitElement) {
- return ReferenceKind.topLevelFunction;
- }
- return ReferenceKind.function;
- } else if (element is FunctionTypeAliasElement) {
- return ReferenceKind.typedef;
- } else if (element is PropertyAccessorElement) {
- if (element.enclosingElement is ClassElement) {
- return ReferenceKind.propertyAccessor;
- }
- return ReferenceKind.topLevelPropertyAccessor;
- } else if (element is MethodElement) {
- return ReferenceKind.method;
- } else if (element is TopLevelVariableElement) {
- // Summaries don't need to distinguish between references to a variable and
- // references to its getter.
- return ReferenceKind.topLevelPropertyAccessor;
- } else if (element is LocalVariableElement) {
- return ReferenceKind.variable;
- } else if (element is FieldElement) {
- // Summaries don't need to distinguish between references to a field and
- // references to its getter.
- return ReferenceKind.propertyAccessor;
- } else {
- throw new Exception('Unexpected element kind: ${element.runtimeType}');
- }
-}
-
-/**
- * Type of closures used by [_LibrarySerializer] to defer generation of
- * [EntityRefBuilder] objects until the end of serialization of a
- * compilation unit.
- */
-typedef EntityRefBuilder _SerializeTypeRef();
-
-/**
- * Data structure holding the result of serializing a [LibraryElement].
- */
-class LibrarySerializationResult {
- /**
- * Linked information the given library.
- */
- final LinkedLibraryBuilder linked;
-
- /**
- * Unlinked information for the compilation units constituting the library.
- * The zeroth entry in the list is the defining compilation unit; the
- * remaining entries are the parts, in the order listed in the defining
- * compilation unit's part declarations.
- */
- final List<UnlinkedUnitBuilder> unlinkedUnits;
-
- /**
- * Absolute URI of each compilation unit appearing in the library.
- */
- final List<String> unitUris;
-
- /**
- * Source object corresponding to each compilation unit appearing in the
- * library.
- */
- final List<Source> unitSources;
-
- LibrarySerializationResult(
- this.linked, this.unlinkedUnits, this.unitUris, this.unitSources);
-}
/**
* Object that gathers information uses it to assemble a new
@@ -154,31 +55,6 @@
: _excludeHashes = excludeHashes,
_unlinkedUnitHashes = excludeHashes ? null : <String>[];
- /**
- * Add a fallback library to the package bundle, corresponding to the library
- * whose defining compilation unit is located at [source]. Caller must also
- * call [addFallbackUnit] for all compilation units contained in the library
- * (including the defining compilation unit).
- */
- void addFallbackLibrary(Source source) {
- String uri = source.uri.toString();
- _linkedLibraryUris.add(uri);
- _linkedLibraries.add(new LinkedLibraryBuilder(fallbackMode: true));
- }
-
- /**
- * Add a fallback compilation unit to the package bundle, corresponding to
- * the compilation unit located at [source].
- */
- void addFallbackUnit(Source source) {
- String uri = source.uri.toString();
- UnlinkedUnitBuilder unit = new UnlinkedUnitBuilder(
- fallbackModePath: path.relative(source.fullName));
- _unlinkedUnitUris.add(uri);
- _unlinkedUnits.add(unit);
- _unlinkedUnitMap[uri] = unit;
- }
-
void addLinkedLibrary(String uri, LinkedLibraryBuilder library) {
_linkedLibraries.add(library);
_linkedLibraryUris.add(uri);
@@ -222,28 +98,6 @@
}
/**
- * Serialize the library with the given [element].
- */
- void serializeLibraryElement(LibraryElement element) {
- String uri = element.source.uri.toString();
- LibrarySerializationResult libraryResult = serializeLibrary(
- element,
- element.context.typeProvider,
- element.context.analysisOptions.strongMode);
- _linkedLibraryUris.add(uri);
- _linkedLibraries.add(libraryResult.linked);
- _unlinkedUnitUris.addAll(libraryResult.unitUris);
- _unlinkedUnits.addAll(libraryResult.unlinkedUnits);
- for (int i = 0; i < libraryResult.unitUris.length; i++) {
- _unlinkedUnitMap[libraryResult.unitUris[i]] =
- libraryResult.unlinkedUnits[i];
- }
- for (Source source in libraryResult.unitSources) {
- _unlinkedUnitHashes?.add(_hash(source.contents.data));
- }
- }
-
- /**
* Compute the API signature for this package bundle.
*/
String _computeApiSignature() {
@@ -262,1458 +116,3 @@
return hex.encode(md5.convert(UTF8.encode(contents)).bytes);
}
}
-
-/**
- * Instances of this class keep track of intermediate state during
- * serialization of a single compilation unit.
- */
-class _CompilationUnitSerializer {
- /**
- * The [_LibrarySerializer] which is serializing the library of which
- * [compilationUnit] is a part.
- */
- final _LibrarySerializer librarySerializer;
-
- /**
- * The [CompilationUnitElement] being serialized.
- */
- final CompilationUnitElement compilationUnit;
-
- /**
- * The ordinal index of [compilationUnit] within the library, where 0
- * represents the defining compilation unit.
- */
- final int unitNum;
-
- /**
- * The final linked summary of the compilation unit.
- */
- final LinkedUnitBuilder linkedUnit = new LinkedUnitBuilder();
-
- /**
- * The final unlinked summary of the compilation unit.
- */
- final UnlinkedUnitBuilder unlinkedUnit = new UnlinkedUnitBuilder();
-
- /**
- * Absolute URI of the compilation unit.
- */
- String unitUri;
-
- /**
- * Map from [Element] to the index of the entry in the "references table"
- * that refers to it.
- */
- final Map<Element, int> referenceMap = <Element, int>{};
-
- /**
- * The unlinked portion of the "references table". This is the list of
- * objects which should be written to [UnlinkedUnit.references].
- */
- List<UnlinkedReferenceBuilder> unlinkedReferences;
-
- /**
- * The linked portion of the "references table". This is the list of
- * objects which should be written to [LinkedUnit.references].
- */
- List<LinkedReferenceBuilder> linkedReferences;
-
- /**
- * The number of slot ids which have been assigned to this compilation unit.
- */
- int numSlots = 0;
-
- /**
- * List of closures which should be invoked at the end of serialization of a
- * compilation unit, to produce [LinkedUnit.types].
- */
- final List<_SerializeTypeRef> deferredLinkedTypes = <_SerializeTypeRef>[];
-
- /**
- * List which should be stored in [LinkedUnit.constCycles].
- */
- final List<int> constCycles = <int>[];
-
- /**
- * Index into the "references table" representing an unresolved reference, if
- * such an index exists. `null` if no such entry has been made in the
- * references table yet.
- */
- int unresolvedReferenceIndex = null;
-
- /**
- * Index into the "references table" representing the "bottom" type, if such
- * an index exists. `null` if no such entry has been made in the references
- * table yet.
- */
- int bottomReferenceIndex = null;
-
- /**
- * If `true`, we are currently generating linked references, so new
- * references will be not stored in [unlinkedReferences].
- */
- bool buildingLinkedReferences = false;
-
- _CompilationUnitSerializer(
- this.librarySerializer, this.compilationUnit, this.unitNum);
-
- /**
- * Source object for the compilation unit.
- */
- Source get unitSource => compilationUnit.source;
-
- /**
- * Add all classes, enums, typedefs, executables, and top level variables
- * from the given compilation unit [element] to the compilation unit summary.
- * [unitNum] indicates the ordinal position of this compilation unit in the
- * library.
- */
- void addCompilationUnitElements() {
- unlinkedReferences = <UnlinkedReferenceBuilder>[
- new UnlinkedReferenceBuilder()
- ];
- linkedReferences = <LinkedReferenceBuilder>[
- new LinkedReferenceBuilder(kind: ReferenceKind.unresolved)
- ];
- List<UnlinkedPublicNameBuilder> names = <UnlinkedPublicNameBuilder>[];
- for (PropertyAccessorElement accessor in compilationUnit.accessors) {
- if (accessor.isPublic) {
- names.add(new UnlinkedPublicNameBuilder(
- kind: ReferenceKind.topLevelPropertyAccessor,
- name: accessor.name,
- numTypeParameters: accessor.typeParameters.length));
- }
- }
- for (ClassElement cls in compilationUnit.types) {
- if (cls.isPublic) {
- names.add(new UnlinkedPublicNameBuilder(
- kind: ReferenceKind.classOrEnum,
- name: cls.name,
- numTypeParameters: cls.typeParameters.length,
- members: serializeClassStaticMembers(cls)));
- }
- }
- for (ClassElement enm in compilationUnit.enums) {
- if (enm.isPublic) {
- names.add(new UnlinkedPublicNameBuilder(
- kind: ReferenceKind.classOrEnum,
- name: enm.name,
- members: serializeClassStaticMembers(enm)));
- }
- }
- for (FunctionElement function in compilationUnit.functions) {
- if (function.isPublic) {
- names.add(new UnlinkedPublicNameBuilder(
- kind: ReferenceKind.topLevelFunction,
- name: function.name,
- numTypeParameters: function.typeParameters.length));
- }
- }
- for (FunctionTypeAliasElement typedef
- in compilationUnit.functionTypeAliases) {
- if (typedef.isPublic) {
- names.add(new UnlinkedPublicNameBuilder(
- kind: ReferenceKind.typedef,
- name: typedef.name,
- numTypeParameters: typedef.typeParameters.length));
- }
- }
- if (unitNum == 0) {
- LibraryElement libraryElement = librarySerializer.libraryElement;
- if (libraryElement.name.isNotEmpty) {
- LibraryElement libraryElement = librarySerializer.libraryElement;
- unlinkedUnit.libraryName = libraryElement.name;
- unlinkedUnit.libraryNameOffset = libraryElement.nameOffset;
- unlinkedUnit.libraryNameLength = libraryElement.nameLength;
- unlinkedUnit.libraryDocumentationComment =
- serializeDocumentation(libraryElement);
- unlinkedUnit.libraryAnnotations = serializeAnnotations(libraryElement);
- }
- unlinkedUnit.publicNamespace = new UnlinkedPublicNamespaceBuilder(
- exports: libraryElement.exports.map(serializeExportPublic).toList(),
- parts: libraryElement.parts
- .map((CompilationUnitElement e) => e.uri)
- .toList(),
- names: names);
- unlinkedUnit.exports =
- libraryElement.exports.map(serializeExportNonPublic).toList();
- unlinkedUnit.imports =
- libraryElement.imports.map(serializeImport).toList();
- unlinkedUnit.parts = libraryElement.parts
- .map((CompilationUnitElement e) => new UnlinkedPartBuilder(
- uriOffset: e.uriOffset,
- uriEnd: e.uriEnd,
- annotations: serializeAnnotations(e)))
- .toList();
- } else {
- // TODO(paulberry): we need to figure out a way to record library, part,
- // import, and export declarations that appear in non-defining
- // compilation units (even though such declarations are prohibited by the
- // language), so that if the user makes code changes that cause a
- // non-defining compilation unit to become a defining compilation unit,
- // we can create a correct summary by simply re-linking.
- unlinkedUnit.publicNamespace =
- new UnlinkedPublicNamespaceBuilder(names: names);
- }
- unlinkedUnit.codeRange = serializeCodeRange(compilationUnit);
- unlinkedUnit.classes = compilationUnit.types.map(serializeClass).toList();
- unlinkedUnit.enums = compilationUnit.enums.map(serializeEnum).toList();
- unlinkedUnit.typedefs =
- compilationUnit.functionTypeAliases.map(serializeTypedef).toList();
- List<UnlinkedExecutableBuilder> executables =
- compilationUnit.functions.map(serializeExecutable).toList();
- for (PropertyAccessorElement accessor in compilationUnit.accessors) {
- if (!accessor.isSynthetic) {
- executables.add(serializeExecutable(accessor));
- }
- }
- unlinkedUnit.executables = executables;
- List<UnlinkedVariableBuilder> variables = <UnlinkedVariableBuilder>[];
- for (PropertyAccessorElement accessor in compilationUnit.accessors) {
- if (accessor.isSynthetic && accessor.isGetter) {
- PropertyInducingElement variable = accessor.variable;
- if (variable != null) {
- assert(!variable.isSynthetic);
- variables.add(serializeVariable(variable));
- }
- }
- }
- unlinkedUnit.variables = variables;
- unlinkedUnit.references = unlinkedReferences;
- unlinkedUnit.lineStarts =
- compilationUnit.context?.computeLineInfo(unitSource)?.lineStarts;
- linkedUnit.references = linkedReferences;
- unitUri = compilationUnit.source.uri.toString();
- }
-
- /**
- * Create the [LinkedUnit.types] table based on deferred types that were
- * found during [addCompilationUnitElements]. Also populate
- * [LinkedUnit.constCycles].
- */
- void createLinkedInfo() {
- buildingLinkedReferences = true;
- linkedUnit.types = deferredLinkedTypes
- .map((_SerializeTypeRef closure) => closure())
- .toList();
- linkedUnit.constCycles = constCycles;
- buildingLinkedReferences = false;
- }
-
- /**
- * Compute the appropriate De Bruijn index to represent the given type
- * parameter [type], or return `null` if the type parameter is not in scope.
- */
- int findTypeParameterIndex(TypeParameterType type, Element context) {
- int index = 0;
- while (context != null) {
- List<TypeParameterElement> typeParameters;
- if (context is ClassElement) {
- typeParameters = context.typeParameters;
- } else if (context is FunctionTypeAliasElement) {
- typeParameters = context.typeParameters;
- } else if (context is ExecutableElement) {
- typeParameters = context.typeParameters;
- }
- if (typeParameters != null) {
- for (int i = 0; i < typeParameters.length; i++) {
- TypeParameterElement param = typeParameters[i];
- if (param == type.element) {
- return index + typeParameters.length - i;
- }
- }
- index += typeParameters.length;
- }
- context = context.enclosingElement;
- }
- return null;
- }
-
- /**
- * Get the type arguments for the given [type], or `null` if the type has no
- * type arguments.
- *
- * TODO(paulberry): consider adding an abstract getter to [DartType] to do
- * this.
- */
- List<DartType> getTypeArguments(DartType type) {
- if (type is InterfaceType) {
- return type.typeArguments;
- } else if (type is FunctionType) {
- return type.typeArguments;
- } else {
- return null;
- }
- }
-
- /**
- * Serialize annotations from the given [element]. If [element] has no
- * annotations, the empty list is returned.
- */
- List<UnlinkedConstBuilder> serializeAnnotations(Element element) {
- if (element.metadata.isEmpty) {
- return const <UnlinkedConstBuilder>[];
- }
- return element.metadata.map((ElementAnnotation a) {
- _ConstExprSerializer serializer =
- new _ConstExprSerializer(this, element, null, null);
- serializer
- .serializeAnnotation((a as ElementAnnotationImpl).annotationAst);
- return serializer.toBuilder();
- }).toList();
- }
-
- /**
- * Return the index of the entry in the references table
- * ([LinkedLibrary.references]) used for the "bottom" type. A new entry is
- * added to the table if necessary to satisfy the request.
- */
- int serializeBottomReference() {
- if (bottomReferenceIndex == null) {
- // References to the "bottom" type are always implicit, since there is no
- // way to explicitly refer to the "bottom" type. Therefore they should
- // be stored only in the linked references table.
- bottomReferenceIndex = linkedReferences.length;
- linkedReferences.add(new LinkedReferenceBuilder(
- name: '*bottom*', kind: ReferenceKind.classOrEnum));
- }
- return bottomReferenceIndex;
- }
-
- /**
- * Serialize the given [classElement], creating an [UnlinkedClass].
- */
- UnlinkedClassBuilder serializeClass(ClassElement classElement) {
- UnlinkedClassBuilder b = new UnlinkedClassBuilder();
- b.name = classElement.name;
- b.nameOffset = classElement.nameOffset;
- b.typeParameters =
- classElement.typeParameters.map(serializeTypeParam).toList();
- if (classElement.supertype == null) {
- b.hasNoSupertype = true;
- } else if (!classElement.supertype.isObject) {
- b.supertype = serializeTypeRef(classElement.supertype, classElement);
- }
- b.mixins = classElement.mixins
- .map((InterfaceType t) => serializeTypeRef(t, classElement))
- .toList();
- b.interfaces = classElement.interfaces
- .map((InterfaceType t) => serializeTypeRef(t, classElement))
- .toList();
- List<UnlinkedVariableBuilder> fields = <UnlinkedVariableBuilder>[];
- List<UnlinkedExecutableBuilder> executables = <UnlinkedExecutableBuilder>[];
- for (ConstructorElement executable in classElement.constructors) {
- if (!executable.isSynthetic) {
- executables.add(serializeExecutable(executable));
- }
- }
- for (MethodElement executable in classElement.methods) {
- executables.add(serializeExecutable(executable));
- }
- for (PropertyAccessorElement accessor in classElement.accessors) {
- if (!accessor.isSynthetic) {
- executables.add(serializeExecutable(accessor));
- } else if (accessor.isGetter) {
- PropertyInducingElement field = accessor.variable;
- if (field != null && !field.isSynthetic) {
- fields.add(serializeVariable(field));
- }
- }
- }
- b.fields = fields;
- b.executables = executables;
- b.isAbstract = classElement.isAbstract;
- b.isMixinApplication = classElement.isMixinApplication;
- b.documentationComment = serializeDocumentation(classElement);
- b.annotations = serializeAnnotations(classElement);
- b.codeRange = serializeCodeRange(classElement);
- return b;
- }
-
- /**
- * If [cls] is a class, return the list of its static members - static
- * constant fields, static methods and constructors. Otherwise return `null`.
- */
- List<UnlinkedPublicNameBuilder> serializeClassStaticMembers(
- ClassElement cls) {
- if (cls.isMixinApplication) {
- // Mixin application members can't be determined directly from the AST so
- // we can't store them in UnlinkedPublicName.
- // TODO(paulberry): find somewhere else to store them.
- return null;
- }
- if (cls.kind == ElementKind.CLASS) {
- List<UnlinkedPublicNameBuilder> bs = <UnlinkedPublicNameBuilder>[];
- for (MethodElement method in cls.methods) {
- if (method.isStatic && method.isPublic) {
- // TODO(paulberry): should numTypeParameters include class params?
- bs.add(new UnlinkedPublicNameBuilder(
- name: method.name,
- kind: ReferenceKind.method,
- numTypeParameters: method.typeParameters.length));
- }
- }
- for (PropertyAccessorElement accessor in cls.accessors) {
- if (accessor.isStatic && accessor.isGetter && accessor.isPublic) {
- // TODO(paulberry): should numTypeParameters include class params?
- bs.add(new UnlinkedPublicNameBuilder(
- name: accessor.name, kind: ReferenceKind.propertyAccessor));
- }
- }
- for (ConstructorElement constructor in cls.constructors) {
- if (constructor.isPublic && constructor.name.isNotEmpty) {
- // TODO(paulberry): should numTypeParameters include class params?
- bs.add(new UnlinkedPublicNameBuilder(
- name: constructor.name,
- kind: ReferenceKind.constructor,
- numTypeParameters: 0));
- }
- }
- return bs;
- }
- return null;
- }
-
- CodeRangeBuilder serializeCodeRange(Element element) {
- if (element is ElementImpl && element.codeOffset != null) {
- return new CodeRangeBuilder(
- offset: element.codeOffset, length: element.codeLength);
- }
- return null;
- }
-
- /**
- * Serialize the given [combinator] into an [UnlinkedCombinator].
- */
- UnlinkedCombinatorBuilder serializeCombinator(
- NamespaceCombinator combinator) {
- UnlinkedCombinatorBuilder b = new UnlinkedCombinatorBuilder();
- if (combinator is ShowElementCombinator) {
- b.shows = combinator.shownNames;
- b.offset = combinator.offset;
- b.end = combinator.end;
- } else if (combinator is HideElementCombinator) {
- b.hides = combinator.hiddenNames;
- }
- return b;
- }
-
- /**
- * Serialize the given [expression], creating an [UnlinkedConstBuilder].
- */
- UnlinkedConstBuilder serializeConstExpr(Element context,
- ExecutableElement executableContext, Expression expression,
- [Set<String> constructorParameterNames]) {
- _ConstExprSerializer serializer = new _ConstExprSerializer(
- this, context, executableContext, constructorParameterNames);
- serializer.serialize(expression);
- return serializer.toBuilder();
- }
-
- /**
- * Serialize documentation from the given [element], creating an
- * [UnlinkedDocumentationComment].
- *
- * If [element] has no documentation, `null` is returned.
- */
- UnlinkedDocumentationCommentBuilder serializeDocumentation(Element element) {
- if (element.documentationComment == null) {
- return null;
- }
- return new UnlinkedDocumentationCommentBuilder(
- text: element.documentationComment);
- }
-
- /**
- * Serialize the given [enumElement], creating an [UnlinkedEnum].
- */
- UnlinkedEnumBuilder serializeEnum(ClassElement enumElement) {
- UnlinkedEnumBuilder b = new UnlinkedEnumBuilder();
- b.name = enumElement.name;
- b.nameOffset = enumElement.nameOffset;
- List<UnlinkedEnumValueBuilder> values = <UnlinkedEnumValueBuilder>[];
- for (FieldElement field in enumElement.fields) {
- if (field.isConst && field.type.element == enumElement) {
- values.add(new UnlinkedEnumValueBuilder(
- name: field.name,
- nameOffset: field.nameOffset,
- documentationComment: serializeDocumentation(field)));
- }
- }
- b.values = values;
- b.documentationComment = serializeDocumentation(enumElement);
- b.annotations = serializeAnnotations(enumElement);
- b.codeRange = serializeCodeRange(enumElement);
- return b;
- }
-
- /**
- * Serialize the given [executableElement], creating an [UnlinkedExecutable].
- */
- UnlinkedExecutableBuilder serializeExecutable(
- ExecutableElement executableElement) {
- UnlinkedExecutableBuilder b = new UnlinkedExecutableBuilder();
- b.name = executableElement.name;
- b.nameOffset = executableElement.nameOffset;
- if (executableElement is ConstructorElement) {
- if (executableElement.name.isNotEmpty) {
- b.nameEnd = executableElement.nameEnd;
- b.periodOffset = executableElement.periodOffset;
- }
- } else {
- if (!executableElement.hasImplicitReturnType) {
- b.returnType = serializeTypeRef(
- executableElement.type.returnType, executableElement);
- } else if (!executableElement.isStatic) {
- b.inferredReturnTypeSlot =
- storeInferredType(executableElement.returnType, executableElement);
- }
- }
- b.typeParameters =
- executableElement.typeParameters.map(serializeTypeParam).toList();
- b.parameters =
- executableElement.type.parameters.map(serializeParam).toList();
- if (executableElement is PropertyAccessorElement) {
- if (executableElement.isGetter) {
- b.kind = UnlinkedExecutableKind.getter;
- } else {
- b.kind = UnlinkedExecutableKind.setter;
- }
- } else if (executableElement is ConstructorElementImpl) {
- b.kind = UnlinkedExecutableKind.constructor;
- b.isConst = executableElement.isConst;
- b.isFactory = executableElement.isFactory;
- ConstructorElement redirectedConstructor =
- executableElement.redirectedConstructor;
- if (redirectedConstructor != null) {
- b.isRedirectedConstructor = true;
- if (executableElement.isFactory) {
- InterfaceType returnType = redirectedConstructor is ConstructorMember
- ? redirectedConstructor.definingType
- : redirectedConstructor.enclosingElement.type;
- EntityRefBuilder typeRef =
- serializeTypeRef(returnType, executableElement);
- if (redirectedConstructor.name.isNotEmpty) {
- String name = redirectedConstructor.name;
- int typeId = typeRef.reference;
- LinkedReference typeLinkedRef = linkedReferences[typeId];
- int refId = serializeUnlinkedReference(
- name, ReferenceKind.constructor,
- unit: typeLinkedRef.unit, prefixReference: typeId);
- b.redirectedConstructor = new EntityRefBuilder(
- reference: refId, typeArguments: typeRef.typeArguments);
- } else {
- b.redirectedConstructor = typeRef;
- }
- } else {
- b.redirectedConstructorName = redirectedConstructor.name;
- }
- }
- if (executableElement.isConst) {
- b.constCycleSlot = storeConstCycle(!executableElement.isCycleFree);
- if (executableElement.constantInitializers != null) {
- Set<String> constructorParameterNames =
- executableElement.parameters.map((p) => p.name).toSet();
- b.constantInitializers = executableElement.constantInitializers
- .map((ConstructorInitializer initializer) =>
- serializeConstructorInitializer(
- initializer,
- (expr) => serializeConstExpr(executableElement,
- executableElement, expr, constructorParameterNames)))
- .toList();
- }
- }
- } else {
- b.kind = UnlinkedExecutableKind.functionOrMethod;
- }
- b.isAbstract = executableElement.isAbstract;
- b.isAsynchronous = executableElement.isAsynchronous;
- b.isGenerator = executableElement.isGenerator;
- b.isStatic = executableElement.isStatic &&
- executableElement.enclosingElement is ClassElement;
- b.isExternal = executableElement.isExternal;
- b.documentationComment = serializeDocumentation(executableElement);
- b.annotations = serializeAnnotations(executableElement);
- b.codeRange = serializeCodeRange(executableElement);
- if (executableElement is FunctionElement) {
- SourceRange visibleRange = executableElement.visibleRange;
- if (visibleRange != null) {
- b.visibleOffset = visibleRange.offset;
- b.visibleLength = visibleRange.length;
- }
- }
- b.localFunctions =
- executableElement.functions.map(serializeExecutable).toList();
- b.localLabels = executableElement.labels.map(serializeLabel).toList();
- b.localVariables =
- executableElement.localVariables.map(serializeVariable).toList();
- return b;
- }
-
- /**
- * Serialize the given [exportElement] into an [UnlinkedExportNonPublic].
- */
- UnlinkedExportNonPublicBuilder serializeExportNonPublic(
- ExportElement exportElement) {
- UnlinkedExportNonPublicBuilder b = new UnlinkedExportNonPublicBuilder();
- b.offset = exportElement.nameOffset;
- b.uriOffset = exportElement.uriOffset;
- b.uriEnd = exportElement.uriEnd;
- b.annotations = serializeAnnotations(exportElement);
- return b;
- }
-
- /**
- * Serialize the given [exportElement] into an [UnlinkedExportPublic].
- */
- UnlinkedExportPublicBuilder serializeExportPublic(
- ExportElement exportElement) {
- UnlinkedExportPublicBuilder b = new UnlinkedExportPublicBuilder();
- b.uri = exportElement.uri;
- b.combinators = exportElement.combinators.map(serializeCombinator).toList();
- return b;
- }
-
- /**
- * Serialize the given [importElement] yielding an [UnlinkedImportBuilder].
- * Also, add linked information about it to the [linkedImports] list.
- */
- UnlinkedImportBuilder serializeImport(ImportElement importElement) {
- UnlinkedImportBuilder b = new UnlinkedImportBuilder();
- b.annotations = serializeAnnotations(importElement);
- b.isDeferred = importElement.isDeferred;
- b.combinators = importElement.combinators.map(serializeCombinator).toList();
- if (importElement.prefix != null) {
- b.prefixReference = serializePrefix(importElement.prefix);
- b.prefixOffset = importElement.prefix.nameOffset;
- }
- if (importElement.isSynthetic) {
- b.isImplicit = true;
- } else {
- b.offset = importElement.nameOffset;
- b.uri = importElement.uri;
- b.uriOffset = importElement.uriOffset;
- b.uriEnd = importElement.uriEnd;
- }
- return b;
- }
-
- /**
- * Serialize the given [label], creating an [UnlinkedLabelBuilder].
- */
- UnlinkedLabelBuilder serializeLabel(LabelElement label) {
- LabelElementImpl labelImpl = label as LabelElementImpl;
- UnlinkedLabelBuilder b = new UnlinkedLabelBuilder();
- b.name = labelImpl.name;
- b.nameOffset = labelImpl.nameOffset;
- b.isOnSwitchMember = labelImpl.isOnSwitchMember;
- b.isOnSwitchStatement = labelImpl.isOnSwitchStatement;
- return b;
- }
-
- /**
- * Serialize the given [parameter] into an [UnlinkedParam].
- */
- UnlinkedParamBuilder serializeParam(ParameterElement parameter,
- [Element context]) {
- context ??= parameter;
- UnlinkedParamBuilder b = new UnlinkedParamBuilder();
- b.name = parameter.name;
- b.nameOffset = parameter.nameOffset >= 0 ? parameter.nameOffset : 0;
- switch (parameter.parameterKind) {
- case ParameterKind.REQUIRED:
- b.kind = UnlinkedParamKind.required;
- break;
- case ParameterKind.POSITIONAL:
- b.kind = UnlinkedParamKind.positional;
- break;
- case ParameterKind.NAMED:
- b.kind = UnlinkedParamKind.named;
- break;
- }
- b.annotations = serializeAnnotations(parameter);
- b.codeRange = serializeCodeRange(parameter);
- b.isInitializingFormal = parameter.isInitializingFormal;
- DartType type = parameter.type;
- if (parameter.hasImplicitType) {
- Element contextParent = context.enclosingElement;
- if (!parameter.isInitializingFormal &&
- contextParent is ExecutableElement &&
- !contextParent.isStatic &&
- contextParent is! ConstructorElement) {
- b.inferredTypeSlot = storeInferredType(type, context);
- }
- } else {
- if (type is FunctionType && type.element.isSynthetic) {
- b.isFunctionTyped = true;
- b.type = serializeTypeRef(type.returnType, parameter);
- b.parameters = type.parameters
- .map((parameter) => serializeParam(parameter, context))
- .toList();
- } else {
- b.type = serializeTypeRef(type, context);
- }
- }
- // TODO(scheglov) VariableMember.initializer is not implemented
- if (parameter is! VariableMember && parameter.initializer != null) {
- b.initializer = serializeExecutable(parameter.initializer);
- }
- if (parameter is ConstVariableElement) {
- ConstVariableElement constParameter = parameter as ConstVariableElement;
- Expression initializer = constParameter.constantInitializer;
- if (initializer != null) {
- b.initializer?.bodyExpr = serializeConstExpr(
- parameter,
- parameter.getAncestor((Element e) => e is ExecutableElement),
- initializer);
- b.defaultValueCode = parameter.defaultValueCode;
- }
- }
- {
- SourceRange visibleRange = parameter.visibleRange;
- if (visibleRange != null) {
- b.visibleOffset = visibleRange.offset;
- b.visibleLength = visibleRange.length;
- }
- }
- return b;
- }
-
- /**
- * Serialize the given [prefix] into an index into the references table.
- */
- int serializePrefix(PrefixElement element) {
- return referenceMap.putIfAbsent(element,
- () => serializeUnlinkedReference(element.name, ReferenceKind.prefix));
- }
-
- /**
- * Compute the reference index which should be stored in a [EntityRef].
- */
- int serializeReferenceForType(DartType type) {
- Element element = type.element;
- LibraryElement dependentLibrary = element?.library;
- if (dependentLibrary == null) {
- if (type.isBottom) {
- // References to the "bottom" type are always implicit, since there is
- // no way to explicitly refer to the "bottom" type. Therefore they
- // should always be linked.
- assert(buildingLinkedReferences);
- return serializeBottomReference();
- }
- assert(type.isDynamic || type.isVoid);
- if (type is UndefinedTypeImpl) {
- return serializeUnresolvedReference();
- }
- // Note: for a type which is truly `dynamic` or `void`, fall through to
- // use [_getElementReferenceId].
- }
- return _getElementReferenceId(element);
- }
-
- /**
- * Serialize the given [typedefElement], creating an [UnlinkedTypedef].
- */
- UnlinkedTypedefBuilder serializeTypedef(
- FunctionTypeAliasElement typedefElement) {
- UnlinkedTypedefBuilder b = new UnlinkedTypedefBuilder();
- b.name = typedefElement.name;
- b.nameOffset = typedefElement.nameOffset;
- b.typeParameters =
- typedefElement.typeParameters.map(serializeTypeParam).toList();
- b.returnType = serializeTypeRef(typedefElement.returnType, typedefElement);
- b.parameters = typedefElement.parameters.map(serializeParam).toList();
- b.documentationComment = serializeDocumentation(typedefElement);
- b.annotations = serializeAnnotations(typedefElement);
- b.codeRange = serializeCodeRange(typedefElement);
- return b;
- }
-
- /**
- * Serialize the given [typeParameter] into an [UnlinkedTypeParam].
- */
- UnlinkedTypeParamBuilder serializeTypeParam(
- TypeParameterElement typeParameter) {
- UnlinkedTypeParamBuilder b = new UnlinkedTypeParamBuilder();
- b.name = typeParameter.name;
- b.nameOffset = typeParameter.nameOffset;
- if (typeParameter.bound != null) {
- b.bound = serializeTypeRef(typeParameter.bound, typeParameter);
- }
- b.annotations = serializeAnnotations(typeParameter);
- b.codeRange = serializeCodeRange(typeParameter);
- return b;
- }
-
- /**
- * Serialize the given [type] into a [EntityRef]. If [slot] is provided,
- * it should be included in the [EntityRef].
- *
- * [context] is the element within which the [EntityRef] will be
- * interpreted; this is used to serialize type parameters.
- */
- EntityRefBuilder serializeTypeRef(DartType type, Element context,
- {int slot}) {
- if (slot != null) {
- assert(buildingLinkedReferences);
- }
- EntityRefBuilder b = new EntityRefBuilder(slot: slot);
- Element typeElement = type.element;
- if (type is TypeParameterType) {
- int typeParameterIndex = findTypeParameterIndex(type, context);
- if (typeParameterIndex != null) {
- b.paramReference = typeParameterIndex;
- } else {
- // Out-of-scope type parameters only occur in circumstances where they
- // are irrelevant (i.e. when a type parameter is unused). So we can
- // safely convert them to `dynamic`.
- b.reference = serializeReferenceForType(DynamicTypeImpl.instance);
- }
- } else if (type is FunctionType &&
- typeElement is FunctionElement &&
- typeElement.enclosingElement == null) {
- b.syntheticReturnType =
- serializeTypeRef(typeElement.returnType, typeElement);
- b.syntheticParams = typeElement.parameters
- .map((ParameterElement param) => serializeParam(param, context))
- .toList();
- } else {
- if (type is FunctionType &&
- typeElement.enclosingElement is ParameterElement) {
- // Code cannot refer to function types implicitly defined by parameters
- // directly, so if we get here, we must be serializing a linked
- // reference from type inference.
- assert(buildingLinkedReferences);
- ParameterElement parameterElement = typeElement.enclosingElement;
- while (true) {
- Element parent = parameterElement.enclosingElement;
- if (parent is ParameterElement) {
- // Function-typed parameter inside a function-typed parameter.
- b.implicitFunctionTypeIndices
- .insert(0, parent.parameters.indexOf(parameterElement));
- parameterElement = parent;
- continue;
- } else if (parent is FunctionTypedElement) {
- b.implicitFunctionTypeIndices
- .insert(0, parent.parameters.indexOf(parameterElement));
- // Function-typed parameter inside a top level function, method, or
- // typedef.
- b.reference = _getElementReferenceId(parent);
- break;
- } else {
- throw new StateError(
- 'Unexpected element enclosing parameter: ${parent.runtimeType}');
- }
- }
- } else {
- b.reference = serializeReferenceForType(type);
- }
- List<DartType> typeArguments = getTypeArguments(type);
- if (typeArguments != null) {
- b.typeArguments = typeArguments
- .map((typeArgument) => serializeTypeRef(typeArgument, context))
- .toList();
- }
- }
- return b;
- }
-
- /**
- * Create a new entry in the references table ([UnlinkedUnit.references]
- * and [LinkedUnit.references]) representing an entity having the given
- * [name] and [kind]. If [unit] is given, it is the index of the compilation
- * unit containing the entity being referred to. If [prefixReference] is
- * given, it indicates the entry in the references table for the prefix.
- */
- int serializeUnlinkedReference(String name, ReferenceKind kind,
- {int unit: 0, int prefixReference: 0}) {
- assert(unlinkedReferences.length == linkedReferences.length);
- int index = unlinkedReferences.length;
- unlinkedReferences.add(new UnlinkedReferenceBuilder(
- name: name, prefixReference: prefixReference));
- linkedReferences.add(new LinkedReferenceBuilder(kind: kind, unit: unit));
- return index;
- }
-
- /**
- * Return the index of the entry in the references table
- * ([UnlinkedLibrary.references] and [LinkedLibrary.references]) used for
- * unresolved references. A new entry is added to the table if necessary to
- * satisfy the request.
- */
- int serializeUnresolvedReference() {
- // TODO(paulberry): in order for relinking to work, we need to record the
- // name and prefix of the unresolved symbol. This is not (yet) encoded in
- // the element model. For the moment we use a name that can't possibly
- // ever exist.
- if (unresolvedReferenceIndex == null) {
- unresolvedReferenceIndex =
- serializeUnlinkedReference('*unresolved*', ReferenceKind.unresolved);
- }
- return unresolvedReferenceIndex;
- }
-
- /**
- * Serialize the given [variable], creating an [UnlinkedVariable].
- */
- UnlinkedVariableBuilder serializeVariable(VariableElement variable) {
- UnlinkedVariableBuilder b = new UnlinkedVariableBuilder();
- b.name = variable.name;
- b.nameOffset = variable.nameOffset;
- if (!variable.hasImplicitType) {
- b.type = serializeTypeRef(variable.type, variable);
- }
- b.isStatic = variable.isStatic && variable.enclosingElement is ClassElement;
- b.isFinal = variable.isFinal;
- b.isConst = variable.isConst;
- b.documentationComment = serializeDocumentation(variable);
- b.annotations = serializeAnnotations(variable);
- // TODO(scheglov) VariableMember.initializer is not implemented
- if (variable is! VariableMember && variable.initializer != null) {
- b.initializer = serializeExecutable(variable.initializer);
- }
- if (variable is ConstVariableElement) {
- ConstVariableElement constVariable = variable as ConstVariableElement;
- Expression initializer = constVariable.constantInitializer;
- if (initializer != null) {
- b.initializer?.bodyExpr =
- serializeConstExpr(variable, variable.initializer, initializer);
- }
- }
- if (variable is PropertyInducingElement) {
- if (b.isFinal || b.isConst) {
- b.propagatedTypeSlot =
- storeLinkedType(variable.propagatedType, variable);
- } else {
- // Variable is not propagable.
- assert(variable.propagatedType == null);
- }
- }
- if (variable.hasImplicitType &&
- (variable.initializer != null || !variable.isStatic)) {
- b.inferredTypeSlot = storeInferredType(variable.type, variable);
- }
- b.codeRange = serializeCodeRange(variable);
- if (variable is LocalVariableElement) {
- SourceRange visibleRange = variable.visibleRange;
- if (visibleRange != null) {
- b.visibleOffset = visibleRange.offset;
- b.visibleLength = visibleRange.length;
- }
- }
- return b;
- }
-
- /**
- * Create a new slot id and return it. If [hasCycle] is `true`, arrange for
- * the slot id to be included in [LinkedUnit.constCycles].
- */
- int storeConstCycle(bool hasCycle) {
- int slot = ++numSlots;
- if (hasCycle) {
- constCycles.add(slot);
- }
- return slot;
- }
-
- /**
- * Create a slot id for the given [type] (which is an inferred type). If
- * [type] is not `dynamic`, it is stored in [linkedTypes] so that once the
- * compilation unit has been fully visited, it will be serialized into
- * [LinkedUnit.types].
- *
- * [context] is the element within which the slot id will appear; this is
- * used to serialize type parameters.
- */
- int storeInferredType(DartType type, Element context) {
- return storeLinkedType(type.isDynamic ? null : type, context);
- }
-
- /**
- * Create a slot id for the given [type] (which may be either a propagated
- * type or an inferred type). If [type] is not `null`, it is stored in
- * [linkedTypes] so that once the compilation unit has been fully visited,
- * it will be serialized to [LinkedUnit.types].
- *
- * [context] is the element within which the slot id will appear; this is
- * used to serialize type parameters.
- */
- int storeLinkedType(DartType type, Element context) {
- int slot = ++numSlots;
- if (type != null) {
- deferredLinkedTypes
- .add(() => serializeTypeRef(type, context, slot: slot));
- }
- return slot;
- }
-
- int _getElementReferenceId(Element element) {
- return referenceMap.putIfAbsent(element, () {
- LibraryElement dependentLibrary = librarySerializer.libraryElement;
- int unit = 0;
- Element enclosingElement;
- if (element != null) {
- enclosingElement = element.enclosingElement;
- if (enclosingElement is CompilationUnitElement) {
- dependentLibrary = enclosingElement.library;
- unit = dependentLibrary.units.indexOf(enclosingElement);
- assert(unit != -1);
- }
- }
- ReferenceKind kind = _getReferenceKind(element);
- String name = element == null ? 'void' : element.name;
- int index;
- LinkedReferenceBuilder linkedReference;
- if (buildingLinkedReferences) {
- linkedReference =
- new LinkedReferenceBuilder(kind: kind, unit: unit, name: name);
- if (enclosingElement != null &&
- enclosingElement is! CompilationUnitElement) {
- linkedReference.containingReference =
- _getElementReferenceId(enclosingElement);
- if (enclosingElement is ClassElement) {
- // Nothing to do.
- } else if (enclosingElement is ExecutableElement) {
- if (element is FunctionElement) {
- assert(enclosingElement.functions.contains(element));
- linkedReference.localIndex =
- enclosingElement.functions.indexOf(element);
- } else if (element is LocalVariableElement) {
- assert(enclosingElement.localVariables.contains(element));
- linkedReference.localIndex =
- enclosingElement.localVariables.indexOf(element);
- } else {
- throw new StateError(
- 'Unexpected enclosed element type: ${element.runtimeType}');
- }
- } else if (enclosingElement is VariableElement) {
- assert(identical(enclosingElement.initializer, element));
- } else {
- throw new StateError(
- 'Unexpected enclosing element type: ${enclosingElement.runtimeType}');
- }
- }
- index = linkedReferences.length;
- linkedReferences.add(linkedReference);
- } else {
- assert(unlinkedReferences.length == linkedReferences.length);
- int prefixReference = 0;
- Element enclosing = element?.enclosingElement;
- if (enclosing == null || enclosing is CompilationUnitElement) {
- // Figure out a prefix that may be used to refer to the given element.
- // TODO(paulberry): to avoid subtle relinking inconsistencies we
- // should use the actual prefix from the AST (a given type may be
- // reachable via multiple prefixes), but sadly, this information is
- // not recorded in the element model.
- PrefixElement prefix = librarySerializer.prefixMap[element];
- if (prefix != null) {
- prefixReference = serializePrefix(prefix);
- }
- } else {
- prefixReference = _getElementReferenceId(enclosing);
- }
- index = serializeUnlinkedReference(name, kind,
- prefixReference: prefixReference, unit: unit);
- linkedReference = linkedReferences[index];
- }
- linkedReference.dependency =
- librarySerializer.serializeDependency(dependentLibrary);
- if (element is TypeParameterizedElement) {
- linkedReference.numTypeParameters += element.typeParameters.length;
- }
- return index;
- });
- }
-}
-
-/**
- * Instances of this class keep track of intermediate state during
- * serialization of a single constant [Expression].
- */
-class _ConstExprSerializer extends AbstractConstExprSerializer {
- final _CompilationUnitSerializer serializer;
- final Element context;
- final ExecutableElement executableContext;
-
- /**
- * If a constructor initializer expression is being serialized, the names of
- * the constructor parameters. Otherwise `null`.
- */
- final Set<String> constructorParameterNames;
-
- _ConstExprSerializer(this.serializer, this.context, this.executableContext,
- this.constructorParameterNames);
-
- @override
- bool isParameterName(String name) {
- return constructorParameterNames?.contains(name) ?? false;
- }
-
- @override
- void serializeAnnotation(Annotation annotation) {
- if (annotation.arguments == null) {
- assert(annotation.constructorName == null);
- serialize(annotation.name);
- } else {
- Identifier name = annotation.name;
- Element nameElement = name.staticElement;
- EntityRefBuilder constructor;
- if (nameElement is ConstructorElement && name is PrefixedIdentifier) {
- assert(annotation.constructorName == null);
- constructor = serializeConstructorRef(
- nameElement.returnType, name.prefix, null, name.identifier);
- } else if (nameElement is TypeDefiningElement) {
- constructor = serializeConstructorRef(nameElement.type, annotation.name,
- null, annotation.constructorName);
- } else if (nameElement == null) {
- // Unresolved annotation.
- if (name is PrefixedIdentifier && annotation.constructorName == null) {
- constructor =
- serializeConstructorRef(null, name.prefix, null, name.identifier);
- } else {
- constructor = serializeConstructorRef(
- null, annotation.name, null, annotation.constructorName);
- }
- } else {
- throw new StateError('Unexpected annotation nameElement type:'
- ' ${nameElement.runtimeType}');
- }
- serializeInstanceCreation(constructor, annotation.arguments);
- }
- }
-
- @override
- EntityRefBuilder serializeConstructorRef(DartType type, Identifier typeName,
- TypeArgumentList typeArguments, SimpleIdentifier name) {
- EntityRefBuilder typeRef = serializeType(type, typeName, typeArguments);
- if (name == null) {
- return typeRef;
- } else {
- LinkedReference typeLinkedRef =
- serializer.linkedReferences[typeRef.reference];
- int refId = serializer.serializeUnlinkedReference(
- name.name,
- name.staticElement != null
- ? ReferenceKind.constructor
- : ReferenceKind.unresolved,
- prefixReference: typeRef.reference,
- unit: typeLinkedRef.unit);
- return new EntityRefBuilder(
- reference: refId, typeArguments: typeRef.typeArguments);
- }
- }
-
- @override
- List<int> serializeFunctionExpression(FunctionExpression functionExpression) {
- if (executableContext == null) {
- return null;
- }
- ExecutableElement functionElement = functionExpression.element;
- // TOOD(paulberry): handle the situation where [functionExpression] is not
- // an immediate child of [executableContext].
- assert(functionElement.enclosingElement == executableContext);
- int popCount = 0;
- int localIndex = executableContext.functions.indexOf(functionElement);
- assert(localIndex != -1);
- return <int>[popCount, localIndex];
- }
-
- EntityRefBuilder serializeIdentifier(Identifier identifier,
- {int prefixReference: 0}) {
- if (identifier is SimpleIdentifier) {
- Element element = identifier.staticElement;
- if (element is TypeParameterElement) {
- int typeParameterIndex =
- serializer.findTypeParameterIndex(element.type, context);
- return new EntityRefBuilder(paramReference: typeParameterIndex);
- } else if (_isPrelinkResolvableElement(element)) {
- int ref = serializer._getElementReferenceId(element);
- return new EntityRefBuilder(reference: ref);
- } else {
- int ref = serializer.serializeUnlinkedReference(
- identifier.name, ReferenceKind.unresolved);
- return new EntityRefBuilder(reference: ref);
- }
- } else if (identifier is PrefixedIdentifier) {
- Element element = identifier.staticElement;
- if (_isPrelinkResolvableElement(element)) {
- int ref = serializer._getElementReferenceId(element);
- return new EntityRefBuilder(reference: ref);
- } else {
- int prefixRef = serializeIdentifier(identifier.prefix).reference;
- int ref = serializer.serializeUnlinkedReference(
- identifier.identifier.name, ReferenceKind.unresolved,
- prefixReference: prefixRef);
- return new EntityRefBuilder(reference: ref);
- }
- } else {
- throw new StateError(
- 'Unexpected identifier type: ${identifier.runtimeType}');
- }
- }
-
- @override
- EntityRefBuilder serializeIdentifierSequence(Expression expr) {
- if (expr is Identifier) {
- return serializeIdentifier(expr);
- }
- if (expr is PropertyAccess) {
- Element element = expr.propertyName.staticElement;
- if (_isPrelinkResolvableElement(element)) {
- int ref = serializer._getElementReferenceId(element);
- return new EntityRefBuilder(reference: ref);
- } else {
- int targetRef = serializeIdentifierSequence(expr.target).reference;
- int ref = serializer.serializeUnlinkedReference(
- expr.propertyName.name, ReferenceKind.unresolved,
- prefixReference: targetRef);
- return new EntityRefBuilder(reference: ref);
- }
- } else {
- throw new StateError('Unexpected node type: ${expr.runtimeType}');
- }
- }
-
- @override
- EntityRefBuilder serializeType(
- DartType type, Identifier name, TypeArgumentList arguments) {
- if (name != null) {
- if (type == null || type.isUndefined) {
- return serializeIdentifier(name);
- }
- }
- DartType typeOrDynamic = type ?? DynamicTypeImpl.instance;
- return serializer.serializeTypeRef(typeOrDynamic, context);
- }
-
- /**
- * Return `true` if the given [element] can be resolved at prelink step.
- */
- static bool _isPrelinkResolvableElement(Element element) {
- if (element == null) {
- return false;
- }
- if (element == DynamicTypeImpl.instance.element) {
- return true;
- }
- if (element is PrefixElement) {
- return true;
- }
- Element enclosingElement = element.enclosingElement;
- if (enclosingElement is CompilationUnitElement) {
- return true;
- }
- if (enclosingElement is ClassElement) {
- return element is ConstructorElement ||
- element is ClassMemberElement && element.isStatic ||
- element is PropertyAccessorElement && element.isStatic;
- }
- return false;
- }
-}
-
-/**
- * Instances of this class keep track of intermediate state during
- * serialization of a single library.
- */
-class _LibrarySerializer {
- /**
- * The library to be serialized.
- */
- final LibraryElement libraryElement;
-
- /**
- * The type provider. This is used to locate the library for `dart:core`.
- */
- final TypeProvider typeProvider;
-
- /**
- * Indicates whether the element model being serialized was analyzed using
- * strong mode.
- */
- final bool strongMode;
-
- /**
- * Map from [LibraryElement] to the index of the entry in the "dependency
- * table" that refers to it.
- */
- final Map<LibraryElement, int> dependencyMap = <LibraryElement, int>{};
-
- /**
- * The "dependency table". This is the list of objects which should be
- * written to [LinkedLibrary.dependencies].
- */
- final List<LinkedDependencyBuilder> dependencies =
- <LinkedDependencyBuilder>[];
-
- /**
- * The linked portion of the "imports table". This is the list of ints
- * which should be written to [LinkedLibrary.imports].
- */
- final List<int> linkedImports = <int>[];
-
- /**
- * The linked portion of the "exports table". This is the list of ints
- * which should be written to [LinkedLibrary.exports].
- */
- final List<int> linkedExports = <int>[];
-
- /**
- * Set of libraries which have been seen so far while visiting the transitive
- * closure of exports.
- */
- final Set<LibraryElement> librariesAddedToTransitiveExportClosure =
- new Set<LibraryElement>();
-
- /**
- * Map from imported element to the prefix which may be used to refer to that
- * element; elements for which no prefix is needed are absent from this map.
- */
- final Map<Element, PrefixElement> prefixMap = <Element, PrefixElement>{};
-
- /**
- * List of serializers for the compilation units constituting this library.
- */
- final List<_CompilationUnitSerializer> compilationUnitSerializers =
- <_CompilationUnitSerializer>[];
-
- _LibrarySerializer(this.libraryElement, this.typeProvider, this.strongMode) {
- dependencies.add(new LinkedDependencyBuilder());
- dependencyMap[libraryElement] = 0;
- }
-
- /**
- * Retrieve a list of the Sources for the compilation units in the library.
- */
- List<Source> get unitSources => compilationUnitSerializers
- .map((_CompilationUnitSerializer s) => s.unitSource)
- .toList();
-
- /**
- * Retrieve a list of the URIs for the compilation units in the library.
- */
- List<String> get unitUris => compilationUnitSerializers
- .map((_CompilationUnitSerializer s) => s.unitUri)
- .toList();
-
- /**
- * Retrieve a list of the [UnlinkedUnitBuilder]s for the compilation units in
- * the library.
- */
- List<UnlinkedUnitBuilder> get unlinkedUnits => compilationUnitSerializers
- .map((_CompilationUnitSerializer s) => s.unlinkedUnit)
- .toList();
-
- /**
- * Add [exportedLibrary] (and the transitive closure of all libraries it
- * exports) to the dependency table ([LinkedLibrary.dependencies]).
- */
- void addTransitiveExportClosure(LibraryElement exportedLibrary) {
- if (librariesAddedToTransitiveExportClosure.add(exportedLibrary)) {
- serializeDependency(exportedLibrary);
- for (LibraryElement transitiveExport
- in exportedLibrary.exportedLibraries) {
- addTransitiveExportClosure(transitiveExport);
- }
- }
- }
-
- /**
- * Fill in [prefixMap] using information from [libraryElement.imports].
- */
- void computePrefixMap() {
- for (ImportElement import in libraryElement.imports) {
- if (import.prefix == null) {
- continue;
- }
- import.importedLibrary.exportNamespace.definedNames
- .forEach((String name, Element e) {
- if (new NameFilter.forNamespaceCombinators(import.combinators)
- .accepts(name)) {
- prefixMap[e] = import.prefix;
- }
- });
- }
- }
-
- /**
- * Return the index of the entry in the dependency table
- * ([LinkedLibrary.dependencies]) for the given [dependentLibrary]. A new
- * entry is added to the table if necessary to satisfy the request.
- */
- int serializeDependency(LibraryElement dependentLibrary) {
- return dependencyMap.putIfAbsent(dependentLibrary, () {
- int index = dependencies.length;
- List<String> parts = dependentLibrary.parts
- .map((CompilationUnitElement e) => e.source.uri.toString())
- .toList();
- dependencies.add(new LinkedDependencyBuilder(
- uri: dependentLibrary.source.uri.toString(), parts: parts));
- return index;
- });
- }
-
- /**
- * Serialize the whole library element into a [LinkedLibrary]. Should be
- * called exactly once for each instance of [_LibrarySerializer].
- *
- * The unlinked compilation units are stored in [unlinkedUnits], and their
- * absolute URIs are stored in [unitUris].
- */
- LinkedLibraryBuilder serializeLibrary() {
- computePrefixMap();
- LinkedLibraryBuilder pb = new LinkedLibraryBuilder();
- for (ExportElement exportElement in libraryElement.exports) {
- addTransitiveExportClosure(exportElement.exportedLibrary);
- linkedExports.add(serializeDependency(exportElement.exportedLibrary));
- }
- for (ImportElement importElement in libraryElement.imports) {
- addTransitiveExportClosure(importElement.importedLibrary);
- linkedImports.add(serializeDependency(importElement.importedLibrary));
- }
- compilationUnitSerializers.add(new _CompilationUnitSerializer(
- this, libraryElement.definingCompilationUnit, 0));
- for (int i = 0; i < libraryElement.parts.length; i++) {
- compilationUnitSerializers.add(
- new _CompilationUnitSerializer(this, libraryElement.parts[i], i + 1));
- }
- for (_CompilationUnitSerializer compilationUnitSerializer
- in compilationUnitSerializers) {
- compilationUnitSerializer.addCompilationUnitElements();
- }
- pb.units = compilationUnitSerializers
- .map((_CompilationUnitSerializer s) => s.linkedUnit)
- .toList();
- pb.dependencies = dependencies;
- pb.numPrelinkedDependencies = dependencies.length;
- for (_CompilationUnitSerializer compilationUnitSerializer
- in compilationUnitSerializers) {
- compilationUnitSerializer.createLinkedInfo();
- }
- pb.importDependencies = linkedImports;
- pb.exportDependencies = linkedExports;
- List<String> exportedNames =
- libraryElement.exportNamespace.definedNames.keys.toList();
- exportedNames.sort();
- List<LinkedExportNameBuilder> exportNames = <LinkedExportNameBuilder>[];
- for (String name in exportedNames) {
- if (libraryElement.publicNamespace.definedNames.containsKey(name)) {
- continue;
- }
- Element element = libraryElement.exportNamespace.get(name);
- LibraryElement dependentLibrary = element.library;
- CompilationUnitElement unitElement =
- element.getAncestor((Element e) => e is CompilationUnitElement);
- int unit = dependentLibrary.units.indexOf(unitElement);
- assert(unit != -1);
- ReferenceKind kind = _getReferenceKind(element);
- exportNames.add(new LinkedExportNameBuilder(
- name: name,
- dependency: serializeDependency(dependentLibrary),
- unit: unit,
- kind: kind));
- }
- pb.exportNames = exportNames;
- return pb;
- }
-}
diff --git a/pkg/analyzer/lib/src/summary/summary_file_builder.dart b/pkg/analyzer/lib/src/summary/summary_file_builder.dart
index c9c835e..d27133f 100644
--- a/pkg/analyzer/lib/src/summary/summary_file_builder.dart
+++ b/pkg/analyzer/lib/src/summary/summary_file_builder.dart
@@ -5,128 +5,54 @@
library analyzer.src.summary.summary_file_builder;
import 'dart:collection';
-import 'dart:io' as io;
import 'package:analyzer/dart/ast/ast.dart';
-import 'package:analyzer/dart/element/element.dart';
+import 'package:analyzer/dart/ast/token.dart';
+import 'package:analyzer/error/listener.dart';
import 'package:analyzer/file_system/file_system.dart';
import 'package:analyzer/file_system/physical_file_system.dart';
+import 'package:analyzer/src/dart/scanner/reader.dart';
+import 'package:analyzer/src/dart/scanner/scanner.dart';
import 'package:analyzer/src/dart/sdk/sdk.dart';
import 'package:analyzer/src/generated/engine.dart';
+import 'package:analyzer/src/generated/parser.dart';
import 'package:analyzer/src/generated/sdk.dart';
import 'package:analyzer/src/generated/source.dart';
-import 'package:analyzer/src/summary/flat_buffers.dart' as fb;
-import 'package:analyzer/src/summary/index_unit.dart';
+import 'package:analyzer/src/summary/format.dart';
+import 'package:analyzer/src/summary/idl.dart';
+import 'package:analyzer/src/summary/link.dart';
+import 'package:analyzer/src/summary/summarize_ast.dart';
import 'package:analyzer/src/summary/summarize_elements.dart';
-import 'package:path/path.dart';
-
-const int FIELD_SPEC_INDEX = 1;
-const int FIELD_SPEC_SUM = 0;
-const int FIELD_STRONG_INDEX = 3;
-const int FIELD_STRONG_SUM = 2;
-
-class BuilderOutput {
- final List<int> sum;
- final List<int> index;
-
- BuilderOutput(this.sum, this.index);
-
- void writeMultiple(String outputDirectoryPath, String modeName) {
- // Write summary.
- {
- String outputPath = join(outputDirectoryPath, '$modeName.sum');
- io.File file = new io.File(outputPath);
- file.writeAsBytesSync(sum, mode: io.FileMode.WRITE_ONLY);
- }
- // Write index.
- {
- String outputPath = join(outputDirectoryPath, '$modeName.index');
- io.File file = new io.File(outputPath);
- file.writeAsBytesSync(index, mode: io.FileMode.WRITE_ONLY);
- }
- }
-}
-
-/**
- * Summary build configuration.
- */
-class SummaryBuildConfig {
- /**
- * Whether to use exclude informative data from created summaries.
- */
- final bool buildSummaryExcludeInformative;
-
- /**
- * Whether to output a summary in "fallback mode".
- */
- final bool buildSummaryFallback;
-
- /**
- * Whether to create summaries directly from ASTs, i.e. don't create a
- * full element model.
- */
- final bool buildSummaryOnlyAst;
-
- /**
- * Path to the dart SDK summary file.
- */
- final String dartSdkSummaryPath;
-
- /**
- * Whether to use strong static checking.
- */
- final bool strongMode;
-
- /**
- * List of summary input file paths.
- */
- final Iterable<String> summaryInputs;
-
- /**
- * Create a build configuration with the given set options.
- */
- SummaryBuildConfig(
- {this.strongMode: false,
- this.summaryInputs,
- this.dartSdkSummaryPath,
- this.buildSummaryExcludeInformative: false,
- this.buildSummaryFallback: false,
- this.buildSummaryOnlyAst: false});
-}
class SummaryBuilder {
- final AnalysisContext context;
final Iterable<Source> librarySources;
- final SummaryBuildConfig config;
+ final AnalysisContext context;
+ final bool strong;
/**
- * Create a summary builder for these [librarySources] and [context] using the
- * given [config].
+ * Create a summary builder for these [librarySources] and [context].
*/
- SummaryBuilder(this.librarySources, this.context, this.config);
+ SummaryBuilder(this.librarySources, this.context, this.strong);
/**
- * Create an SDK summary builder for the dart SDK at the given [sdkPath],
- * using this [config].
+ * Create an SDK summary builder for the dart SDK at the given [sdkPath].
*/
- factory SummaryBuilder.forSdk(String sdkPath, SummaryBuildConfig config) {
- bool strongMode = config.strongMode;
-
+ factory SummaryBuilder.forSdk(String sdkPath, bool strong) {
//
// Prepare SDK.
//
ResourceProvider resourceProvider = PhysicalResourceProvider.INSTANCE;
FolderBasedDartSdk sdk = new FolderBasedDartSdk(
- resourceProvider, resourceProvider.getFolder(sdkPath), strongMode);
+ resourceProvider, resourceProvider.getFolder(sdkPath), strong);
sdk.useSummary = false;
- sdk.analysisOptions = new AnalysisOptionsImpl()..strongMode = strongMode;
+ sdk.analysisOptions = new AnalysisOptionsImpl()..strongMode = strong;
//
// Prepare 'dart:' URIs to serialize.
//
Set<String> uriSet =
sdk.sdkLibraries.map((SdkLibrary library) => library.shortName).toSet();
- if (!strongMode) {
+ if (!strong) {
uriSet.add('dart:html/nativewrappers.dart');
}
uriSet.add('dart:html_common/html_common_dart2js.dart');
@@ -136,88 +62,89 @@
librarySources.add(sdk.mapDartUri(uri));
}
- return new SummaryBuilder(librarySources, sdk.context, config);
+ return new SummaryBuilder(librarySources, sdk.context, strong);
}
- BuilderOutput build() => new _Builder(context, librarySources).build();
-}
-
-/**
- * Intermediary summary output result.
- */
-class SummaryOutput {
- final BuilderOutput spec;
- final BuilderOutput strong;
- SummaryOutput(this.spec, this.strong);
-
/**
- * Write this summary output to the given [outputPath] and return the
- * created file.
+ * Build the linked bundle and return its bytes.
*/
- io.File write(String outputPath) {
- fb.Builder builder = new fb.Builder();
- fb.Offset specSumOffset = builder.writeListUint8(spec.sum);
- fb.Offset specIndexOffset = builder.writeListUint8(spec.index);
- fb.Offset strongSumOffset = builder.writeListUint8(strong.sum);
- fb.Offset strongIndexOffset = builder.writeListUint8(strong.index);
- builder.startTable();
- builder.addOffset(FIELD_SPEC_SUM, specSumOffset);
- builder.addOffset(FIELD_SPEC_INDEX, specIndexOffset);
- builder.addOffset(FIELD_STRONG_SUM, strongSumOffset);
- builder.addOffset(FIELD_STRONG_INDEX, strongIndexOffset);
- fb.Offset offset = builder.endTable();
- return new io.File(outputPath)
- ..writeAsBytesSync(builder.finish(offset), mode: io.FileMode.WRITE_ONLY);
- }
+ List<int> build() => new _Builder(context, librarySources, strong).build();
}
class _Builder {
- final Set<Source> processedSources = new Set<Source>();
-
- final PackageBundleAssembler bundleAssembler = new PackageBundleAssembler();
- final PackageIndexAssembler indexAssembler = new PackageIndexAssembler();
-
final AnalysisContext context;
final Iterable<Source> librarySources;
+ final bool strong;
- _Builder(this.context, this.librarySources);
+ final Set<String> libraryUris = new Set<String>();
+ final Map<String, UnlinkedUnit> unlinkedMap = <String, UnlinkedUnit>{};
+
+ final PackageBundleAssembler bundleAssembler = new PackageBundleAssembler();
+
+ _Builder(this.context, this.librarySources, this.strong);
/**
- * Build summary output.
+ * Build the linked bundle and return its bytes.
*/
- BuilderOutput build() {
- //
- // Serialize each source.
- //
- for (Source source in librarySources) {
- _serializeLibrary(source);
- }
- //
- // Assemble the output.
- //
- List<int> sumBytes = bundleAssembler.assemble().toBuffer();
- List<int> indexBytes = indexAssembler.assemble().toBuffer();
- return new BuilderOutput(sumBytes, indexBytes);
+ List<int> build() {
+ librarySources.forEach(_addLibrary);
+
+ Map<String, LinkedLibraryBuilder> map = link(libraryUris, (uri) {
+ throw new StateError('Unexpected call to GetDependencyCallback($uri).');
+ }, (uri) {
+ UnlinkedUnit unlinked = unlinkedMap[uri];
+ if (unlinked == null) {
+ throw new StateError('Unable to find unresolved unit $uri.');
+ }
+ return unlinked;
+ }, (String name) {
+ throw new StateError('Unexpected call to GetDeclaredVariable($name).');
+ }, strong);
+ map.forEach(bundleAssembler.addLinkedLibrary);
+
+ return bundleAssembler.assemble().toBuffer();
}
- /**
- * Serialize the library with the given [source] and all its direct or
- * indirect imports and exports.
- */
- void _serializeLibrary(Source source) {
- if (!processedSources.add(source)) {
+ void _addLibrary(Source source) {
+ String uriStr = source.uri.toString();
+ if (!libraryUris.add(uriStr)) {
return;
}
- LibraryElement element = context.computeLibraryElement(source);
- bundleAssembler.serializeLibraryElement(element);
- element.importedLibraries.forEach((e) => _serializeLibrary(e.source));
- element.exportedLibraries.forEach((e) => _serializeLibrary(e.source));
- // Index every unit of the library.
- for (CompilationUnitElement unitElement in element.units) {
- Source unitSource = unitElement.source;
- CompilationUnit unit =
- context.resolveCompilationUnit2(unitSource, source);
- indexAssembler.indexUnit(unit);
+ CompilationUnit unit = _addUnlinked(source);
+ for (Directive directive in unit.directives) {
+ if (directive is NamespaceDirective) {
+ String libUri = directive.uri.stringValue;
+ Source libSource = context.sourceFactory.resolveUri(source, libUri);
+ _addLibrary(libSource);
+ } else if (directive is PartDirective) {
+ String partUri = directive.uri.stringValue;
+ Source partSource = context.sourceFactory.resolveUri(source, partUri);
+ _addUnlinked(partSource);
+ }
}
}
+
+ CompilationUnit _addUnlinked(Source source) {
+ String uriStr = source.uri.toString();
+ CompilationUnit unit = _parse(source);
+ UnlinkedUnitBuilder unlinked = serializeAstUnlinked(unit);
+ unlinkedMap[uriStr] = unlinked;
+ bundleAssembler.addUnlinkedUnit(source, unlinked);
+ return unit;
+ }
+
+ CompilationUnit _parse(Source source) {
+ AnalysisErrorListener errorListener = AnalysisErrorListener.NULL_LISTENER;
+ String code = source.contents.data;
+ CharSequenceReader reader = new CharSequenceReader(code);
+ Scanner scanner = new Scanner(source, reader, errorListener);
+ scanner.scanGenericMethodComments = strong;
+ Token token = scanner.tokenize();
+ LineInfo lineInfo = new LineInfo(scanner.lineStarts);
+ Parser parser = new Parser(source, errorListener);
+ parser.parseGenericMethodComments = strong;
+ CompilationUnit unit = parser.parseCompilationUnit(token);
+ unit.lineInfo = lineInfo;
+ return unit;
+ }
}
diff --git a/pkg/analyzer/lib/src/task/dart.dart b/pkg/analyzer/lib/src/task/dart.dart
index 94cd824..3401fbe 100644
--- a/pkg/analyzer/lib/src/task/dart.dart
+++ b/pkg/analyzer/lib/src/task/dart.dart
@@ -11,19 +11,23 @@
import 'package:analyzer/dart/ast/visitor.dart';
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/type.dart';
+import 'package:analyzer/error/error.dart';
+import 'package:analyzer/error/listener.dart';
import 'package:analyzer/exception/exception.dart';
import 'package:analyzer/src/context/cache.dart';
import 'package:analyzer/src/context/context.dart';
+import 'package:analyzer/src/dart/ast/ast.dart'
+ show NamespaceDirectiveImpl, UriBasedDirectiveImpl;
import 'package:analyzer/src/dart/ast/utilities.dart';
import 'package:analyzer/src/dart/element/builder.dart';
import 'package:analyzer/src/dart/element/element.dart';
import 'package:analyzer/src/dart/resolver/inheritance_manager.dart';
import 'package:analyzer/src/dart/scanner/reader.dart';
import 'package:analyzer/src/dart/scanner/scanner.dart';
+import 'package:analyzer/src/error/codes.dart';
import 'package:analyzer/src/error/pending_error.dart';
import 'package:analyzer/src/generated/constant.dart';
import 'package:analyzer/src/generated/engine.dart';
-import 'package:analyzer/src/generated/error.dart';
import 'package:analyzer/src/generated/error_verifier.dart';
import 'package:analyzer/src/generated/incremental_resolver.dart';
import 'package:analyzer/src/generated/parser.dart';
@@ -1521,7 +1525,7 @@
directivesToResolve.add(directive);
} else if (directive is PartDirective) {
StringLiteral partUri = directive.uri;
- Source partSource = directive.source;
+ Source partSource = directive.uriSource;
hasPartDirective = true;
CompilationUnit partUnit = partUnitMap[partSource];
if (partUnit != null) {
@@ -3981,6 +3985,16 @@
]);
/**
+ * The source that is being parsed.
+ */
+ Source _source;
+
+ /**
+ * The [ErrorReporter] to report errors to.
+ */
+ ErrorReporter _errorReporter;
+
+ /**
* Initialize a newly created task to parse the content of the Dart file
* associated with the given [target] in the given [context].
*/
@@ -3992,17 +4006,20 @@
@override
void internalPerform() {
- Source source = getRequiredSource();
+ _source = getRequiredSource();
LineInfo lineInfo = getRequiredInput(LINE_INFO_INPUT_NAME);
int modificationTime = getRequiredInput(MODIFICATION_TIME_INPUT_NAME);
Token tokenStream = getRequiredInput(TOKEN_STREAM_INPUT_NAME);
RecordingErrorListener errorListener = new RecordingErrorListener();
- Parser parser = new Parser(source, errorListener);
+ _errorReporter = new ErrorReporter(errorListener, _source);
+
+ Parser parser = new Parser(_source, errorListener);
AnalysisOptions options = context.analysisOptions;
parser.enableAssertInitializer = options.enableAssertInitializer;
parser.parseAsync = options.enableAsync;
- parser.parseFunctionBodies = options.analyzeFunctionBodiesPredicate(source);
+ parser.parseFunctionBodies =
+ options.analyzeFunctionBodiesPredicate(_source);
parser.parseGenericMethods = options.enableGenericMethods;
parser.parseGenericMethodComments = options.strongMode;
CompilationUnit unit = parser.parseCompilationUnit(tokenStream);
@@ -4022,8 +4039,7 @@
} else {
hasNonPartOfDirective = true;
if (directive is UriBasedDirective) {
- Source referencedSource =
- resolveDirective(context, source, directive, errorListener);
+ Source referencedSource = _resolveDirective(directive);
if (referencedSource != null) {
if (directive is ExportDirective) {
exportedSourceSet.add(referencedSource);
@@ -4068,25 +4084,38 @@
//
// Compute referenced names.
//
- ReferencedNames referencedNames = new ReferencedNames(source);
+ ReferencedNames referencedNames = new ReferencedNames(_source);
new ReferencedNamesBuilder(referencedNames).build(unit);
//
- // Record outputs.
+ // Compute source lists.
//
List<Source> explicitlyImportedSources =
explicitlyImportedSourceSet.toList();
List<Source> exportedSources = exportedSourceSet.toList();
List<Source> importedSources = importedSourceSet.toList();
List<Source> includedSources = includedSourceSet.toList();
- List<AnalysisError> parseErrors = getUniqueErrors(errorListener.errors);
- List<Source> unitSources = <Source>[source]..addAll(includedSourceSet);
- List<Source> referencedSources = (new Set<Source>()
- ..addAll(importedSources)
- ..addAll(exportedSources)
- ..addAll(unitSources))
- .toList();
+ List<Source> unitSources = <Source>[_source]..addAll(includedSourceSet);
List<LibrarySpecificUnit> librarySpecificUnits =
- unitSources.map((s) => new LibrarySpecificUnit(source, s)).toList();
+ unitSources.map((s) => new LibrarySpecificUnit(_source, s)).toList();
+ //
+ // Compute referenced sources.
+ //
+ Set<Source> referencedSources = new Set<Source>();
+ referencedSources.add(coreLibrarySource);
+ referencedSources.addAll(unitSources);
+ for (Directive directive in unit.directives) {
+ if (directive is NamespaceDirective) {
+ referencedSources.add(directive.uriSource);
+ for (Configuration configuration in directive.configurations) {
+ referencedSources.add(configuration.uriSource);
+ }
+ }
+ }
+ referencedSources.removeWhere((source) => source == null);
+ //
+ // Record outputs.
+ //
+ List<AnalysisError> parseErrors = getUniqueErrors(errorListener.errors);
outputs[EXPLICITLY_IMPORTED_LIBRARIES] = explicitlyImportedSources;
outputs[EXPORTED_LIBRARIES] = exportedSources;
outputs[IMPORTED_LIBRARIES] = importedSources;
@@ -4095,12 +4124,86 @@
outputs[PARSE_ERRORS] = parseErrors;
outputs[PARSED_UNIT] = unit;
outputs[REFERENCED_NAMES] = referencedNames;
- outputs[REFERENCED_SOURCES] = referencedSources;
+ outputs[REFERENCED_SOURCES] = referencedSources.toList();
outputs[SOURCE_KIND] = sourceKind;
outputs[UNITS] = unitSources;
}
/**
+ * Return the result of resolving the URI of the given URI-based [directive]
+ * against the URI of the given library, or `null` if the URI is not valid.
+ */
+ Source _resolveDirective(UriBasedDirective directive) {
+ bool isImport = directive is ImportDirective;
+
+ // Resolve the default URI.
+ Source defaultSource;
+ {
+ StringLiteral uriLiteral = directive.uri;
+ String uriContent = uriLiteral.stringValue;
+ if (uriContent != null) {
+ uriContent = uriContent.trim();
+ directive.uriContent = uriContent;
+ }
+ defaultSource = _resolveUri(isImport, uriLiteral, uriContent);
+ directive.uriSource = defaultSource;
+ }
+
+ // Resolve all configurations and try to choose one.
+ if (directive is NamespaceDirectiveImpl) {
+ String configuredUriContent;
+ Source configuredSource;
+ for (Configuration configuration in directive.configurations) {
+ String uriContent = configuration.uri.stringValue;
+ Source source = _resolveUri(isImport, configuration.uri, uriContent);
+ configuration.uriSource = source;
+ if (configuredSource == null) {
+ String variableName =
+ configuration.name.components.map((i) => i.name).join('.');
+ String variableValue = context.declaredVariables.get(variableName);
+ if (configuration.value != null &&
+ variableValue == configuration.value.stringValue ||
+ variableValue == 'true') {
+ configuredUriContent = configuration.uri.stringValue;
+ configuredSource = source;
+ }
+ }
+ }
+ String selectedContentUri = configuredUriContent ?? directive.uriContent;
+ Source selectedSource = configuredSource ?? defaultSource;
+ directive.selectedUriContent = selectedContentUri;
+ directive.selectedSource = selectedSource;
+ return selectedSource;
+ }
+ return defaultSource;
+ }
+
+ /**
+ * Return the result of resolve the given [uriContent], reporting errors
+ * against the [uriLiteral].
+ */
+ Source _resolveUri(
+ bool isImport, StringLiteral uriLiteral, String uriContent) {
+ UriValidationCode code =
+ UriBasedDirectiveImpl.validateUri(isImport, uriLiteral, uriContent);
+ if (code == null) {
+ String encodedUriContent = Uri.encodeFull(uriContent);
+ return context.sourceFactory.resolveUri(_source, encodedUriContent);
+ } else if (code == UriValidationCode.URI_WITH_DART_EXT_SCHEME) {
+ return null;
+ } else if (code == UriValidationCode.URI_WITH_INTERPOLATION) {
+ _errorReporter.reportErrorForNode(
+ CompileTimeErrorCode.URI_WITH_INTERPOLATION, uriLiteral);
+ return null;
+ } else if (code == UriValidationCode.INVALID_URI) {
+ _errorReporter.reportErrorForNode(
+ CompileTimeErrorCode.INVALID_URI, uriLiteral, [uriContent]);
+ return null;
+ }
+ throw new AnalysisException('Failed to handle validation code: $code');
+ }
+
+ /**
* Return a map from the names of the inputs of this kind of task to the task
* input descriptors describing those inputs for a task with the given
* [target].
@@ -4121,45 +4224,6 @@
AnalysisContext context, AnalysisTarget target) {
return new ParseDartTask(context, target);
}
-
- /**
- * Return the result of resolving the URI of the given URI-based [directive]
- * against the URI of the given library, or `null` if the URI is not valid.
- *
- * Resolution is to be performed in the given [context]. Errors should be
- * reported to the [errorListener].
- */
- static Source resolveDirective(AnalysisContext context, Source librarySource,
- UriBasedDirective directive, AnalysisErrorListener errorListener) {
- StringLiteral uriLiteral = directive.uri;
- String uriContent = uriLiteral.stringValue;
- if (uriContent != null) {
- uriContent = uriContent.trim();
- directive.uriContent = uriContent;
- }
- UriValidationCode code = directive.validate();
- if (code == null) {
- String encodedUriContent = Uri.encodeFull(uriContent);
- Source source =
- context.sourceFactory.resolveUri(librarySource, encodedUriContent);
- directive.source = source;
- return source;
- }
- if (code == UriValidationCode.URI_WITH_DART_EXT_SCHEME) {
- return null;
- }
- if (code == UriValidationCode.URI_WITH_INTERPOLATION) {
- errorListener.onError(new AnalysisError(librarySource, uriLiteral.offset,
- uriLiteral.length, CompileTimeErrorCode.URI_WITH_INTERPOLATION));
- return null;
- }
- if (code == UriValidationCode.INVALID_URI) {
- errorListener.onError(new AnalysisError(librarySource, uriLiteral.offset,
- uriLiteral.length, CompileTimeErrorCode.INVALID_URI, [uriContent]));
- return null;
- }
- throw new AnalysisException('Failed to handle validation code: $code');
- }
}
/**
@@ -6172,7 +6236,33 @@
* report an error if it does not.
*/
void validateReferencedSource(UriBasedDirective directive) {
- Source source = directive.source;
+ if (directive is NamespaceDirective) {
+ for (Configuration configuration in directive.configurations) {
+ Source source = configuration.uriSource;
+ StringLiteral uriLiteral = configuration.uri;
+ String uriContent = uriLiteral?.stringValue?.trim();
+ if (source != null) {
+ int modificationTime = sourceTimeMap[source] ?? -1;
+ if (modificationTime >= 0) {
+ continue;
+ }
+ } else {
+ // Don't report errors already reported by ParseDartTask.resolveDirective
+ if (UriBasedDirectiveImpl.validateUri(
+ directive is ImportDirective, uriLiteral, uriContent) !=
+ null) {
+ continue;
+ }
+ }
+ CompileTimeErrorCode errorCode =
+ CompileTimeErrorCode.URI_DOES_NOT_EXIST;
+ if (_isGenerated(source)) {
+ errorCode = CompileTimeErrorCode.URI_HAS_NOT_BEEN_GENERATED;
+ }
+ errorReporter.reportErrorForNode(errorCode, uriLiteral, [uriContent]);
+ }
+ }
+ Source source = directive.uriSource;
if (source != null) {
int modificationTime = sourceTimeMap[source] ?? -1;
if (modificationTime >= 0) {
diff --git a/pkg/analyzer/lib/src/task/dart_work_manager.dart b/pkg/analyzer/lib/src/task/dart_work_manager.dart
index f3dd0b6..aecdba4 100644
--- a/pkg/analyzer/lib/src/task/dart_work_manager.dart
+++ b/pkg/analyzer/lib/src/task/dart_work_manager.dart
@@ -6,10 +6,10 @@
import 'dart:collection';
+import 'package:analyzer/error/error.dart';
import 'package:analyzer/src/context/cache.dart';
import 'package:analyzer/src/generated/engine.dart'
show AnalysisEngine, AnalysisErrorInfo, CacheState, InternalAnalysisContext;
-import 'package:analyzer/src/generated/error.dart';
import 'package:analyzer/src/generated/source.dart';
import 'package:analyzer/src/generated/utilities_collection.dart';
import 'package:analyzer/src/task/dart.dart';
diff --git a/pkg/analyzer/lib/src/task/html.dart b/pkg/analyzer/lib/src/task/html.dart
index ae45620..81587b2 100644
--- a/pkg/analyzer/lib/src/task/html.dart
+++ b/pkg/analyzer/lib/src/task/html.dart
@@ -6,11 +6,11 @@
import 'dart:collection';
+import 'package:analyzer/error/error.dart';
import 'package:analyzer/exception/exception.dart';
import 'package:analyzer/src/context/cache.dart';
import 'package:analyzer/src/dart/scanner/scanner.dart';
import 'package:analyzer/src/generated/engine.dart';
-import 'package:analyzer/src/generated/error.dart';
import 'package:analyzer/src/generated/java_engine.dart';
import 'package:analyzer/src/generated/source.dart';
import 'package:analyzer/src/plugin/engine_plugin.dart';
diff --git a/pkg/analyzer/lib/src/task/html_work_manager.dart b/pkg/analyzer/lib/src/task/html_work_manager.dart
index 07dfb29..911ef16 100644
--- a/pkg/analyzer/lib/src/task/html_work_manager.dart
+++ b/pkg/analyzer/lib/src/task/html_work_manager.dart
@@ -6,10 +6,10 @@
import 'dart:collection';
+import 'package:analyzer/error/error.dart';
import 'package:analyzer/src/context/cache.dart';
import 'package:analyzer/src/generated/engine.dart'
show AnalysisEngine, AnalysisErrorInfo, CacheState, InternalAnalysisContext;
-import 'package:analyzer/src/generated/error.dart';
import 'package:analyzer/src/generated/source.dart';
import 'package:analyzer/src/generated/utilities_collection.dart';
import 'package:analyzer/src/task/html.dart';
diff --git a/pkg/analyzer/lib/src/task/incremental_element_builder.dart b/pkg/analyzer/lib/src/task/incremental_element_builder.dart
index bd317cf..6ae19ff 100644
--- a/pkg/analyzer/lib/src/task/incremental_element_builder.dart
+++ b/pkg/analyzer/lib/src/task/incremental_element_builder.dart
@@ -244,6 +244,7 @@
}
}
}
+
void processFieldDeclaration(FieldDeclaration node, bool isNew) {
for (VariableDeclaration field in node.fields.variables) {
PropertyInducingElement element = field.element;
@@ -269,6 +270,7 @@
}
}
}
+
void processMethodDeclaration(MethodDeclaration node, bool isNew) {
Element element = node.element;
if (element is MethodElement) {
@@ -287,6 +289,7 @@
}
}
}
+
// Replace new nodes with the identical old nodes.
bool newHasConstructor = false;
for (ClassMember newNode in newClass.members) {
@@ -409,7 +412,11 @@
// URI's must be resolved to the same sources.
if (newDirective is UriBasedDirective &&
oldDirective is UriBasedDirective) {
- if (oldDirective.source != newDirective.source) {
+ Source source(UriBasedDirective directive) =>
+ directive is NamespaceDirective
+ ? directive.selectedSource
+ : directive.uriSource;
+ if (source(oldDirective) != source(newDirective)) {
continue;
}
}
@@ -536,6 +543,7 @@
}
}
}
+
if (node is FieldDeclaration) {
addPropertyAccessors(node.fields);
} else if (node is TopLevelVariableDeclaration) {
diff --git a/pkg/analyzer/lib/src/task/options.dart b/pkg/analyzer/lib/src/task/options.dart
index 58d76ac..5ed99dc 100644
--- a/pkg/analyzer/lib/src/task/options.dart
+++ b/pkg/analyzer/lib/src/task/options.dart
@@ -29,6 +29,14 @@
new ListResultDescriptor<AnalysisError>(
'ANALYSIS_OPTIONS_ERRORS', AnalysisError.NO_ERRORS);
+/**
+ * The descriptor used to associate error processors with analysis contexts in
+ * configuration data.
+ */
+final ListResultDescriptor<ErrorProcessor> CONFIGURED_ERROR_PROCESSORS =
+ new ListResultDescriptor<ErrorProcessor>(
+ 'configured.errors', const <ErrorProcessor>[]);
+
final _OptionsProcessor _processor = new _OptionsProcessor();
void applyToAnalysisOptions(
diff --git a/pkg/analyzer/lib/src/task/options_work_manager.dart b/pkg/analyzer/lib/src/task/options_work_manager.dart
index 7956a8a..d78a21c 100644
--- a/pkg/analyzer/lib/src/task/options_work_manager.dart
+++ b/pkg/analyzer/lib/src/task/options_work_manager.dart
@@ -6,10 +6,10 @@
import 'dart:collection';
+import 'package:analyzer/error/error.dart';
import 'package:analyzer/src/context/cache.dart';
import 'package:analyzer/src/generated/engine.dart'
show AnalysisEngine, AnalysisErrorInfo, CacheState, InternalAnalysisContext;
-import 'package:analyzer/src/generated/error.dart';
import 'package:analyzer/src/generated/source.dart';
import 'package:analyzer/src/task/options.dart';
import 'package:analyzer/task/model.dart';
diff --git a/pkg/analyzer/lib/src/task/strong/checker.dart b/pkg/analyzer/lib/src/task/strong/checker.dart
index f47c957..1183ce3 100644
--- a/pkg/analyzer/lib/src/task/strong/checker.dart
+++ b/pkg/analyzer/lib/src/task/strong/checker.dart
@@ -13,22 +13,15 @@
import 'package:analyzer/dart/ast/visitor.dart';
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/type.dart';
+import 'package:analyzer/src/dart/element/element.dart';
import 'package:analyzer/src/dart/element/type.dart';
+import 'package:analyzer/src/error/codes.dart' show StrongModeCode;
import 'package:analyzer/src/generated/engine.dart' show AnalysisOptionsImpl;
-import 'package:analyzer/src/generated/error.dart' show StrongModeCode;
import 'package:analyzer/src/generated/resolver.dart' show TypeProvider;
import 'package:analyzer/src/generated/type_system.dart';
import 'ast_properties.dart';
-bool isKnownFunction(Expression expression) {
- var element = _getKnownElement(expression);
- // First class functions and static methods, where we know the original
- // declaration, will have an exact type, so we know a downcast will fail.
- return element is FunctionElement ||
- element is MethodElement && element.isStatic;
-}
-
/// Given an [expression] and a corresponding [typeSystem] and [typeProvider],
/// gets the known static type of the expression.
///
@@ -50,9 +43,20 @@
return type;
}
-bool _hasStrictArrow(Expression expression) {
+bool isKnownFunction(Expression expression) {
var element = _getKnownElement(expression);
- return element is FunctionElement || element is MethodElement;
+ // First class functions and static methods, where we know the original
+ // declaration, will have an exact type, so we know a downcast will fail.
+ return element is FunctionElement ||
+ element is MethodElement && element.isStatic;
+}
+
+DartType _elementType(Element e) {
+ if (e == null) {
+ // Malformed code - just return dynamic.
+ return DynamicTypeImpl.instance;
+ }
+ return (e as dynamic).type;
}
Element _getKnownElement(Expression expression) {
@@ -69,20 +73,12 @@
return null;
}
-DartType _elementType(Element e) {
- if (e == null) {
- // Malformed code - just return dynamic.
- return DynamicTypeImpl.instance;
- }
- return (e as dynamic).type;
-}
-
-// Return the field on type corresponding to member, or null if none
-// exists or the "field" is actually a getter/setter.
-PropertyInducingElement _getMemberField(
+/// Return the field on type corresponding to member, or null if none
+/// exists or the "field" is actually a getter/setter.
+FieldElement _getMemberField(
InterfaceType type, PropertyAccessorElement member) {
String memberName = member.name;
- PropertyInducingElement field;
+ FieldElement field;
if (member.isGetter) {
// The subclass member is an explicit getter or a field
// - lookup the getter on the superclass.
@@ -109,6 +105,11 @@
FunctionType _getMemberType(InterfaceType type, ExecutableElement member) =>
_memberTypeGetter(member)(type);
+bool _hasStrictArrow(Expression expression) {
+ var element = _getKnownElement(expression);
+ return element is FunctionElement || element is MethodElement;
+}
+
_MemberTypeGetter _memberTypeGetter(ExecutableElement member) {
String memberName = member.name;
final isGetter = member is PropertyAccessorElement && member.isGetter;
@@ -640,6 +641,20 @@
}
@override
+ Object visitVariableDeclaration(VariableDeclaration node) {
+ if (!node.isConst &&
+ !node.isFinal &&
+ node.initializer == null &&
+ rules.isNonNullableType(node?.element?.type)) {
+ _recordMessage(
+ node,
+ StaticTypeWarningCode.NON_NULLABLE_FIELD_NOT_INITIALIZED,
+ [node.name, node?.element?.type]);
+ }
+ return super.visitVariableDeclaration(node);
+ }
+
+ @override
void visitVariableDeclarationList(VariableDeclarationList node) {
TypeName type = node.type;
if (type == null) {
@@ -658,20 +673,6 @@
}
@override
- Object visitVariableDeclaration(VariableDeclaration node) {
- if (!node.isConst &&
- !node.isFinal &&
- node.initializer == null &&
- rules.isNonNullableType(node?.element?.type)) {
- _recordMessage(
- node,
- StaticTypeWarningCode.NON_NULLABLE_FIELD_NOT_INITIALIZED,
- [node.name, node?.element?.type]);
- }
- return super.visitVariableDeclaration(node);
- }
-
- @override
void visitWhileStatement(WhileStatement node) {
checkBoolean(node.condition);
node.visitChildren(this);
@@ -877,10 +878,11 @@
/// Checks if the assignment is valid with respect to non-nullable types.
/// Returns `false` if a nullable expression is assigned to a variable of
/// non-nullable type and `true` otherwise.
- bool _checkNonNullAssignment(Expression expression, DartType to, DartType from) {
+ bool _checkNonNullAssignment(
+ Expression expression, DartType to, DartType from) {
if (rules.isNonNullableType(to) && rules.isNullableType(from)) {
- _recordMessage(expression, StaticTypeWarningCode.INVALID_ASSIGNMENT,
- [from, to]);
+ _recordMessage(
+ expression, StaticTypeWarningCode.INVALID_ASSIGNMENT, [from, to]);
return false;
}
return true;
@@ -923,6 +925,9 @@
}
}
+ DartType _getDefiniteType(Expression expr) =>
+ getDefiniteType(expr, rules, typeProvider);
+
/// Gets the expected return type of the given function [body], either from
/// a normal return/yield, or from a yield*.
DartType _getExpectedReturnType(FunctionBody body, {bool yieldStar: false}) {
@@ -977,9 +982,6 @@
}
}
- DartType _getDefiniteType(Expression expr) =>
- getDefiniteType(expr, rules, typeProvider);
-
/// Given an expression, return its type assuming it is
/// in the caller position of a call (that is, accounting
/// for the possibility of a call method). Returns null
@@ -1121,13 +1123,11 @@
/// applications.
class _OverrideChecker {
final StrongTypeSystemImpl rules;
- final TypeProvider _typeProvider;
final CodeChecker _checker;
_OverrideChecker(CodeChecker checker)
: _checker = checker,
- rules = checker.rules,
- _typeProvider = checker.typeProvider;
+ rules = checker.rules;
void check(ClassDeclaration node) {
if (node.element.type.isObject) return;
@@ -1389,9 +1389,10 @@
if (isSubclass && element is PropertyAccessorElement) {
// Disallow any overriding if the base class defines this member
- // as a field. We effectively treat fields as final / non-virtual.
- PropertyInducingElement field = _getMemberField(type, element);
- if (field != null) {
+ // as a field. We effectively treat fields as final / non-virtual,
+ // unless they are explicitly marked as @virtual
+ var field = _getMemberField(type, element);
+ if (field != null && !field.isVirtual) {
_checker._recordMessage(
errorLocation, StrongModeCode.INVALID_FIELD_OVERRIDE, [
element.enclosingElement.name,
@@ -1409,24 +1410,8 @@
concreteSubType = rules.instantiateToBounds(concreteSubType);
}
}
- concreteSubType =
- rules.typeToConcreteType(_typeProvider, concreteSubType);
- concreteBaseType =
- rules.typeToConcreteType(_typeProvider, concreteBaseType);
- if (!rules.isSubtypeOf(concreteSubType, concreteBaseType)) {
- // See whether non-subtype cases fit one of our common patterns:
- //
- // Common pattern 1: Inferable return type (on getters and methods)
- // class A {
- // int get foo => ...;
- // String toString() { ... }
- // }
- // class B extends A {
- // get foo => e; // no type specified.
- // toString() { ... } // no return type specified.
- // }
-
+ if (!rules.isOverrideSubtypeOf(concreteSubType, concreteBaseType)) {
ErrorCode errorCode;
if (errorLocation is ExtendsClause) {
errorCode = StrongModeCode.INVALID_METHOD_OVERRIDE_FROM_BASE;
@@ -1444,7 +1429,12 @@
baseType
]);
}
- return true;
+
+ // If we have any covariant parameters and we're comparing against a
+ // superclass, we check all superclasses instead of stopping the search.
+ bool hasCovariant = element.parameters.any((p) => p.isCovariant);
+ bool keepSearching = hasCovariant && isSubclass;
+ return !keepSearching;
}
/// Check overrides between a class and its superclasses and mixins. For
diff --git a/pkg/analyzer/lib/src/task/strong_mode.dart b/pkg/analyzer/lib/src/task/strong_mode.dart
index ea4e0b3..37c91cf 100644
--- a/pkg/analyzer/lib/src/task/strong_mode.dart
+++ b/pkg/analyzer/lib/src/task/strong_mode.dart
@@ -121,8 +121,9 @@
DartType parameterType = null;
int length = overriddenTypes.length;
for (int i = 0; i < length; i++) {
- DartType type = _getTypeOfCorrespondingParameter(
+ ParameterElement matchingParam = _getCorrespondingParameter(
parameter, index, overriddenTypes[i].parameters);
+ var type = matchingParam?.type ?? typeProvider.dynamicType;
if (parameterType == null) {
parameterType = type;
} else if (parameterType != type) {
@@ -156,45 +157,38 @@
}
/**
- * Given a method, return the type of the parameter in the method that
- * corresponds to the given [parameter]. If the parameter is positional, then
+ * Given a method, return the parameter in the method that corresponds to the
+ * given [parameter]. If the parameter is positional, then
* it appears at the given [index] in its enclosing element's list of
* parameters.
*/
- DartType _getTypeOfCorrespondingParameter(ParameterElement parameter,
+ ParameterElement _getCorrespondingParameter(ParameterElement parameter,
int index, List<ParameterElement> methodParameters) {
//
// Find the corresponding parameter.
//
- ParameterElement matchingParameter = null;
if (parameter.parameterKind == ParameterKind.NAMED) {
//
// If we're looking for a named parameter, only a named parameter with
// the same name will be matched.
//
- matchingParameter = methodParameters.lastWhere(
+ return methodParameters.lastWhere(
(ParameterElement methodParameter) =>
methodParameter.parameterKind == ParameterKind.NAMED &&
methodParameter.name == parameter.name,
orElse: () => null);
- } else {
- //
- // If we're looking for a positional parameter we ignore the difference
- // between required and optional parameters.
- //
- if (index < methodParameters.length) {
- matchingParameter = methodParameters[index];
- if (matchingParameter.parameterKind == ParameterKind.NAMED) {
- matchingParameter = null;
- }
- }
}
//
- // Then return the type of the parameter.
+ // If we're looking for a positional parameter we ignore the difference
+ // between required and optional parameters.
//
- return matchingParameter == null
- ? typeProvider.dynamicType
- : matchingParameter.type;
+ if (index < methodParameters.length) {
+ var matchingParameter = methodParameters[index];
+ if (matchingParameter.parameterKind != ParameterKind.NAMED) {
+ return matchingParameter;
+ }
+ }
+ return null;
}
/**
@@ -311,10 +305,14 @@
int length = parameters.length;
for (int i = 0; i < length; ++i) {
ParameterElement parameter = parameters[i];
- if (parameter is ParameterElementImpl && parameter.hasImplicitType) {
- parameter.type = _computeParameterType(parameter, i, overriddenTypes);
- if (element is PropertyAccessorElement) {
- _updateSyntheticVariableType(element);
+ if (parameter is ParameterElementImpl) {
+ _inferParameterCovariance(parameter, i, overriddenTypes);
+
+ if (parameter.hasImplicitType) {
+ parameter.type = _computeParameterType(parameter, i, overriddenTypes);
+ if (element is PropertyAccessorElement) {
+ _updateSyntheticVariableType(element);
+ }
}
}
}
@@ -325,9 +323,19 @@
* which no type was provided, infer the type of the field.
*/
void _inferField(FieldElement fieldElement) {
- if (!fieldElement.isSynthetic &&
- !fieldElement.isStatic &&
- fieldElement.hasImplicitType) {
+ if (fieldElement.isSynthetic || fieldElement.isStatic) {
+ return;
+ }
+ List<ExecutableElement> overriddenSetters =
+ inheritanceManager.lookupOverrides(
+ fieldElement.enclosingElement, fieldElement.name + '=');
+ var setter = fieldElement.setter;
+ if (setter != null && overriddenSetters.isNotEmpty) {
+ _inferParameterCovariance(
+ setter.parameters[0], 0, overriddenSetters.map((s) => s.type));
+ }
+
+ if (fieldElement.hasImplicitType) {
//
// First look for overridden getters with the same name as the field.
//
@@ -337,9 +345,7 @@
if (overriddenGetters.isNotEmpty && _onlyGetters(overriddenGetters)) {
newType =
_computeReturnType(overriddenGetters.map((e) => e.returnType));
- List<ExecutableElement> overriddenSetters =
- inheritanceManager.lookupOverrides(
- fieldElement.enclosingElement, fieldElement.name + '=');
+
if (!_isCompatible(newType, overriddenSetters)) {
newType = null;
}
@@ -374,6 +380,17 @@
}
/**
+ * If a parameter is covariant, any parameters that override it are too.
+ */
+ void _inferParameterCovariance(ParameterElementImpl parameter, int index,
+ Iterable<FunctionType> overriddenTypes) {
+ parameter.inheritsCovariant = overriddenTypes.any((f) {
+ var param = _getCorrespondingParameter(parameter, index, f.parameters);
+ return param != null && param.isCovariant;
+ });
+ }
+
+ /**
* Infer type information for all of the instance members in the given
* interface [type].
*/
diff --git a/pkg/analyzer/lib/src/task/yaml.dart b/pkg/analyzer/lib/src/task/yaml.dart
index c74804a..2ac731d 100644
--- a/pkg/analyzer/lib/src/task/yaml.dart
+++ b/pkg/analyzer/lib/src/task/yaml.dart
@@ -4,11 +4,11 @@
library analyzer.src.task.yaml;
+import 'package:analyzer/error/error.dart';
import 'package:analyzer/exception/exception.dart';
import 'package:analyzer/src/context/cache.dart';
import 'package:analyzer/src/dart/scanner/scanner.dart';
import 'package:analyzer/src/generated/engine.dart';
-import 'package:analyzer/src/generated/error.dart';
import 'package:analyzer/src/generated/source.dart';
import 'package:analyzer/src/task/general.dart';
import 'package:analyzer/task/general.dart';
diff --git a/pkg/analyzer/lib/task/dart.dart b/pkg/analyzer/lib/task/dart.dart
index 5837d05..2a6f5fe 100644
--- a/pkg/analyzer/lib/task/dart.dart
+++ b/pkg/analyzer/lib/task/dart.dart
@@ -7,7 +7,7 @@
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/ast/token.dart';
import 'package:analyzer/dart/element/element.dart';
-import 'package:analyzer/src/generated/error.dart';
+import 'package:analyzer/error/error.dart';
import 'package:analyzer/src/generated/source.dart';
import 'package:analyzer/src/generated/utilities_general.dart';
import 'package:analyzer/src/task/dart.dart';
diff --git a/pkg/analyzer/lib/task/html.dart b/pkg/analyzer/lib/task/html.dart
index abfbdf7..9df8394 100644
--- a/pkg/analyzer/lib/task/html.dart
+++ b/pkg/analyzer/lib/task/html.dart
@@ -4,7 +4,7 @@
library analyzer.task.html;
-import 'package:analyzer/src/generated/error.dart';
+import 'package:analyzer/error/error.dart';
import 'package:analyzer/src/generated/source.dart';
import 'package:analyzer/task/model.dart';
import 'package:html/dom.dart';
diff --git a/pkg/analyzer/lib/task/model.dart b/pkg/analyzer/lib/task/model.dart
index 32df0e5..2a6f6c5 100644
--- a/pkg/analyzer/lib/task/model.dart
+++ b/pkg/analyzer/lib/task/model.dart
@@ -7,9 +7,9 @@
import 'dart:collection';
import 'dart:developer';
+import 'package:analyzer/error/error.dart' show AnalysisError;
import 'package:analyzer/exception/exception.dart';
import 'package:analyzer/src/generated/engine.dart';
-import 'package:analyzer/src/generated/error.dart' show AnalysisError;
import 'package:analyzer/src/generated/source.dart';
import 'package:analyzer/src/generated/utilities_general.dart';
import 'package:analyzer/src/task/driver.dart';
diff --git a/pkg/analyzer/lib/task/yaml.dart b/pkg/analyzer/lib/task/yaml.dart
index 1795d8f..3888bf7 100644
--- a/pkg/analyzer/lib/task/yaml.dart
+++ b/pkg/analyzer/lib/task/yaml.dart
@@ -4,7 +4,7 @@
library analyzer.task.yaml;
-import 'package:analyzer/src/generated/error.dart';
+import 'package:analyzer/error/error.dart';
import 'package:analyzer/src/generated/source.dart';
import 'package:analyzer/task/model.dart';
import 'package:yaml/yaml.dart';
diff --git a/pkg/analyzer/test/enum_test.dart b/pkg/analyzer/test/enum_test.dart
index 932ea55..6996ee0 100644
--- a/pkg/analyzer/test/enum_test.dart
+++ b/pkg/analyzer/test/enum_test.dart
@@ -7,9 +7,9 @@
import 'dart:mirrors';
import 'package:analyzer/dart/element/element.dart';
+import 'package:analyzer/error/error.dart';
import 'package:analyzer/src/dart/element/element.dart';
import 'package:analyzer/src/generated/engine.dart';
-import 'package:analyzer/src/generated/error.dart';
import 'package:analyzer/src/generated/java_core.dart';
import 'package:analyzer/src/generated/resolver.dart';
import 'package:analyzer/src/generated/source.dart';
diff --git a/pkg/analyzer/test/generated/all_the_rest_test.dart b/pkg/analyzer/test/generated/all_the_rest_test.dart
index e52d5a4..a8411f4 100644
--- a/pkg/analyzer/test/generated/all_the_rest_test.dart
+++ b/pkg/analyzer/test/generated/all_the_rest_test.dart
@@ -8,6 +8,8 @@
import 'package:analyzer/dart/ast/token.dart';
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/type.dart';
+import 'package:analyzer/error/error.dart';
+import 'package:analyzer/error/listener.dart';
import 'package:analyzer/file_system/file_system.dart';
import 'package:analyzer/file_system/memory_file_system.dart';
import 'package:analyzer/file_system/physical_file_system.dart';
@@ -16,8 +18,8 @@
import 'package:analyzer/src/dart/element/builder.dart';
import 'package:analyzer/src/dart/element/element.dart';
import 'package:analyzer/src/dart/sdk/sdk.dart' hide SdkLibrariesReader;
+import 'package:analyzer/src/error/codes.dart';
import 'package:analyzer/src/generated/engine.dart';
-import 'package:analyzer/src/generated/error.dart';
import 'package:analyzer/src/generated/java_engine_io.dart';
import 'package:analyzer/src/generated/java_io.dart';
import 'package:analyzer/src/generated/resolver.dart';
diff --git a/pkg/analyzer/test/generated/analysis_context_factory.dart b/pkg/analyzer/test/generated/analysis_context_factory.dart
index 48234e1..78c62e9 100644
--- a/pkg/analyzer/test/generated/analysis_context_factory.dart
+++ b/pkg/analyzer/test/generated/analysis_context_factory.dart
@@ -226,7 +226,7 @@
ElementFactory.namedParameter2("onError", provider.functionType)
]);
if (!futureThenR.type.isDynamic) {
- thenMethod.typeParameters = [futureThenR];
+ thenMethod.typeParameters = <TypeParameterElement>[futureThenR];
}
thenOnValue.enclosingElement = thenMethod;
thenOnValue.type = new FunctionTypeImpl(thenOnValue);
diff --git a/pkg/analyzer/test/generated/checked_mode_compile_time_error_code_test.dart b/pkg/analyzer/test/generated/checked_mode_compile_time_error_code_test.dart
index 513d399..b252888 100644
--- a/pkg/analyzer/test/generated/checked_mode_compile_time_error_code_test.dart
+++ b/pkg/analyzer/test/generated/checked_mode_compile_time_error_code_test.dart
@@ -4,7 +4,7 @@
library analyzer.test.generated.checked_mode_compile_time_error_code_test;
-import 'package:analyzer/src/generated/error.dart';
+import 'package:analyzer/src/error/codes.dart';
import 'package:analyzer/src/generated/source_io.dart';
import 'package:test_reflective_loader/test_reflective_loader.dart';
diff --git a/pkg/analyzer/test/generated/compile_time_error_code_test.dart b/pkg/analyzer/test/generated/compile_time_error_code_test.dart
index 71b0aef..cae5fd7 100644
--- a/pkg/analyzer/test/generated/compile_time_error_code_test.dart
+++ b/pkg/analyzer/test/generated/compile_time_error_code_test.dart
@@ -4,8 +4,9 @@
library analyzer.test.generated.compile_time_error_code_test;
+import 'package:analyzer/error/error.dart';
+import 'package:analyzer/src/error/codes.dart';
import 'package:analyzer/src/generated/engine.dart';
-import 'package:analyzer/src/generated/error.dart';
import 'package:analyzer/src/generated/parser.dart' show ParserErrorCode;
import 'package:analyzer/src/generated/source_io.dart';
import 'package:test_reflective_loader/test_reflective_loader.dart';
diff --git a/pkg/analyzer/test/generated/engine_test.dart b/pkg/analyzer/test/generated/engine_test.dart
index c98cfc9..1c681c4 100644
--- a/pkg/analyzer/test/generated/engine_test.dart
+++ b/pkg/analyzer/test/generated/engine_test.dart
@@ -8,6 +8,7 @@
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/element/element.dart';
+import 'package:analyzer/error/error.dart';
import 'package:analyzer/plugin/resolver_provider.dart';
import 'package:analyzer/src/cancelable_future.dart';
import 'package:analyzer/src/context/builder.dart' show EmbedderYamlLocator;
@@ -16,7 +17,6 @@
import 'package:analyzer/src/context/source.dart';
import 'package:analyzer/src/generated/constant.dart';
import 'package:analyzer/src/generated/engine.dart';
-import 'package:analyzer/src/generated/error.dart';
import 'package:analyzer/src/generated/resolver.dart';
import 'package:analyzer/src/generated/source_io.dart';
import 'package:analyzer/src/string_source.dart';
diff --git a/pkg/analyzer/test/generated/error_suppression_test.dart b/pkg/analyzer/test/generated/error_suppression_test.dart
index a546200..00355f6 100644
--- a/pkg/analyzer/test/generated/error_suppression_test.dart
+++ b/pkg/analyzer/test/generated/error_suppression_test.dart
@@ -2,7 +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/src/generated/error.dart';
+import 'package:analyzer/src/error/codes.dart';
import 'package:analyzer/src/generated/source.dart';
import 'package:analyzer/src/generated/source_io.dart';
import 'package:test_reflective_loader/test_reflective_loader.dart';
diff --git a/pkg/analyzer/test/generated/hint_code_test.dart b/pkg/analyzer/test/generated/hint_code_test.dart
index b003089..750ef78 100644
--- a/pkg/analyzer/test/generated/hint_code_test.dart
+++ b/pkg/analyzer/test/generated/hint_code_test.dart
@@ -4,8 +4,9 @@
library analyzer.test.generated.hint_code_test;
+import 'package:analyzer/error/error.dart';
+import 'package:analyzer/src/error/codes.dart';
import 'package:analyzer/src/generated/engine.dart';
-import 'package:analyzer/src/generated/error.dart';
import 'package:analyzer/src/generated/parser.dart';
import 'package:analyzer/src/generated/source_io.dart';
import 'package:test_reflective_loader/test_reflective_loader.dart';
@@ -108,17 +109,6 @@
verify([source]);
}
- void test_canBeNullAfterNullAware_false_propertyAccess() {
- Source source = addSource(r'''
-m(x) {
- x?.a?.b;
-}
-''');
- computeLibrarySourceErrors(source);
- assertNoErrors(source);
- verify([source]);
- }
-
void test_canBeNullAfterNullAware_false_null() {
Source source = addSource(r'''
m(x) {
@@ -135,6 +125,17 @@
verify([source]);
}
+ void test_canBeNullAfterNullAware_false_propertyAccess() {
+ Source source = addSource(r'''
+m(x) {
+ x?.a?.b;
+}
+''');
+ computeLibrarySourceErrors(source);
+ assertNoErrors(source);
+ verify([source]);
+ }
+
void test_canBeNullAfterNullAware_methodInvocation() {
Source source = addSource(r'''
m(x) {
diff --git a/pkg/analyzer/test/generated/incremental_resolver_test.dart b/pkg/analyzer/test/generated/incremental_resolver_test.dart
index b9d0e78..e80ea99 100644
--- a/pkg/analyzer/test/generated/incremental_resolver_test.dart
+++ b/pkg/analyzer/test/generated/incremental_resolver_test.dart
@@ -7,6 +7,8 @@
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/ast/token.dart';
import 'package:analyzer/dart/element/element.dart';
+import 'package:analyzer/error/error.dart';
+import 'package:analyzer/error/listener.dart';
import 'package:analyzer/exception/exception.dart';
import 'package:analyzer/src/context/cache.dart';
import 'package:analyzer/src/dart/ast/utilities.dart';
@@ -14,7 +16,6 @@
import 'package:analyzer/src/dart/scanner/reader.dart';
import 'package:analyzer/src/dart/scanner/scanner.dart';
import 'package:analyzer/src/generated/engine.dart';
-import 'package:analyzer/src/generated/error.dart';
import 'package:analyzer/src/generated/incremental_logger.dart' as logging;
import 'package:analyzer/src/generated/incremental_resolution_validator.dart';
import 'package:analyzer/src/generated/incremental_resolver.dart';
diff --git a/pkg/analyzer/test/generated/inheritance_manager_test.dart b/pkg/analyzer/test/generated/inheritance_manager_test.dart
index 753b06e..0be0549 100644
--- a/pkg/analyzer/test/generated/inheritance_manager_test.dart
+++ b/pkg/analyzer/test/generated/inheritance_manager_test.dart
@@ -8,11 +8,12 @@
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/type.dart';
+import 'package:analyzer/error/error.dart';
import 'package:analyzer/file_system/memory_file_system.dart';
import 'package:analyzer/src/dart/element/element.dart';
import 'package:analyzer/src/dart/resolver/inheritance_manager.dart';
+import 'package:analyzer/src/error/codes.dart';
import 'package:analyzer/src/generated/engine.dart';
-import 'package:analyzer/src/generated/error.dart';
import 'package:analyzer/src/generated/resolver.dart';
import 'package:analyzer/src/generated/source_io.dart';
import 'package:analyzer/src/generated/testing/ast_factory.dart';
diff --git a/pkg/analyzer/test/generated/non_error_resolver_test.dart b/pkg/analyzer/test/generated/non_error_resolver_test.dart
index 138970c..21eb70a 100644
--- a/pkg/analyzer/test/generated/non_error_resolver_test.dart
+++ b/pkg/analyzer/test/generated/non_error_resolver_test.dart
@@ -6,8 +6,9 @@
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/element/element.dart';
+import 'package:analyzer/error/error.dart';
+import 'package:analyzer/src/error/codes.dart';
import 'package:analyzer/src/generated/engine.dart';
-import 'package:analyzer/src/generated/error.dart';
import 'package:analyzer/src/generated/parser.dart' show ParserErrorCode;
import 'package:analyzer/src/generated/source_io.dart';
import 'package:test_reflective_loader/test_reflective_loader.dart';
diff --git a/pkg/analyzer/test/generated/non_hint_code_test.dart b/pkg/analyzer/test/generated/non_hint_code_test.dart
index ba99612..b023ed5 100644
--- a/pkg/analyzer/test/generated/non_hint_code_test.dart
+++ b/pkg/analyzer/test/generated/non_hint_code_test.dart
@@ -4,7 +4,8 @@
library analyzer.test.generated.non_hint_code_test;
-import 'package:analyzer/src/generated/error.dart';
+import 'package:analyzer/error/error.dart';
+import 'package:analyzer/src/error/codes.dart';
import 'package:analyzer/src/generated/source_io.dart';
import 'package:test_reflective_loader/test_reflective_loader.dart';
diff --git a/pkg/analyzer/test/generated/parser_test.dart b/pkg/analyzer/test/generated/parser_test.dart
index 38d3464..76aef35 100644
--- a/pkg/analyzer/test/generated/parser_test.dart
+++ b/pkg/analyzer/test/generated/parser_test.dart
@@ -7,10 +7,10 @@
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/ast/token.dart';
import 'package:analyzer/dart/ast/visitor.dart';
+import 'package:analyzer/error/error.dart';
import 'package:analyzer/src/dart/ast/token.dart';
import 'package:analyzer/src/dart/scanner/reader.dart';
import 'package:analyzer/src/dart/scanner/scanner.dart';
-import 'package:analyzer/src/generated/error.dart';
import 'package:analyzer/src/generated/parser.dart';
import 'package:analyzer/src/generated/testing/ast_factory.dart';
import 'package:analyzer/src/generated/testing/token_factory.dart';
@@ -30,15 +30,6 @@
defineReflectiveTests(SimpleParserTest);
}
-class AnalysisErrorListener_SimpleParserTest_computeStringValue
- implements AnalysisErrorListener {
- @override
- void onError(AnalysisError event) {
- fail(
- "Unexpected compilation error: ${event.message} (${event.offset}, ${event.length})");
- }
-}
-
/**
* Instances of the class `AstValidator` are used to validate the correct construction of an
* AST structure.
@@ -345,6 +336,20 @@
BinaryExpression, expression.condition);
}
+ void test_conditionalExpression_precedence_nullableType() {
+ enableNnbd = true;
+ Expression expression = parseExpression('x is String ? (x + y) : z');
+ expect(expression, isNotNull);
+ expect(expression, new isInstanceOf<ConditionalExpression>());
+ ConditionalExpression conditional = expression;
+ Expression condition = conditional.condition;
+ expect(condition, new isInstanceOf<IsExpression>());
+ Expression thenExpression = conditional.thenExpression;
+ expect(thenExpression, new isInstanceOf<ParenthesizedExpression>());
+ Expression elseExpression = conditional.elseExpression;
+ expect(elseExpression, new isInstanceOf<SimpleIdentifier>());
+ }
+
void test_constructor_initializer_withParenthesizedExpression() {
CompilationUnit unit = ParserTestCase.parseCompilationUnit(r'''
class C {
@@ -394,7 +399,7 @@
BinaryExpression, expression.leftOperand);
}
- void test_ifNullExpression_precendce_logicalOr_right() {
+ void test_ifNullExpression_precedence_logicalOr_right() {
BinaryExpression expression = parseExpression('x ?? y || z');
EngineTestCase.assertInstanceOf((obj) => obj is BinaryExpression,
BinaryExpression, expression.rightOperand);
@@ -402,32 +407,34 @@
void test_logicalAndExpression() {
BinaryExpression expression = parseExpression("x && y && z");
- EngineTestCase.assertInstanceOf((obj) => obj is BinaryExpression,
- BinaryExpression, expression.leftOperand);
+ expect(expression.leftOperand, new isInstanceOf<BinaryExpression>());
}
void test_logicalAndExpression_precedence_bitwiseOr_left() {
BinaryExpression expression = parseExpression("x | y < z");
- EngineTestCase.assertInstanceOf((obj) => obj is BinaryExpression,
- BinaryExpression, expression.leftOperand);
+ expect(expression.leftOperand, new isInstanceOf<BinaryExpression>());
}
void test_logicalAndExpression_precedence_bitwiseOr_right() {
BinaryExpression expression = parseExpression("x < y | z");
- EngineTestCase.assertInstanceOf((obj) => obj is BinaryExpression,
- BinaryExpression, expression.rightOperand);
+ expect(expression.rightOperand, new isInstanceOf<BinaryExpression>());
+ }
+
+ void test_logicalAndExpression_precedence_nullableType() {
+ enableNnbd = true;
+ BinaryExpression expression = parseExpression("x is C? && y is D");
+ expect(expression.leftOperand, new isInstanceOf<IsExpression>());
+ expect(expression.rightOperand, new isInstanceOf<IsExpression>());
}
void test_logicalOrExpression() {
BinaryExpression expression = parseExpression("x || y || z");
- EngineTestCase.assertInstanceOf((obj) => obj is BinaryExpression,
- BinaryExpression, expression.leftOperand);
+ expect(expression.leftOperand, new isInstanceOf<BinaryExpression>());
}
void test_logicalOrExpression_precedence_logicalAnd_left() {
BinaryExpression expression = parseExpression("x && y || z");
- EngineTestCase.assertInstanceOf((obj) => obj is BinaryExpression,
- BinaryExpression, expression.leftOperand);
+ expect(expression.leftOperand, new isInstanceOf<BinaryExpression>());
}
void test_logicalOrExpression_precedence_logicalAnd_right() {
@@ -436,6 +443,16 @@
BinaryExpression, expression.rightOperand);
}
+ void test_logicalOrExpression_precedence_nullableType() {
+ enableNnbd = true;
+ BinaryExpression expression = parseExpression("a is X? || (b ? c : d)");
+ expect(expression.leftOperand, new isInstanceOf<IsExpression>());
+ expect(
+ expression.rightOperand, new isInstanceOf<ParenthesizedExpression>());
+ expect((expression.rightOperand as ParenthesizedExpression).expression,
+ new isInstanceOf<ConditionalExpression>());
+ }
+
void test_multipleLabels_statement() {
LabeledStatement statement =
ParserTestCase.parseStatement("a: b: c: return x;");
@@ -563,8 +580,11 @@
// literals that are being created are not always zero length (because they
// could have type parameters), which violates the contract of
// isSynthetic().
- TypedLiteral literal = parse3("parseListOrMapLiteral", <Object>[null], "1",
- [ParserErrorCode.EXPECTED_LIST_OR_MAP_LITERAL]);
+ createParser('1');
+ TypedLiteral literal = parser.parseListOrMapLiteral(null);
+ expectNotNullIfNoErrors(literal);
+ listener
+ .assertErrorsWithCodes([ParserErrorCode.EXPECTED_LIST_OR_MAP_LITERAL]);
expect(literal.isSynthetic, isTrue);
}
@@ -577,32 +597,43 @@
void fail_invalidCommentReference__new_nonIdentifier() {
// This test fails because the method parseCommentReference returns null.
- parse3("parseCommentReference", <Object>["new 42", 0], "",
- [ParserErrorCode.INVALID_COMMENT_REFERENCE]);
+ createParser('');
+ CommentReference reference = parser.parseCommentReference('new 42', 0);
+ expectNotNullIfNoErrors(reference);
+ listener.assertErrorsWithCodes([ParserErrorCode.INVALID_COMMENT_REFERENCE]);
}
void fail_invalidCommentReference__new_tooMuch() {
- parse3("parseCommentReference", <Object>["new a.b.c.d", 0], "",
- [ParserErrorCode.INVALID_COMMENT_REFERENCE]);
+ createParser('');
+ CommentReference reference = parser.parseCommentReference('new a.b.c.d', 0);
+ expectNotNullIfNoErrors(reference);
+ listener.assertErrorsWithCodes([ParserErrorCode.INVALID_COMMENT_REFERENCE]);
}
void fail_invalidCommentReference__nonNew_nonIdentifier() {
// This test fails because the method parseCommentReference returns null.
- parse3("parseCommentReference", <Object>["42", 0], "",
- [ParserErrorCode.INVALID_COMMENT_REFERENCE]);
+ createParser('');
+ CommentReference reference = parser.parseCommentReference('42', 0);
+ expectNotNullIfNoErrors(reference);
+ listener.assertErrorsWithCodes([ParserErrorCode.INVALID_COMMENT_REFERENCE]);
}
void fail_invalidCommentReference__nonNew_tooMuch() {
- parse3("parseCommentReference", <Object>["a.b.c.d", 0], "",
- [ParserErrorCode.INVALID_COMMENT_REFERENCE]);
+ createParser('');
+ CommentReference reference = parser.parseCommentReference('a.b.c.d', 0);
+ expectNotNullIfNoErrors(reference);
+ listener.assertErrorsWithCodes([ParserErrorCode.INVALID_COMMENT_REFERENCE]);
}
void fail_missingClosingParenthesis() {
// It is possible that it is not possible to generate this error (that it's
// being reported in code that cannot actually be reached), but that hasn't
// been proven yet.
- parse4("parseFormalParameterList", "(int a, int b ;",
- [ParserErrorCode.MISSING_CLOSING_PARENTHESIS]);
+ createParser('(int a, int b ;');
+ FormalParameterList list = parser.parseFormalParameterList();
+ expectNotNullIfNoErrors(list);
+ listener
+ .assertErrorsWithCodes([ParserErrorCode.MISSING_CLOSING_PARENTHESIS]);
}
void fail_missingFunctionParameters_local_nonVoid_block() {
@@ -622,10 +653,11 @@
}
void fail_namedFunctionExpression() {
- Expression expression = parse4("parsePrimaryExpression", "f() {}",
- [ParserErrorCode.NAMED_FUNCTION_EXPRESSION]);
- EngineTestCase.assertInstanceOf(
- (obj) => obj is FunctionExpression, FunctionExpression, expression);
+ createParser('f() {}');
+ Expression expression = parser.parsePrimaryExpression();
+ expectNotNullIfNoErrors(expression);
+ listener.assertErrorsWithCodes([ParserErrorCode.NAMED_FUNCTION_EXPRESSION]);
+ expect(expression, new isInstanceOf<FunctionExpression>());
}
void fail_unexpectedToken_invalidPostfixExpression() {
@@ -643,33 +675,45 @@
void fail_varAndType_parameter() {
// This is currently reporting EXPECTED_TOKEN for a missing semicolon, but
// this would be a better error message.
- parse4("parseFormalParameterList", "(var int x)",
- [ParserErrorCode.VAR_AND_TYPE]);
+ createParser('(var int x)');
+ FormalParameterList list = parser.parseFormalParameterList();
+ expectNotNullIfNoErrors(list);
+ listener.assertErrorsWithCodes([ParserErrorCode.VAR_AND_TYPE]);
}
void test_abstractClassMember_constructor() {
- parse3("parseClassMember", <Object>["C"], "abstract C.c();",
- [ParserErrorCode.ABSTRACT_CLASS_MEMBER]);
+ createParser('abstract C.c();');
+ ClassMember member = parser.parseClassMember('C');
+ expectNotNullIfNoErrors(member);
+ listener.assertErrorsWithCodes([ParserErrorCode.ABSTRACT_CLASS_MEMBER]);
}
void test_abstractClassMember_field() {
- parse3("parseClassMember", <Object>["C"], "abstract C f;",
- [ParserErrorCode.ABSTRACT_CLASS_MEMBER]);
+ createParser('abstract C f;');
+ ClassMember member = parser.parseClassMember('C');
+ expectNotNullIfNoErrors(member);
+ listener.assertErrorsWithCodes([ParserErrorCode.ABSTRACT_CLASS_MEMBER]);
}
void test_abstractClassMember_getter() {
- parse3("parseClassMember", <Object>["C"], "abstract get m;",
- [ParserErrorCode.ABSTRACT_CLASS_MEMBER]);
+ createParser('abstract get m;');
+ ClassMember member = parser.parseClassMember('C');
+ expectNotNullIfNoErrors(member);
+ listener.assertErrorsWithCodes([ParserErrorCode.ABSTRACT_CLASS_MEMBER]);
}
void test_abstractClassMember_method() {
- parse3("parseClassMember", <Object>["C"], "abstract m();",
- [ParserErrorCode.ABSTRACT_CLASS_MEMBER]);
+ createParser('abstract m();');
+ ClassMember member = parser.parseClassMember('C');
+ expectNotNullIfNoErrors(member);
+ listener.assertErrorsWithCodes([ParserErrorCode.ABSTRACT_CLASS_MEMBER]);
}
void test_abstractClassMember_setter() {
- parse3("parseClassMember", <Object>["C"], "abstract set m(v);",
- [ParserErrorCode.ABSTRACT_CLASS_MEMBER]);
+ createParser('abstract set m(v);');
+ ClassMember member = parser.parseClassMember('C');
+ expectNotNullIfNoErrors(member);
+ listener.assertErrorsWithCodes([ParserErrorCode.ABSTRACT_CLASS_MEMBER]);
}
void test_abstractEnum() {
@@ -713,24 +757,38 @@
}
void test_breakOutsideOfLoop_breakInDoStatement() {
- parse4("parseDoStatement", "do {break;} while (x);");
+ createParser('do {break;} while (x);');
+ DoStatement statement = parser.parseDoStatement();
+ expectNotNullIfNoErrors(statement);
+ listener.assertNoErrors();
}
void test_breakOutsideOfLoop_breakInForStatement() {
- parse4("parseForStatement", "for (; x;) {break;}");
+ createParser('for (; x;) {break;}');
+ Statement statement = parser.parseForStatement();
+ expectNotNullIfNoErrors(statement);
+ listener.assertNoErrors();
}
void test_breakOutsideOfLoop_breakInIfStatement() {
- parse4("parseIfStatement", "if (x) {break;}",
- [ParserErrorCode.BREAK_OUTSIDE_OF_LOOP]);
+ createParser('if (x) {break;}');
+ IfStatement statement = parser.parseIfStatement();
+ expectNotNullIfNoErrors(statement);
+ listener.assertErrorsWithCodes([ParserErrorCode.BREAK_OUTSIDE_OF_LOOP]);
}
void test_breakOutsideOfLoop_breakInSwitchStatement() {
- parse4("parseSwitchStatement", "switch (x) {case 1: break;}");
+ createParser('switch (x) {case 1: break;}');
+ SwitchStatement statement = parser.parseSwitchStatement();
+ expectNotNullIfNoErrors(statement);
+ listener.assertNoErrors();
}
void test_breakOutsideOfLoop_breakInWhileStatement() {
- parse4("parseWhileStatement", "while (x) {break;}");
+ createParser('while (x) {break;}');
+ WhileStatement statement = parser.parseWhileStatement();
+ expectNotNullIfNoErrors(statement);
+ listener.assertNoErrors();
}
void test_breakOutsideOfLoop_functionExpression_inALoop() {
@@ -755,10 +813,11 @@
void test_classTypeAlias_abstractAfterEq() {
// This syntax has been removed from the language in favor of
// "abstract class A = B with C;" (issue 18098).
- parse3(
- "parseCompilationUnitMember",
- <Object>[emptyCommentAndMetadata()],
- "class A = abstract B with C;",
+ createParser('class A = abstract B with C;');
+ CompilationUnitMember member =
+ parser.parseCompilationUnitMember(emptyCommentAndMetadata());
+ expectNotNullIfNoErrors(member);
+ listener.assertErrorsWithCodes(
[ParserErrorCode.EXPECTED_TOKEN, ParserErrorCode.EXPECTED_TOKEN]);
}
@@ -768,13 +827,17 @@
}
void test_constAndFinal() {
- parse3("parseClassMember", <Object>["C"], "const final int x;",
- [ParserErrorCode.CONST_AND_FINAL]);
+ createParser('const final int x;');
+ ClassMember member = parser.parseClassMember('C');
+ expectNotNullIfNoErrors(member);
+ listener.assertErrorsWithCodes([ParserErrorCode.CONST_AND_FINAL]);
}
void test_constAndVar() {
- parse3("parseClassMember", <Object>["C"], "const var x;",
- [ParserErrorCode.CONST_AND_VAR]);
+ createParser('const var x;');
+ ClassMember member = parser.parseClassMember('C');
+ expectNotNullIfNoErrors(member);
+ listener.assertErrorsWithCodes([ParserErrorCode.CONST_AND_VAR]);
}
void test_constClass() {
@@ -783,8 +846,11 @@
}
void test_constConstructorWithBody() {
- parse3("parseClassMember", <Object>["C"], "const C() {}",
- [ParserErrorCode.CONST_CONSTRUCTOR_WITH_BODY]);
+ createParser('const C() {}');
+ ClassMember member = parser.parseClassMember('C');
+ expectNotNullIfNoErrors(member);
+ listener
+ .assertErrorsWithCodes([ParserErrorCode.CONST_CONSTRUCTOR_WITH_BODY]);
}
void test_constEnum() {
@@ -793,23 +859,33 @@
}
void test_constFactory() {
- parse3("parseClassMember", <Object>["C"], "const factory C() {}",
- [ParserErrorCode.CONST_FACTORY]);
+ createParser('const factory C() {}');
+ ClassMember member = parser.parseClassMember('C');
+ expectNotNullIfNoErrors(member);
+ listener.assertErrorsWithCodes([ParserErrorCode.CONST_FACTORY]);
}
void test_constMethod() {
- parse3("parseClassMember", <Object>["C"], "const int m() {}",
- [ParserErrorCode.CONST_METHOD]);
+ createParser('const int m() {}');
+ ClassMember member = parser.parseClassMember('C');
+ expectNotNullIfNoErrors(member);
+ listener.assertErrorsWithCodes([ParserErrorCode.CONST_METHOD]);
}
void test_constructorWithReturnType() {
- parse3("parseClassMember", <Object>["C"], "C C() {}",
- [ParserErrorCode.CONSTRUCTOR_WITH_RETURN_TYPE]);
+ createParser('C C() {}');
+ ClassMember member = parser.parseClassMember('C');
+ expectNotNullIfNoErrors(member);
+ listener
+ .assertErrorsWithCodes([ParserErrorCode.CONSTRUCTOR_WITH_RETURN_TYPE]);
}
void test_constructorWithReturnType_var() {
- parse3("parseClassMember", <Object>["C"], "var C() {}",
- [ParserErrorCode.CONSTRUCTOR_WITH_RETURN_TYPE]);
+ createParser('var C() {}');
+ ClassMember member = parser.parseClassMember('C');
+ expectNotNullIfNoErrors(member);
+ listener
+ .assertErrorsWithCodes([ParserErrorCode.CONSTRUCTOR_WITH_RETURN_TYPE]);
}
void test_constTypedef() {
@@ -818,24 +894,38 @@
}
void test_continueOutsideOfLoop_continueInDoStatement() {
- parse4("parseDoStatement", "do {continue;} while (x);");
+ createParser('do {continue;} while (x);');
+ DoStatement statement = parser.parseDoStatement();
+ expectNotNullIfNoErrors(statement);
+ listener.assertNoErrors();
}
void test_continueOutsideOfLoop_continueInForStatement() {
- parse4("parseForStatement", "for (; x;) {continue;}");
+ createParser('for (; x;) {continue;}');
+ Statement statement = parser.parseForStatement();
+ expectNotNullIfNoErrors(statement);
+ listener.assertNoErrors();
}
void test_continueOutsideOfLoop_continueInIfStatement() {
- parse4("parseIfStatement", "if (x) {continue;}",
- [ParserErrorCode.CONTINUE_OUTSIDE_OF_LOOP]);
+ createParser('if (x) {continue;}');
+ IfStatement statement = parser.parseIfStatement();
+ expectNotNullIfNoErrors(statement);
+ listener.assertErrorsWithCodes([ParserErrorCode.CONTINUE_OUTSIDE_OF_LOOP]);
}
void test_continueOutsideOfLoop_continueInSwitchStatement() {
- parse4("parseSwitchStatement", "switch (x) {case 1: continue a;}");
+ createParser('switch (x) {case 1: continue a;}');
+ SwitchStatement statement = parser.parseSwitchStatement();
+ expectNotNullIfNoErrors(statement);
+ listener.assertNoErrors();
}
void test_continueOutsideOfLoop_continueInWhileStatement() {
- parse4("parseWhileStatement", "while (x) {continue;}");
+ createParser('while (x) {continue;}');
+ WhileStatement statement = parser.parseWhileStatement();
+ expectNotNullIfNoErrors(statement);
+ listener.assertNoErrors();
}
void test_continueOutsideOfLoop_functionExpression_inALoop() {
@@ -848,17 +938,25 @@
}
void test_continueWithoutLabelInCase_error() {
- parse4("parseSwitchStatement", "switch (x) {case 1: continue;}",
+ createParser('switch (x) {case 1: continue;}');
+ SwitchStatement statement = parser.parseSwitchStatement();
+ expectNotNullIfNoErrors(statement);
+ listener.assertErrorsWithCodes(
[ParserErrorCode.CONTINUE_WITHOUT_LABEL_IN_CASE]);
}
void test_continueWithoutLabelInCase_noError() {
- parse4("parseSwitchStatement", "switch (x) {case 1: continue a;}");
+ createParser('switch (x) {case 1: continue a;}');
+ SwitchStatement statement = parser.parseSwitchStatement();
+ expectNotNullIfNoErrors(statement);
+ listener.assertNoErrors();
}
void test_continueWithoutLabelInCase_noError_switchInLoop() {
- parse4(
- "parseWhileStatement", "while (a) { switch (b) {default: continue;}}");
+ createParser('while (a) { switch (b) {default: continue;}}');
+ WhileStatement statement = parser.parseWhileStatement();
+ expectNotNullIfNoErrors(statement);
+ listener.assertNoErrors();
}
void test_deprecatedClassTypeAlias() {
@@ -886,76 +984,95 @@
}
void test_duplicatedModifier_const() {
- parse3("parseClassMember", <Object>["C"], "const const m;",
- [ParserErrorCode.DUPLICATED_MODIFIER]);
+ createParser('const const m;');
+ ClassMember member = parser.parseClassMember('C');
+ expectNotNullIfNoErrors(member);
+ listener.assertErrorsWithCodes([ParserErrorCode.DUPLICATED_MODIFIER]);
}
void test_duplicatedModifier_external() {
- parse3("parseClassMember", <Object>["C"], "external external f();",
- [ParserErrorCode.DUPLICATED_MODIFIER]);
+ createParser('external external f();');
+ ClassMember member = parser.parseClassMember('C');
+ expectNotNullIfNoErrors(member);
+ listener.assertErrorsWithCodes([ParserErrorCode.DUPLICATED_MODIFIER]);
}
void test_duplicatedModifier_factory() {
- parse3("parseClassMember", <Object>["C"], "factory factory C() {}",
- [ParserErrorCode.DUPLICATED_MODIFIER]);
+ createParser('factory factory C() {}');
+ ClassMember member = parser.parseClassMember('C');
+ expectNotNullIfNoErrors(member);
+ listener.assertErrorsWithCodes([ParserErrorCode.DUPLICATED_MODIFIER]);
}
void test_duplicatedModifier_final() {
- parse3("parseClassMember", <Object>["C"], "final final m;",
- [ParserErrorCode.DUPLICATED_MODIFIER]);
+ createParser('final final m;');
+ ClassMember member = parser.parseClassMember('C');
+ expectNotNullIfNoErrors(member);
+ listener.assertErrorsWithCodes([ParserErrorCode.DUPLICATED_MODIFIER]);
}
void test_duplicatedModifier_static() {
- parse3("parseClassMember", <Object>["C"], "static static var m;",
- [ParserErrorCode.DUPLICATED_MODIFIER]);
+ createParser('static static var m;');
+ ClassMember member = parser.parseClassMember('C');
+ expectNotNullIfNoErrors(member);
+ listener.assertErrorsWithCodes([ParserErrorCode.DUPLICATED_MODIFIER]);
}
void test_duplicatedModifier_var() {
- parse3("parseClassMember", <Object>["C"], "var var m;",
- [ParserErrorCode.DUPLICATED_MODIFIER]);
+ createParser('var var m;');
+ ClassMember member = parser.parseClassMember('C');
+ expectNotNullIfNoErrors(member);
+ listener.assertErrorsWithCodes([ParserErrorCode.DUPLICATED_MODIFIER]);
}
void test_duplicateLabelInSwitchStatement() {
- parse4(
- "parseSwitchStatement",
- "switch (e) {l1: case 0: break; l1: case 1: break;}",
+ createParser('switch (e) {l1: case 0: break; l1: case 1: break;}');
+ SwitchStatement statement = parser.parseSwitchStatement();
+ expectNotNullIfNoErrors(statement);
+ listener.assertErrorsWithCodes(
[ParserErrorCode.DUPLICATE_LABEL_IN_SWITCH_STATEMENT]);
}
void test_emptyEnumBody() {
- parse3("parseEnumDeclaration", <Object>[emptyCommentAndMetadata()],
- "enum E {}", [ParserErrorCode.EMPTY_ENUM_BODY]);
+ createParser('enum E {}');
+ EnumDeclaration declaration =
+ parser.parseEnumDeclaration(emptyCommentAndMetadata());
+ expectNotNullIfNoErrors(declaration);
+ listener.assertErrorsWithCodes([ParserErrorCode.EMPTY_ENUM_BODY]);
}
void test_enableAsync_false_1() {
parseAsync = false;
- FunctionDeclarationStatement stmt = parse4(
- "parseFunctionDeclarationStatement",
- "foo() async {}",
- [ParserErrorCode.ASYNC_NOT_SUPPORTED]);
- FunctionExpression expr = stmt.functionDeclaration.functionExpression;
+ createParser('foo() async {}');
+ FunctionDeclarationStatement statement =
+ parser.parseFunctionDeclarationStatement();
+ expectNotNullIfNoErrors(statement);
+ listener.assertErrorsWithCodes([ParserErrorCode.ASYNC_NOT_SUPPORTED]);
+ FunctionExpression expr = statement.functionDeclaration.functionExpression;
expect(expr.body.isAsynchronous, isTrue);
expect(expr.body.isGenerator, isFalse);
}
void test_enableAsync_false_2() {
parseAsync = false;
- FunctionDeclarationStatement stmt = parse4(
- "parseFunctionDeclarationStatement",
- "foo() async => 0;",
- [ParserErrorCode.ASYNC_NOT_SUPPORTED]);
- FunctionExpression expr = stmt.functionDeclaration.functionExpression;
+ createParser('foo() async => 0;');
+ FunctionDeclarationStatement statement =
+ parser.parseFunctionDeclarationStatement();
+ expectNotNullIfNoErrors(statement);
+ listener.assertErrorsWithCodes([ParserErrorCode.ASYNC_NOT_SUPPORTED]);
+ FunctionExpression expr = statement.functionDeclaration.functionExpression;
expect(expr.body.isAsynchronous, isTrue);
expect(expr.body.isGenerator, isFalse);
}
void test_enableAsync_false_3() {
parseAsync = false;
- FunctionDeclarationStatement stmt = parse4(
- "parseFunctionDeclarationStatement",
- "foo() sync* {}",
- [ParserErrorCode.ASYNC_NOT_SUPPORTED]);
- FunctionExpression expr = stmt.functionDeclaration.functionExpression;
+ createParser('foo() sync* {}');
+ FunctionDeclarationStatement statement =
+ parser.parseFunctionDeclarationStatement();
+ expectNotNullIfNoErrors(statement);
+ listener.assertErrorsWithCodes([ParserErrorCode.ASYNC_NOT_SUPPORTED]);
+ FunctionExpression expr = statement.functionDeclaration.functionExpression;
expect(expr.body.isAsynchronous, isFalse);
expect(expr.body.isGenerator, isTrue);
}
@@ -988,42 +1105,59 @@
}
void test_expectedCaseOrDefault() {
- parse4("parseSwitchStatement", "switch (e) {break;}",
- [ParserErrorCode.EXPECTED_CASE_OR_DEFAULT]);
+ createParser('switch (e) {break;}');
+ SwitchStatement statement = parser.parseSwitchStatement();
+ expectNotNullIfNoErrors(statement);
+ listener.assertErrorsWithCodes([ParserErrorCode.EXPECTED_CASE_OR_DEFAULT]);
}
void test_expectedClassMember_inClass_afterType() {
- parse3("parseClassMember", <Object>["C"], "heart 2 heart",
- [ParserErrorCode.EXPECTED_CLASS_MEMBER]);
+ createParser('heart 2 heart');
+ ClassMember member = parser.parseClassMember('C');
+ expectNotNullIfNoErrors(member);
+ listener.assertErrorsWithCodes([ParserErrorCode.EXPECTED_CLASS_MEMBER]);
}
void test_expectedClassMember_inClass_beforeType() {
- parse3("parseClassMember", <Object>["C"], "4 score",
- [ParserErrorCode.EXPECTED_CLASS_MEMBER]);
+ createParser('4 score');
+ ClassMember member = parser.parseClassMember('C');
+ expectNotNullIfNoErrors(member);
+ listener.assertErrorsWithCodes([ParserErrorCode.EXPECTED_CLASS_MEMBER]);
}
void test_expectedExecutable_inClass_afterVoid() {
- parse3("parseClassMember", <Object>["C"], "void 2 void",
- [ParserErrorCode.EXPECTED_EXECUTABLE]);
+ createParser('void 2 void');
+ ClassMember member = parser.parseClassMember('C');
+ expectNotNullIfNoErrors(member);
+ listener.assertErrorsWithCodes([ParserErrorCode.EXPECTED_EXECUTABLE]);
}
void test_expectedExecutable_topLevel_afterType() {
- parse3("parseCompilationUnitMember", <Object>[emptyCommentAndMetadata()],
- "heart 2 heart", [ParserErrorCode.EXPECTED_EXECUTABLE]);
+ createParser('heart 2 heart');
+ CompilationUnitMember member =
+ parser.parseCompilationUnitMember(emptyCommentAndMetadata());
+ expectNotNullIfNoErrors(member);
+ listener.assertErrorsWithCodes([ParserErrorCode.EXPECTED_EXECUTABLE]);
}
void test_expectedExecutable_topLevel_afterVoid() {
- parse3("parseCompilationUnitMember", <Object>[emptyCommentAndMetadata()],
- "void 2 void", [ParserErrorCode.EXPECTED_EXECUTABLE]);
+ createParser('void 2 void');
+ CompilationUnitMember member =
+ parser.parseCompilationUnitMember(emptyCommentAndMetadata());
+ expectNotNullIfNoErrors(member);
+ listener.assertErrorsWithCodes([ParserErrorCode.EXPECTED_EXECUTABLE]);
}
void test_expectedExecutable_topLevel_beforeType() {
- parse3("parseCompilationUnitMember", <Object>[emptyCommentAndMetadata()],
- "4 score", [ParserErrorCode.EXPECTED_EXECUTABLE]);
+ createParser('4 score');
+ CompilationUnitMember member =
+ parser.parseCompilationUnitMember(emptyCommentAndMetadata());
+ expectNotNullIfNoErrors(member);
+ listener.assertErrorsWithCodes([ParserErrorCode.EXPECTED_EXECUTABLE]);
}
void test_expectedExecutable_topLevel_eof() {
- parse2(
+ parse(
"parseCompilationUnitMember",
<Object>[emptyCommentAndMetadata()],
"x",
@@ -1031,26 +1165,33 @@
}
void test_expectedInterpolationIdentifier() {
- parse4(
- "parseStringLiteral", "'\$x\$'", [ParserErrorCode.MISSING_IDENTIFIER]);
+ createParser("'\$x\$'");
+ StringLiteral literal = parser.parseStringLiteral();
+ expectNotNullIfNoErrors(literal);
+ listener.assertErrorsWithCodes([ParserErrorCode.MISSING_IDENTIFIER]);
}
void test_expectedInterpolationIdentifier_emptyString() {
// The scanner inserts an empty string token between the two $'s; we need to
// make sure that the MISSING_IDENTIFIER error that is generated has a
// nonzero width so that it will show up in the editor UI.
- parse2("parseStringLiteral", <Object>[], "'\$\$foo'",
+ parse("parseStringLiteral", <Object>[], "'\$\$foo'",
[new AnalysisError(null, 2, 1, ParserErrorCode.MISSING_IDENTIFIER)]);
}
void test_expectedStringLiteral() {
- StringLiteral expression = parse4(
- "parseStringLiteral", "1", [ParserErrorCode.EXPECTED_STRING_LITERAL]);
- expect(expression.isSynthetic, isTrue);
+ createParser('1');
+ StringLiteral literal = parser.parseStringLiteral();
+ expectNotNullIfNoErrors(literal);
+ listener.assertErrorsWithCodes([ParserErrorCode.EXPECTED_STRING_LITERAL]);
+ expect(literal.isSynthetic, isTrue);
}
void test_expectedToken_commaMissingInArgumentList() {
- parse4("parseArgumentList", "(x, y z)", [ParserErrorCode.EXPECTED_TOKEN]);
+ createParser('(x, y z)');
+ ArgumentList list = parser.parseArgumentList();
+ expectNotNullIfNoErrors(list);
+ listener.assertErrorsWithCodes([ParserErrorCode.EXPECTED_TOKEN]);
}
void test_expectedToken_parseStatement_afterVoid() {
@@ -1060,11 +1201,11 @@
void test_expectedToken_semicolonAfterClass() {
Token token = TokenFactory.tokenFromKeyword(Keyword.CLASS);
- parse3(
- "parseClassTypeAlias",
- <Object>[emptyCommentAndMetadata(), null, token],
- "A = B with C",
- [ParserErrorCode.EXPECTED_TOKEN]);
+ createParser('A = B with C');
+ ClassTypeAlias declaration =
+ parser.parseClassTypeAlias(emptyCommentAndMetadata(), null, token);
+ expectNotNullIfNoErrors(declaration);
+ listener.assertErrorsWithCodes([ParserErrorCode.EXPECTED_TOKEN]);
}
void test_expectedToken_semicolonMissingAfterExport() {
@@ -1104,18 +1245,24 @@
}
void test_externalAfterConst() {
- parse3("parseClassMember", <Object>["C"], "const external C();",
- [ParserErrorCode.EXTERNAL_AFTER_CONST]);
+ createParser('const external C();');
+ ClassMember member = parser.parseClassMember('C');
+ expectNotNullIfNoErrors(member);
+ listener.assertErrorsWithCodes([ParserErrorCode.EXTERNAL_AFTER_CONST]);
}
void test_externalAfterFactory() {
- parse3("parseClassMember", <Object>["C"], "factory external C();",
- [ParserErrorCode.EXTERNAL_AFTER_FACTORY]);
+ createParser('factory external C();');
+ ClassMember member = parser.parseClassMember('C');
+ expectNotNullIfNoErrors(member);
+ listener.assertErrorsWithCodes([ParserErrorCode.EXTERNAL_AFTER_FACTORY]);
}
void test_externalAfterStatic() {
- parse3("parseClassMember", <Object>["C"], "static external int m();",
- [ParserErrorCode.EXTERNAL_AFTER_STATIC]);
+ createParser('static external int m();');
+ ClassMember member = parser.parseClassMember('C');
+ expectNotNullIfNoErrors(member);
+ listener.assertErrorsWithCodes([ParserErrorCode.EXTERNAL_AFTER_STATIC]);
}
void test_externalClass() {
@@ -1124,12 +1271,18 @@
}
void test_externalConstructorWithBody_factory() {
- parse3("parseClassMember", <Object>["C"], "external factory C() {}",
+ createParser('external factory C() {}');
+ ClassMember member = parser.parseClassMember('C');
+ expectNotNullIfNoErrors(member);
+ listener.assertErrorsWithCodes(
[ParserErrorCode.EXTERNAL_CONSTRUCTOR_WITH_BODY]);
}
void test_externalConstructorWithBody_named() {
- parse3("parseClassMember", <Object>["C"], "external C.c() {}",
+ createParser('external C.c() {}');
+ ClassMember member = parser.parseClassMember('C');
+ expectNotNullIfNoErrors(member);
+ listener.assertErrorsWithCodes(
[ParserErrorCode.EXTERNAL_CONSTRUCTOR_WITH_BODY]);
}
@@ -1139,51 +1292,67 @@
}
void test_externalField_const() {
- parse3("parseClassMember", <Object>["C"], "external const A f;",
- [ParserErrorCode.EXTERNAL_FIELD]);
+ createParser('external const A f;');
+ ClassMember member = parser.parseClassMember('C');
+ expectNotNullIfNoErrors(member);
+ listener.assertErrorsWithCodes([ParserErrorCode.EXTERNAL_FIELD]);
}
void test_externalField_final() {
- parse3("parseClassMember", <Object>["C"], "external final A f;",
- [ParserErrorCode.EXTERNAL_FIELD]);
+ createParser('external final A f;');
+ ClassMember member = parser.parseClassMember('C');
+ expectNotNullIfNoErrors(member);
+ listener.assertErrorsWithCodes([ParserErrorCode.EXTERNAL_FIELD]);
}
void test_externalField_static() {
- parse3("parseClassMember", <Object>["C"], "external static A f;",
- [ParserErrorCode.EXTERNAL_FIELD]);
+ createParser('external static A f;');
+ ClassMember member = parser.parseClassMember('C');
+ expectNotNullIfNoErrors(member);
+ listener.assertErrorsWithCodes([ParserErrorCode.EXTERNAL_FIELD]);
}
void test_externalField_typed() {
- parse3("parseClassMember", <Object>["C"], "external A f;",
- [ParserErrorCode.EXTERNAL_FIELD]);
+ createParser('external A f;');
+ ClassMember member = parser.parseClassMember('C');
+ expectNotNullIfNoErrors(member);
+ listener.assertErrorsWithCodes([ParserErrorCode.EXTERNAL_FIELD]);
}
void test_externalField_untyped() {
- parse3("parseClassMember", <Object>["C"], "external var f;",
- [ParserErrorCode.EXTERNAL_FIELD]);
+ createParser('external var f;');
+ ClassMember member = parser.parseClassMember('C');
+ expectNotNullIfNoErrors(member);
+ listener.assertErrorsWithCodes([ParserErrorCode.EXTERNAL_FIELD]);
}
void test_externalGetterWithBody() {
- parse3("parseClassMember", <Object>["C"], "external int get x {}",
- [ParserErrorCode.EXTERNAL_GETTER_WITH_BODY]);
+ createParser('external int get x {}');
+ ClassMember member = parser.parseClassMember('C');
+ expectNotNullIfNoErrors(member);
+ listener.assertErrorsWithCodes([ParserErrorCode.EXTERNAL_GETTER_WITH_BODY]);
}
void test_externalMethodWithBody() {
- parse3("parseClassMember", <Object>["C"], "external m() {}",
- [ParserErrorCode.EXTERNAL_METHOD_WITH_BODY]);
+ createParser('external m() {}');
+ ClassMember member = parser.parseClassMember('C');
+ expectNotNullIfNoErrors(member);
+ listener.assertErrorsWithCodes([ParserErrorCode.EXTERNAL_METHOD_WITH_BODY]);
}
void test_externalOperatorWithBody() {
- parse3(
- "parseClassMember",
- <Object>["C"],
- "external operator +(int value) {}",
- [ParserErrorCode.EXTERNAL_OPERATOR_WITH_BODY]);
+ createParser('external operator +(int value) {}');
+ ClassMember member = parser.parseClassMember('C');
+ expectNotNullIfNoErrors(member);
+ listener
+ .assertErrorsWithCodes([ParserErrorCode.EXTERNAL_OPERATOR_WITH_BODY]);
}
void test_externalSetterWithBody() {
- parse3("parseClassMember", <Object>["C"], "external set x(int value) {}",
- [ParserErrorCode.EXTERNAL_SETTER_WITH_BODY]);
+ createParser('external set x(int value) {}');
+ ClassMember member = parser.parseClassMember('C');
+ expectNotNullIfNoErrors(member);
+ listener.assertErrorsWithCodes([ParserErrorCode.EXTERNAL_SETTER_WITH_BODY]);
}
void test_externalTypedef() {
@@ -1192,27 +1361,38 @@
}
void test_extraCommaInParameterList() {
- parse4("parseFormalParameterList", "(int a, , int b)",
+ createParser('(int a, , int b)');
+ FormalParameterList list = parser.parseFormalParameterList();
+ expectNotNullIfNoErrors(list);
+ listener.assertErrorsWithCodes(
[ParserErrorCode.MISSING_IDENTIFIER, ParserErrorCode.EXPECTED_TOKEN]);
}
void test_extraCommaTrailingNamedParameterGroup() {
- parse4("parseFormalParameterList", "({int b},)", [
+ createParser('({int b},)');
+ FormalParameterList list = parser.parseFormalParameterList();
+ expectNotNullIfNoErrors(list);
+ listener.assertErrorsWithCodes([
ParserErrorCode.MISSING_IDENTIFIER,
ParserErrorCode.NORMAL_BEFORE_OPTIONAL_PARAMETERS
]);
}
void test_extraCommaTrailingPositionalParameterGroup() {
- parse4("parseFormalParameterList", "([int b],)", [
+ createParser('([int b],)');
+ FormalParameterList list = parser.parseFormalParameterList();
+ expectNotNullIfNoErrors(list);
+ listener.assertErrorsWithCodes([
ParserErrorCode.MISSING_IDENTIFIER,
ParserErrorCode.NORMAL_BEFORE_OPTIONAL_PARAMETERS
]);
}
void test_extraTrailingCommaInParameterList() {
- parse4("parseFormalParameterList", "(a,,)",
- [ParserErrorCode.MISSING_IDENTIFIER]);
+ createParser('(a,,)');
+ FormalParameterList list = parser.parseFormalParameterList();
+ expectNotNullIfNoErrors(list);
+ listener.assertErrorsWithCodes([ParserErrorCode.MISSING_IDENTIFIER]);
}
void test_factoryTopLevelDeclaration_class() {
@@ -1226,23 +1406,32 @@
}
void test_factoryWithInitializers() {
- parse3("parseClassMember", <Object>["C"], "factory C() : x = 3 {}",
- [ParserErrorCode.FACTORY_WITH_INITIALIZERS]);
+ createParser('factory C() : x = 3 {}');
+ ClassMember member = parser.parseClassMember('C');
+ expectNotNullIfNoErrors(member);
+ listener.assertErrorsWithCodes([ParserErrorCode.FACTORY_WITH_INITIALIZERS]);
}
void test_factoryWithoutBody() {
- parse3("parseClassMember", <Object>["C"], "factory C();",
- [ParserErrorCode.FACTORY_WITHOUT_BODY]);
+ createParser('factory C();');
+ ClassMember member = parser.parseClassMember('C');
+ expectNotNullIfNoErrors(member);
+ listener.assertErrorsWithCodes([ParserErrorCode.FACTORY_WITHOUT_BODY]);
}
void test_fieldInitializerOutsideConstructor() {
- parse3("parseClassMember", <Object>["C"], "void m(this.x);",
+ createParser('void m(this.x);');
+ ClassMember member = parser.parseClassMember('C');
+ expectNotNullIfNoErrors(member);
+ listener.assertErrorsWithCodes(
[ParserErrorCode.FIELD_INITIALIZER_OUTSIDE_CONSTRUCTOR]);
}
void test_finalAndVar() {
- parse3("parseClassMember", <Object>["C"], "final var x;",
- [ParserErrorCode.FINAL_AND_VAR]);
+ createParser('final var x;');
+ ClassMember member = parser.parseClassMember('C');
+ expectNotNullIfNoErrors(member);
+ listener.assertErrorsWithCodes([ParserErrorCode.FINAL_AND_VAR]);
}
void test_finalClass() {
@@ -1251,8 +1440,10 @@
}
void test_finalConstructor() {
- parse3("parseClassMember", <Object>["C"], "final C() {}",
- [ParserErrorCode.FINAL_CONSTRUCTOR]);
+ createParser('final C() {}');
+ ClassMember member = parser.parseClassMember('C');
+ expectNotNullIfNoErrors(member);
+ listener.assertErrorsWithCodes([ParserErrorCode.FINAL_CONSTRUCTOR]);
}
void test_finalEnum() {
@@ -1261,8 +1452,10 @@
}
void test_finalMethod() {
- parse3("parseClassMember", <Object>["C"], "final int m() {}",
- [ParserErrorCode.FINAL_METHOD]);
+ createParser('final int m() {}');
+ ClassMember member = parser.parseClassMember('C');
+ expectNotNullIfNoErrors(member);
+ listener.assertErrorsWithCodes([ParserErrorCode.FINAL_METHOD]);
}
void test_finalTypedef() {
@@ -1307,8 +1500,10 @@
}
void test_getterWithParameters() {
- parse3("parseClassMember", <Object>["C"], "int get x() {}",
- [ParserErrorCode.GETTER_WITH_PARAMETERS]);
+ createParser('int get x() {}');
+ ClassMember member = parser.parseClassMember('C');
+ expectNotNullIfNoErrors(member);
+ listener.assertErrorsWithCodes([ParserErrorCode.GETTER_WITH_PARAMETERS]);
}
void test_illegalAssignmentToNonAssignable_postfix_minusMinus_literal() {
@@ -1360,96 +1555,141 @@
}
void test_initializedVariableInForEach() {
- parse4("parseForStatement", "for (int a = 0 in foo) {}",
+ createParser('for (int a = 0 in foo) {}');
+ Statement statement = parser.parseForStatement();
+ expectNotNullIfNoErrors(statement);
+ listener.assertErrorsWithCodes(
[ParserErrorCode.INITIALIZED_VARIABLE_IN_FOR_EACH]);
}
void test_invalidAwaitInFor() {
- parse4("parseForStatement", "await for (; ;) {}",
- [ParserErrorCode.INVALID_AWAIT_IN_FOR]);
+ createParser('await for (; ;) {}');
+ Statement statement = parser.parseForStatement();
+ expectNotNullIfNoErrors(statement);
+ listener.assertErrorsWithCodes([ParserErrorCode.INVALID_AWAIT_IN_FOR]);
}
void test_invalidCodePoint() {
- parse4("parseStringLiteral", "'\\uD900'",
- [ParserErrorCode.INVALID_CODE_POINT]);
+ createParser("'\\uD900'");
+ StringLiteral literal = parser.parseStringLiteral();
+ expectNotNullIfNoErrors(literal);
+ listener.assertErrorsWithCodes([ParserErrorCode.INVALID_CODE_POINT]);
}
void test_invalidHexEscape_invalidDigit() {
- parse4(
- "parseStringLiteral", "'\\x0 a'", [ParserErrorCode.INVALID_HEX_ESCAPE]);
+ createParser("'\\x0 a'");
+ StringLiteral literal = parser.parseStringLiteral();
+ expectNotNullIfNoErrors(literal);
+ listener.assertErrorsWithCodes([ParserErrorCode.INVALID_HEX_ESCAPE]);
}
void test_invalidHexEscape_tooFewDigits() {
- parse4(
- "parseStringLiteral", "'\\x0'", [ParserErrorCode.INVALID_HEX_ESCAPE]);
+ createParser("'\\x0'");
+ StringLiteral literal = parser.parseStringLiteral();
+ expectNotNullIfNoErrors(literal);
+ listener.assertErrorsWithCodes([ParserErrorCode.INVALID_HEX_ESCAPE]);
}
void test_invalidInterpolationIdentifier_startWithDigit() {
- parse4("parseStringLiteral", "'\$1'", [ParserErrorCode.MISSING_IDENTIFIER]);
+ createParser("'\$1'");
+ StringLiteral literal = parser.parseStringLiteral();
+ expectNotNullIfNoErrors(literal);
+ listener.assertErrorsWithCodes([ParserErrorCode.MISSING_IDENTIFIER]);
}
void test_invalidLiteralInConfiguration() {
- parse4("parseConfiguration", "if (a == 'x \$y z') 'a.dart'",
+ createParser("if (a == 'x \$y z') 'a.dart'");
+ Configuration configuration = parser.parseConfiguration();
+ expectNotNullIfNoErrors(configuration);
+ listener.assertErrorsWithCodes(
[ParserErrorCode.INVALID_LITERAL_IN_CONFIGURATION]);
}
void test_invalidOperator() {
- parse3("parseClassMember", <Object>["C"], "void operator ===(x) {}",
- [ParserErrorCode.INVALID_OPERATOR]);
+ createParser('void operator ===(x) {}');
+ ClassMember member = parser.parseClassMember('C');
+ expectNotNullIfNoErrors(member);
+ listener.assertErrorsWithCodes([ParserErrorCode.INVALID_OPERATOR]);
}
void test_invalidOperatorAfterSuper_assignableExpression() {
- parse3('parseAssignableExpression', <Object>[false], 'super?.v',
- [ParserErrorCode.INVALID_OPERATOR_FOR_SUPER]);
+ createParser('super?.v');
+ Expression expression = parser.parseAssignableExpression(false);
+ expectNotNullIfNoErrors(expression);
+ listener
+ .assertErrorsWithCodes([ParserErrorCode.INVALID_OPERATOR_FOR_SUPER]);
}
void test_invalidOperatorAfterSuper_primaryExpression() {
- parse4('parsePrimaryExpression', 'super?.v',
- [ParserErrorCode.INVALID_OPERATOR_FOR_SUPER]);
+ createParser('super?.v');
+ Expression expression = parser.parsePrimaryExpression();
+ expectNotNullIfNoErrors(expression);
+ listener
+ .assertErrorsWithCodes([ParserErrorCode.INVALID_OPERATOR_FOR_SUPER]);
}
void test_invalidOperatorForSuper() {
- parse4("parseUnaryExpression", "++super",
- [ParserErrorCode.INVALID_OPERATOR_FOR_SUPER]);
+ createParser('++super');
+ Expression expression = parser.parseUnaryExpression();
+ expectNotNullIfNoErrors(expression);
+ listener
+ .assertErrorsWithCodes([ParserErrorCode.INVALID_OPERATOR_FOR_SUPER]);
}
void test_invalidStarAfterAsync() {
- parse3("parseFunctionBody", <Object>[false, null, false], "async* => 0;",
- [ParserErrorCode.INVALID_STAR_AFTER_ASYNC]);
+ createParser('async* => 0;');
+ FunctionBody functionBody = parser.parseFunctionBody(false, null, false);
+ expectNotNullIfNoErrors(functionBody);
+ listener.assertErrorsWithCodes([ParserErrorCode.INVALID_STAR_AFTER_ASYNC]);
}
void test_invalidSync() {
- parse3("parseFunctionBody", <Object>[false, null, false], "sync* => 0;",
- [ParserErrorCode.INVALID_SYNC]);
+ createParser('sync* => 0;');
+ FunctionBody functionBody = parser.parseFunctionBody(false, null, false);
+ expectNotNullIfNoErrors(functionBody);
+ listener.assertErrorsWithCodes([ParserErrorCode.INVALID_SYNC]);
}
void test_invalidUnicodeEscape_incomplete_noDigits() {
- parse4("parseStringLiteral", "'\\u{'",
- [ParserErrorCode.INVALID_UNICODE_ESCAPE]);
+ createParser("'\\u{'");
+ Expression expression = parser.parseStringLiteral();
+ expectNotNullIfNoErrors(expression);
+ listener.assertErrorsWithCodes([ParserErrorCode.INVALID_UNICODE_ESCAPE]);
}
void test_invalidUnicodeEscape_incomplete_someDigits() {
- parse4("parseStringLiteral", "'\\u{0A'",
- [ParserErrorCode.INVALID_UNICODE_ESCAPE]);
+ createParser("'\\u{0A'");
+ Expression expression = parser.parseStringLiteral();
+ expectNotNullIfNoErrors(expression);
+ listener.assertErrorsWithCodes([ParserErrorCode.INVALID_UNICODE_ESCAPE]);
}
void test_invalidUnicodeEscape_invalidDigit() {
- parse4("parseStringLiteral", "'\\u0 a'",
- [ParserErrorCode.INVALID_UNICODE_ESCAPE]);
+ createParser("'\\u0 a'");
+ Expression expression = parser.parseStringLiteral();
+ expectNotNullIfNoErrors(expression);
+ listener.assertErrorsWithCodes([ParserErrorCode.INVALID_UNICODE_ESCAPE]);
}
void test_invalidUnicodeEscape_tooFewDigits_fixed() {
- parse4("parseStringLiteral", "'\\u04'",
- [ParserErrorCode.INVALID_UNICODE_ESCAPE]);
+ createParser("'\\u04'");
+ Expression expression = parser.parseStringLiteral();
+ expectNotNullIfNoErrors(expression);
+ listener.assertErrorsWithCodes([ParserErrorCode.INVALID_UNICODE_ESCAPE]);
}
void test_invalidUnicodeEscape_tooFewDigits_variable() {
- parse4("parseStringLiteral", "'\\u{}'",
- [ParserErrorCode.INVALID_UNICODE_ESCAPE]);
+ createParser("'\\u{}'");
+ Expression expression = parser.parseStringLiteral();
+ expectNotNullIfNoErrors(expression);
+ listener.assertErrorsWithCodes([ParserErrorCode.INVALID_UNICODE_ESCAPE]);
}
void test_invalidUnicodeEscape_tooManyDigits_variable() {
- parse4("parseStringLiteral", "'\\u{12345678}'", [
+ createParser("'\\u{12345678}'");
+ Expression expression = parser.parseStringLiteral();
+ expectNotNullIfNoErrors(expression);
+ listener.assertErrorsWithCodes([
ParserErrorCode.INVALID_UNICODE_ESCAPE,
ParserErrorCode.INVALID_CODE_POINT
]);
@@ -1489,17 +1729,18 @@
void test_method_invalidTypeParameterComments() {
enableGenericMethodComments = true;
- MethodDeclaration method = parse3(
- "parseClassMember",
- <Object>["C"],
- "void m/*<E, hello!>*/() {}",
- [
- ParserErrorCode.EXPECTED_TOKEN /*>*/,
- ParserErrorCode.MISSING_IDENTIFIER,
- ParserErrorCode.EXPECTED_TOKEN /*(*/,
- ParserErrorCode.EXPECTED_TOKEN /*)*/,
- ParserErrorCode.MISSING_FUNCTION_BODY
- ]);
+ createParser('void m/*<E, hello!>*/() {}');
+ ClassMember member = parser.parseClassMember('C');
+ expectNotNullIfNoErrors(member);
+ listener.assertErrorsWithCodes([
+ ParserErrorCode.EXPECTED_TOKEN /*>*/,
+ ParserErrorCode.MISSING_IDENTIFIER,
+ ParserErrorCode.EXPECTED_TOKEN /*(*/,
+ ParserErrorCode.EXPECTED_TOKEN /*)*/,
+ ParserErrorCode.MISSING_FUNCTION_BODY
+ ]);
+ expect(member, new isInstanceOf<MethodDeclaration>());
+ MethodDeclaration method = member;
expect(method.typeParameters.toString(), '<E, hello>',
reason: 'parser recovers what it can');
}
@@ -1509,16 +1750,17 @@
// TODO(jmesserly): ideally we'd be better at parser recovery here.
enableGenericMethods = true;
- MethodDeclaration method = parse3(
- "parseClassMember",
- <Object>["C"],
- "f<E>(E extends num p);",
- [
- ParserErrorCode.MISSING_IDENTIFIER, // `extends` is a keyword
- ParserErrorCode.EXPECTED_TOKEN, // comma
- ParserErrorCode.EXPECTED_TOKEN, // close paren
- ParserErrorCode.MISSING_FUNCTION_BODY
- ]);
+ createParser('f<E>(E extends num p);');
+ ClassMember member = parser.parseClassMember('C');
+ expectNotNullIfNoErrors(member);
+ listener.assertErrorsWithCodes([
+ ParserErrorCode.MISSING_IDENTIFIER, // `extends` is a keyword
+ ParserErrorCode.EXPECTED_TOKEN, // comma
+ ParserErrorCode.EXPECTED_TOKEN, // close paren
+ ParserErrorCode.MISSING_FUNCTION_BODY
+ ]);
+ expect(member, new isInstanceOf<MethodDeclaration>());
+ MethodDeclaration method = member;
expect(method.parameters.toString(), '(E, extends)',
reason: 'parser recovers what it can');
}
@@ -1532,17 +1774,18 @@
// point in the parser. This has a slight effect on the AST that results
// from error recovery.
enableGenericMethodComments = true;
- MethodDeclaration method = parse3(
- "parseClassMember",
- <Object>["C"],
- "f/*<E>*/(dynamic/*=E extends num*/p);",
- [
- ParserErrorCode.MISSING_IDENTIFIER, // `extends` is a keyword
- ParserErrorCode.EXPECTED_TOKEN, // comma
- ParserErrorCode.MISSING_IDENTIFIER, // `extends` is a keyword
- ParserErrorCode.EXPECTED_TOKEN, // close paren
- ParserErrorCode.MISSING_FUNCTION_BODY
- ]);
+ createParser('f/*<E>*/(dynamic/*=E extends num*/p);');
+ ClassMember member = parser.parseClassMember('C');
+ expectNotNullIfNoErrors(member);
+ listener.assertErrorsWithCodes([
+ ParserErrorCode.MISSING_IDENTIFIER, // `extends` is a keyword
+ ParserErrorCode.EXPECTED_TOKEN, // comma
+ ParserErrorCode.MISSING_IDENTIFIER, // `extends` is a keyword
+ ParserErrorCode.EXPECTED_TOKEN, // close paren
+ ParserErrorCode.MISSING_FUNCTION_BODY
+ ]);
+ expect(member, new isInstanceOf<MethodDeclaration>());
+ MethodDeclaration method = member;
expect(method.parameters.toString(), '(E extends, extends)',
reason: 'parser recovers what it can');
}
@@ -1553,17 +1796,18 @@
// valid `>`. If it did we'd get less cascading errors, at least for this
// particular example.
enableGenericMethods = true;
- MethodDeclaration method = parse3(
- "parseClassMember",
- <Object>["C"],
- "void m<E, hello!>() {}",
- [
- ParserErrorCode.EXPECTED_TOKEN /*>*/,
- ParserErrorCode.MISSING_IDENTIFIER,
- ParserErrorCode.EXPECTED_TOKEN /*(*/,
- ParserErrorCode.EXPECTED_TOKEN /*)*/,
- ParserErrorCode.MISSING_FUNCTION_BODY
- ]);
+ createParser('void m<E, hello!>() {}');
+ ClassMember member = parser.parseClassMember('C');
+ expectNotNullIfNoErrors(member);
+ listener.assertErrorsWithCodes([
+ ParserErrorCode.EXPECTED_TOKEN /*>*/,
+ ParserErrorCode.MISSING_IDENTIFIER,
+ ParserErrorCode.EXPECTED_TOKEN /*(*/,
+ ParserErrorCode.EXPECTED_TOKEN /*)*/,
+ ParserErrorCode.MISSING_FUNCTION_BODY
+ ]);
+ expect(member, new isInstanceOf<MethodDeclaration>());
+ MethodDeclaration method = member;
expect(method.typeParameters.toString(), '<E, hello>',
reason: 'parser recovers what it can');
}
@@ -1585,9 +1829,14 @@
}
void test_missingAssignableSelector_superPrimaryExpression() {
- SuperExpression expression = parse4("parsePrimaryExpression", "super",
- [ParserErrorCode.MISSING_ASSIGNABLE_SELECTOR]);
- expect(expression.superKeyword, isNotNull);
+ createParser('super');
+ Expression expression = parser.parsePrimaryExpression();
+ expectNotNullIfNoErrors(expression);
+ listener
+ .assertErrorsWithCodes([ParserErrorCode.MISSING_ASSIGNABLE_SELECTOR]);
+ expect(expression, new isInstanceOf<SuperExpression>());
+ SuperExpression superExpression = expression;
+ expect(superExpression.superKeyword, isNotNull);
}
void test_missingAssignableSelector_superPropertyAccessAssigned() {
@@ -1595,8 +1844,10 @@
}
void test_missingCatchOrFinally() {
- TryStatement statement = parse4("parseTryStatement", "try {}",
- [ParserErrorCode.MISSING_CATCH_OR_FINALLY]);
+ createParser('try {}');
+ TryStatement statement = parser.parseTryStatement();
+ expectNotNullIfNoErrors(statement);
+ listener.assertErrorsWithCodes([ParserErrorCode.MISSING_CATCH_OR_FINALLY]);
expect(statement, isNotNull);
}
@@ -1611,39 +1862,51 @@
}
void test_missingConstFinalVarOrType_topLevel() {
- parse3("parseFinalConstVarOrType", <Object>[false], "a;",
+ createParser('a;');
+ FinalConstVarOrType result = parser.parseFinalConstVarOrType(false);
+ expectNotNullIfNoErrors(result);
+ listener.assertErrorsWithCodes(
[ParserErrorCode.MISSING_CONST_FINAL_VAR_OR_TYPE]);
}
void test_missingEnumBody() {
- parse3("parseEnumDeclaration", <Object>[emptyCommentAndMetadata()],
- "enum E;", [ParserErrorCode.MISSING_ENUM_BODY]);
+ createParser('enum E;');
+ EnumDeclaration declaration =
+ parser.parseEnumDeclaration(emptyCommentAndMetadata());
+ expectNotNullIfNoErrors(declaration);
+ listener.assertErrorsWithCodes([ParserErrorCode.MISSING_ENUM_BODY]);
}
void test_missingExpressionInThrow_withCascade() {
- parse4("parseThrowExpression", "throw;",
- [ParserErrorCode.MISSING_EXPRESSION_IN_THROW]);
+ createParser('throw;');
+ ThrowExpression expression = parser.parseThrowExpression();
+ expectNotNullIfNoErrors(expression);
+ listener
+ .assertErrorsWithCodes([ParserErrorCode.MISSING_EXPRESSION_IN_THROW]);
}
void test_missingExpressionInThrow_withoutCascade() {
- parse4("parseThrowExpressionWithoutCascade", "throw;",
- [ParserErrorCode.MISSING_EXPRESSION_IN_THROW]);
+ createParser('throw;');
+ ThrowExpression expression = parser.parseThrowExpressionWithoutCascade();
+ expectNotNullIfNoErrors(expression);
+ listener
+ .assertErrorsWithCodes([ParserErrorCode.MISSING_EXPRESSION_IN_THROW]);
}
void test_missingFunctionBody_emptyNotAllowed() {
- parse3(
- "parseFunctionBody",
- <Object>[false, ParserErrorCode.MISSING_FUNCTION_BODY, false],
- ";",
- [ParserErrorCode.MISSING_FUNCTION_BODY]);
+ createParser(';');
+ FunctionBody functionBody = parser.parseFunctionBody(
+ false, ParserErrorCode.MISSING_FUNCTION_BODY, false);
+ expectNotNullIfNoErrors(functionBody);
+ listener.assertErrorsWithCodes([ParserErrorCode.MISSING_FUNCTION_BODY]);
}
void test_missingFunctionBody_invalid() {
- parse3(
- "parseFunctionBody",
- <Object>[false, ParserErrorCode.MISSING_FUNCTION_BODY, false],
- "return 0;",
- [ParserErrorCode.MISSING_FUNCTION_BODY]);
+ createParser('return 0;');
+ FunctionBody functionBody = parser.parseFunctionBody(
+ false, ParserErrorCode.MISSING_FUNCTION_BODY, false);
+ expectNotNullIfNoErrors(functionBody);
+ listener.assertErrorsWithCodes([ParserErrorCode.MISSING_FUNCTION_BODY]);
}
void test_missingFunctionParameters_local_void_block() {
@@ -1681,73 +1944,108 @@
}
void test_missingIdentifier_afterOperator() {
- parse4("parseMultiplicativeExpression", "1 *",
- [ParserErrorCode.MISSING_IDENTIFIER]);
+ createParser('1 *');
+ BinaryExpression expression = parser.parseMultiplicativeExpression();
+ expectNotNullIfNoErrors(expression);
+ listener.assertErrorsWithCodes([ParserErrorCode.MISSING_IDENTIFIER]);
}
void test_missingIdentifier_beforeClosingCurly() {
- parse3("parseClassMember", <Object>["C"], "int}",
+ createParser('int}');
+ ClassMember member = parser.parseClassMember('C');
+ expectNotNullIfNoErrors(member);
+ listener.assertErrorsWithCodes(
[ParserErrorCode.MISSING_IDENTIFIER, ParserErrorCode.EXPECTED_TOKEN]);
}
void test_missingIdentifier_functionDeclaration_returnTypeWithoutName() {
- parse4("parseFunctionDeclarationStatement", "A<T> () {}",
- [ParserErrorCode.MISSING_IDENTIFIER]);
+ createParser('A<T> () {}');
+ Statement statement = parser.parseFunctionDeclarationStatement();
+ expectNotNullIfNoErrors(statement);
+ listener.assertErrorsWithCodes([ParserErrorCode.MISSING_IDENTIFIER]);
}
void test_missingIdentifier_inEnum() {
- parse3("parseEnumDeclaration", <Object>[emptyCommentAndMetadata()],
- "enum E {, TWO}", [ParserErrorCode.MISSING_IDENTIFIER]);
+ createParser('enum E {, TWO}');
+ EnumDeclaration declaration =
+ parser.parseEnumDeclaration(emptyCommentAndMetadata());
+ expectNotNullIfNoErrors(declaration);
+ listener.assertErrorsWithCodes([ParserErrorCode.MISSING_IDENTIFIER]);
}
void test_missingIdentifier_inSymbol_afterPeriod() {
- parse4("parseSymbolLiteral", "#a.", [ParserErrorCode.MISSING_IDENTIFIER]);
+ createParser('#a.');
+ SymbolLiteral literal = parser.parseSymbolLiteral();
+ expectNotNullIfNoErrors(literal);
+ listener.assertErrorsWithCodes([ParserErrorCode.MISSING_IDENTIFIER]);
}
void test_missingIdentifier_inSymbol_first() {
- parse4("parseSymbolLiteral", "#", [ParserErrorCode.MISSING_IDENTIFIER]);
+ createParser('#');
+ SymbolLiteral literal = parser.parseSymbolLiteral();
+ expectNotNullIfNoErrors(literal);
+ listener.assertErrorsWithCodes([ParserErrorCode.MISSING_IDENTIFIER]);
}
void test_missingIdentifier_number() {
- SimpleIdentifier expression = parse4(
- "parseSimpleIdentifier", "1", [ParserErrorCode.MISSING_IDENTIFIER]);
+ createParser('1');
+ SimpleIdentifier expression = parser.parseSimpleIdentifier();
+ expectNotNullIfNoErrors(expression);
+ listener.assertErrorsWithCodes([ParserErrorCode.MISSING_IDENTIFIER]);
expect(expression.isSynthetic, isTrue);
}
void test_missingIdentifierForParameterGroup() {
- parse4("parseFormalParameterList", "(,)",
- [ParserErrorCode.MISSING_IDENTIFIER]);
+ createParser('(,)');
+ FormalParameterList list = parser.parseFormalParameterList();
+ expectNotNullIfNoErrors(list);
+ listener.assertErrorsWithCodes([ParserErrorCode.MISSING_IDENTIFIER]);
}
void test_missingKeywordOperator() {
- parse3("parseOperator", <Object>[emptyCommentAndMetadata(), null, null],
- "+(x) {}", [ParserErrorCode.MISSING_KEYWORD_OPERATOR]);
+ createParser('+(x) {}');
+ MethodDeclaration method =
+ parser.parseOperator(emptyCommentAndMetadata(), null, null);
+ expectNotNullIfNoErrors(method);
+ listener.assertErrorsWithCodes([ParserErrorCode.MISSING_KEYWORD_OPERATOR]);
}
void test_missingKeywordOperator_parseClassMember() {
- parse3("parseClassMember", <Object>["C"], "+() {}",
- [ParserErrorCode.MISSING_KEYWORD_OPERATOR]);
+ createParser('+() {}');
+ ClassMember member = parser.parseClassMember('C');
+ expectNotNullIfNoErrors(member);
+ listener.assertErrorsWithCodes([ParserErrorCode.MISSING_KEYWORD_OPERATOR]);
}
void test_missingKeywordOperator_parseClassMember_afterTypeName() {
- parse3("parseClassMember", <Object>["C"], "int +() {}",
- [ParserErrorCode.MISSING_KEYWORD_OPERATOR]);
+ createParser('int +() {}');
+ ClassMember member = parser.parseClassMember('C');
+ expectNotNullIfNoErrors(member);
+ listener.assertErrorsWithCodes([ParserErrorCode.MISSING_KEYWORD_OPERATOR]);
}
void test_missingKeywordOperator_parseClassMember_afterVoid() {
- parse3("parseClassMember", <Object>["C"], "void +() {}",
- [ParserErrorCode.MISSING_KEYWORD_OPERATOR]);
+ createParser('void +() {}');
+ ClassMember member = parser.parseClassMember('C');
+ expectNotNullIfNoErrors(member);
+ listener.assertErrorsWithCodes([ParserErrorCode.MISSING_KEYWORD_OPERATOR]);
}
void test_missingMethodParameters_void_block() {
- MethodDeclaration method = parse3("parseClassMember", <Object>["C"],
- "void m {} }", [ParserErrorCode.MISSING_METHOD_PARAMETERS]);
+ createParser('void m {} }');
+ ClassMember member = parser.parseClassMember('C');
+ expectNotNullIfNoErrors(member);
+ listener.assertErrorsWithCodes([ParserErrorCode.MISSING_METHOD_PARAMETERS]);
+ expect(member, new isInstanceOf<MethodDeclaration>());
+ MethodDeclaration method = member;
expect(method.parameters, hasLength(0));
}
void test_missingMethodParameters_void_expression() {
- parse3("parseClassMember", <Object>["C"], "void m => null; }",
- [ParserErrorCode.MISSING_METHOD_PARAMETERS]);
+ createParser('void m => null; }');
+ ClassMember member = parser.parseClassMember('C');
+ expectNotNullIfNoErrors(member);
+ listener.assertErrorsWithCodes([ParserErrorCode.MISSING_METHOD_PARAMETERS]);
}
void test_missingNameInLibraryDirective() {
@@ -1768,8 +2066,10 @@
}
void test_missingStartAfterSync() {
- parse3("parseFunctionBody", <Object>[false, null, false], "sync {}",
- [ParserErrorCode.MISSING_STAR_AFTER_SYNC]);
+ createParser('sync {}');
+ FunctionBody functionBody = parser.parseFunctionBody(false, null, false);
+ expectNotNullIfNoErrors(functionBody);
+ listener.assertErrorsWithCodes([ParserErrorCode.MISSING_STAR_AFTER_SYNC]);
}
void test_missingStatement() {
@@ -1781,12 +2081,18 @@
}
void test_missingTerminatorForParameterGroup_named() {
- parse4("parseFormalParameterList", "(a, {b: 0)",
+ createParser('(a, {b: 0)');
+ FormalParameterList list = parser.parseFormalParameterList();
+ expectNotNullIfNoErrors(list);
+ listener.assertErrorsWithCodes(
[ParserErrorCode.MISSING_TERMINATOR_FOR_PARAMETER_GROUP]);
}
void test_missingTerminatorForParameterGroup_optional() {
- parse4("parseFormalParameterList", "(a, [b = 0)",
+ createParser('(a, [b = 0)');
+ FormalParameterList list = parser.parseFormalParameterList();
+ expectNotNullIfNoErrors(list);
+ listener.assertErrorsWithCodes(
[ParserErrorCode.MISSING_TERMINATOR_FOR_PARAMETER_GROUP]);
}
@@ -1806,18 +2112,25 @@
}
void test_missingVariableInForEach() {
- parse4("parseForStatement", "for (a < b in foo) {}",
- [ParserErrorCode.MISSING_VARIABLE_IN_FOR_EACH]);
+ createParser('for (a < b in foo) {}');
+ Statement statement = parser.parseForStatement();
+ expectNotNullIfNoErrors(statement);
+ listener
+ .assertErrorsWithCodes([ParserErrorCode.MISSING_VARIABLE_IN_FOR_EACH]);
}
void test_mixedParameterGroups_namedPositional() {
- parse4("parseFormalParameterList", "(a, {b}, [c])",
- [ParserErrorCode.MIXED_PARAMETER_GROUPS]);
+ createParser('(a, {b}, [c])');
+ FormalParameterList list = parser.parseFormalParameterList();
+ expectNotNullIfNoErrors(list);
+ listener.assertErrorsWithCodes([ParserErrorCode.MIXED_PARAMETER_GROUPS]);
}
void test_mixedParameterGroups_positionalNamed() {
- parse4("parseFormalParameterList", "(a, [b], {c})",
- [ParserErrorCode.MIXED_PARAMETER_GROUPS]);
+ createParser('(a, [b], {c})');
+ FormalParameterList list = parser.parseFormalParameterList();
+ expectNotNullIfNoErrors(list);
+ listener.assertErrorsWithCodes([ParserErrorCode.MIXED_PARAMETER_GROUPS]);
}
void test_mixin_application_lacks_with_clause() {
@@ -1841,7 +2154,10 @@
}
void test_multipleNamedParameterGroups() {
- parse4("parseFormalParameterList", "(a, {b}, {c})",
+ createParser('(a, {b}, {c})');
+ FormalParameterList list = parser.parseFormalParameterList();
+ expectNotNullIfNoErrors(list);
+ listener.assertErrorsWithCodes(
[ParserErrorCode.MULTIPLE_NAMED_PARAMETER_GROUPS]);
}
@@ -1851,12 +2167,18 @@
}
void test_multiplePositionalParameterGroups() {
- parse4("parseFormalParameterList", "(a, [b], [c])",
+ createParser('(a, [b], [c])');
+ FormalParameterList list = parser.parseFormalParameterList();
+ expectNotNullIfNoErrors(list);
+ listener.assertErrorsWithCodes(
[ParserErrorCode.MULTIPLE_POSITIONAL_PARAMETER_GROUPS]);
}
void test_multipleVariablesInForEach() {
- parse4("parseForStatement", "for (int a, b in foo) {}",
+ createParser('for (int a, b in foo) {}');
+ Statement statement = parser.parseForStatement();
+ expectNotNullIfNoErrors(statement);
+ listener.assertErrorsWithCodes(
[ParserErrorCode.MULTIPLE_VARIABLES_IN_FOR_EACH]);
}
@@ -1866,18 +2188,25 @@
}
void test_namedParameterOutsideGroup() {
- parse4("parseFormalParameterList", "(a, b : 0)",
- [ParserErrorCode.NAMED_PARAMETER_OUTSIDE_GROUP]);
+ createParser('(a, b : 0)');
+ FormalParameterList list = parser.parseFormalParameterList();
+ expectNotNullIfNoErrors(list);
+ listener
+ .assertErrorsWithCodes([ParserErrorCode.NAMED_PARAMETER_OUTSIDE_GROUP]);
}
void test_nonConstructorFactory_field() {
- parse3("parseClassMember", <Object>["C"], "factory int x;",
- [ParserErrorCode.NON_CONSTRUCTOR_FACTORY]);
+ createParser('factory int x;');
+ ClassMember member = parser.parseClassMember('C');
+ expectNotNullIfNoErrors(member);
+ listener.assertErrorsWithCodes([ParserErrorCode.NON_CONSTRUCTOR_FACTORY]);
}
void test_nonConstructorFactory_method() {
- parse3("parseClassMember", <Object>["C"], "factory int m() {}",
- [ParserErrorCode.NON_CONSTRUCTOR_FACTORY]);
+ createParser('factory int m() {}');
+ ClassMember member = parser.parseClassMember('C');
+ expectNotNullIfNoErrors(member);
+ listener.assertErrorsWithCodes([ParserErrorCode.NON_CONSTRUCTOR_FACTORY]);
}
void test_nonIdentifierLibraryName_library() {
@@ -1903,8 +2232,11 @@
}
void test_nonUserDefinableOperator() {
- parse3("parseClassMember", <Object>["C"], "operator +=(int x) => x + 1;",
- [ParserErrorCode.NON_USER_DEFINABLE_OPERATOR]);
+ createParser('operator +=(int x) => x + 1;');
+ ClassMember member = parser.parseClassMember('C');
+ expectNotNullIfNoErrors(member);
+ listener
+ .assertErrorsWithCodes([ParserErrorCode.NON_USER_DEFINABLE_OPERATOR]);
}
void test_optionalAfterNormalParameters_named() {
@@ -1918,8 +2250,10 @@
}
void test_parseCascadeSection_missingIdentifier() {
- MethodInvocation methodInvocation = parse4(
- "parseCascadeSection", "..()", [ParserErrorCode.MISSING_IDENTIFIER]);
+ createParser('..()');
+ MethodInvocation methodInvocation = parser.parseCascadeSection();
+ expectNotNullIfNoErrors(methodInvocation);
+ listener.assertErrorsWithCodes([ParserErrorCode.MISSING_IDENTIFIER]);
expect(methodInvocation.target, isNull);
expect(methodInvocation.methodName.name, "");
expect(methodInvocation.typeArguments, isNull);
@@ -1928,8 +2262,10 @@
void test_parseCascadeSection_missingIdentifier_typeArguments() {
enableGenericMethods = true;
- MethodInvocation methodInvocation = parse4(
- "parseCascadeSection", "..<E>()", [ParserErrorCode.MISSING_IDENTIFIER]);
+ createParser('..<E>()');
+ MethodInvocation methodInvocation = parser.parseCascadeSection();
+ expectNotNullIfNoErrors(methodInvocation);
+ listener.assertErrorsWithCodes([ParserErrorCode.MISSING_IDENTIFIER]);
expect(methodInvocation.target, isNull);
expect(methodInvocation.methodName.name, "");
expect(methodInvocation.typeArguments, isNotNull);
@@ -1937,27 +2273,42 @@
}
void test_positionalAfterNamedArgument() {
- parse4("parseArgumentList", "(x: 1, 2)",
+ createParser('(x: 1, 2)');
+ ArgumentList list = parser.parseArgumentList();
+ expectNotNullIfNoErrors(list);
+ listener.assertErrorsWithCodes(
[ParserErrorCode.POSITIONAL_AFTER_NAMED_ARGUMENT]);
}
void test_positionalParameterOutsideGroup() {
- parse4("parseFormalParameterList", "(a, b = 0)",
+ createParser('(a, b = 0)');
+ FormalParameterList list = parser.parseFormalParameterList();
+ expectNotNullIfNoErrors(list);
+ listener.assertErrorsWithCodes(
[ParserErrorCode.POSITIONAL_PARAMETER_OUTSIDE_GROUP]);
}
void test_redirectingConstructorWithBody_named() {
- parse3("parseClassMember", <Object>["C"], "C.x() : this() {}",
+ createParser('C.x() : this() {}');
+ ClassMember member = parser.parseClassMember('C');
+ expectNotNullIfNoErrors(member);
+ listener.assertErrorsWithCodes(
[ParserErrorCode.REDIRECTING_CONSTRUCTOR_WITH_BODY]);
}
void test_redirectingConstructorWithBody_unnamed() {
- parse3("parseClassMember", <Object>["C"], "C() : this.x() {}",
+ createParser('C() : this.x() {}');
+ ClassMember member = parser.parseClassMember('C');
+ expectNotNullIfNoErrors(member);
+ listener.assertErrorsWithCodes(
[ParserErrorCode.REDIRECTING_CONSTRUCTOR_WITH_BODY]);
}
void test_redirectionInNonFactoryConstructor() {
- parse3("parseClassMember", <Object>["C"], "C() = D;",
+ createParser('C() = D;');
+ ClassMember member = parser.parseClassMember('C');
+ expectNotNullIfNoErrors(member);
+ listener.assertErrorsWithCodes(
[ParserErrorCode.REDIRECTION_IN_NON_FACTORY_CONSTRUCTOR]);
}
@@ -1972,49 +2323,61 @@
}
void test_staticAfterConst() {
- parse3("parseClassMember", <Object>["C"], "final static int f;",
- [ParserErrorCode.STATIC_AFTER_FINAL]);
+ createParser('final static int f;');
+ ClassMember member = parser.parseClassMember('C');
+ expectNotNullIfNoErrors(member);
+ listener.assertErrorsWithCodes([ParserErrorCode.STATIC_AFTER_FINAL]);
}
void test_staticAfterFinal() {
- parse3("parseClassMember", <Object>["C"], "const static int f;",
- [ParserErrorCode.STATIC_AFTER_CONST]);
+ createParser('const static int f;');
+ ClassMember member = parser.parseClassMember('C');
+ expectNotNullIfNoErrors(member);
+ listener.assertErrorsWithCodes([ParserErrorCode.STATIC_AFTER_CONST]);
}
void test_staticAfterVar() {
- parse3("parseClassMember", <Object>["C"], "var static f;",
- [ParserErrorCode.STATIC_AFTER_VAR]);
+ createParser('var static f;');
+ ClassMember member = parser.parseClassMember('C');
+ expectNotNullIfNoErrors(member);
+ listener.assertErrorsWithCodes([ParserErrorCode.STATIC_AFTER_VAR]);
}
void test_staticConstructor() {
- parse3("parseClassMember", <Object>["C"], "static C.m() {}",
- [ParserErrorCode.STATIC_CONSTRUCTOR]);
+ createParser('static C.m() {}');
+ ClassMember member = parser.parseClassMember('C');
+ expectNotNullIfNoErrors(member);
+ listener.assertErrorsWithCodes([ParserErrorCode.STATIC_CONSTRUCTOR]);
}
void test_staticGetterWithoutBody() {
- parse3("parseClassMember", <Object>["C"], "static get m;",
- [ParserErrorCode.STATIC_GETTER_WITHOUT_BODY]);
+ createParser('static get m;');
+ ClassMember member = parser.parseClassMember('C');
+ expectNotNullIfNoErrors(member);
+ listener
+ .assertErrorsWithCodes([ParserErrorCode.STATIC_GETTER_WITHOUT_BODY]);
}
void test_staticOperator_noReturnType() {
- parse3(
- "parseClassMember",
- <Object>["C"],
- "static operator +(int x) => x + 1;",
- [ParserErrorCode.STATIC_OPERATOR]);
+ createParser('static operator +(int x) => x + 1;');
+ ClassMember member = parser.parseClassMember('C');
+ expectNotNullIfNoErrors(member);
+ listener.assertErrorsWithCodes([ParserErrorCode.STATIC_OPERATOR]);
}
void test_staticOperator_returnType() {
- parse3(
- "parseClassMember",
- <Object>["C"],
- "static int operator +(int x) => x + 1;",
- [ParserErrorCode.STATIC_OPERATOR]);
+ createParser('static int operator +(int x) => x + 1;');
+ ClassMember member = parser.parseClassMember('C');
+ expectNotNullIfNoErrors(member);
+ listener.assertErrorsWithCodes([ParserErrorCode.STATIC_OPERATOR]);
}
void test_staticSetterWithoutBody() {
- parse3("parseClassMember", <Object>["C"], "static set m(x);",
- [ParserErrorCode.STATIC_SETTER_WITHOUT_BODY]);
+ createParser('static set m(x);');
+ ClassMember member = parser.parseClassMember('C');
+ expectNotNullIfNoErrors(member);
+ listener
+ .assertErrorsWithCodes([ParserErrorCode.STATIC_SETTER_WITHOUT_BODY]);
}
void test_staticTopLevelDeclaration_class() {
@@ -2056,65 +2419,76 @@
}
void test_switchHasCaseAfterDefaultCase() {
- parse4(
- "parseSwitchStatement",
- "switch (a) {default: return 0; case 1: return 1;}",
+ createParser('switch (a) {default: return 0; case 1: return 1;}');
+ SwitchStatement statement = parser.parseSwitchStatement();
+ expectNotNullIfNoErrors(statement);
+ listener.assertErrorsWithCodes(
[ParserErrorCode.SWITCH_HAS_CASE_AFTER_DEFAULT_CASE]);
}
void test_switchHasCaseAfterDefaultCase_repeated() {
- parse4("parseSwitchStatement",
- "switch (a) {default: return 0; case 1: return 1; case 2: return 2;}", [
+ createParser(
+ 'switch (a) {default: return 0; case 1: return 1; case 2: return 2;}');
+ SwitchStatement statement = parser.parseSwitchStatement();
+ expectNotNullIfNoErrors(statement);
+ listener.assertErrorsWithCodes([
ParserErrorCode.SWITCH_HAS_CASE_AFTER_DEFAULT_CASE,
ParserErrorCode.SWITCH_HAS_CASE_AFTER_DEFAULT_CASE
]);
}
void test_switchHasMultipleDefaultCases() {
- parse4(
- "parseSwitchStatement",
- "switch (a) {default: return 0; default: return 1;}",
+ createParser('switch (a) {default: return 0; default: return 1;}');
+ SwitchStatement statement = parser.parseSwitchStatement();
+ expectNotNullIfNoErrors(statement);
+ listener.assertErrorsWithCodes(
[ParserErrorCode.SWITCH_HAS_MULTIPLE_DEFAULT_CASES]);
}
void test_switchHasMultipleDefaultCases_repeated() {
- parse4(
- "parseSwitchStatement",
- "switch (a) {default: return 0; default: return 1; default: return 2;}",
- [
- ParserErrorCode.SWITCH_HAS_MULTIPLE_DEFAULT_CASES,
- ParserErrorCode.SWITCH_HAS_MULTIPLE_DEFAULT_CASES
- ]);
+ createParser(
+ 'switch (a) {default: return 0; default: return 1; default: return 2;}');
+ SwitchStatement statement = parser.parseSwitchStatement();
+ expectNotNullIfNoErrors(statement);
+ listener.assertErrorsWithCodes([
+ ParserErrorCode.SWITCH_HAS_MULTIPLE_DEFAULT_CASES,
+ ParserErrorCode.SWITCH_HAS_MULTIPLE_DEFAULT_CASES
+ ]);
}
void test_topLevel_getter() {
- FunctionDeclaration funct = parse3("parseCompilationUnitMember",
- <Object>[emptyCommentAndMetadata()], "get x => 7;");
- expect(funct.functionExpression.parameters, isNull);
+ createParser('get x => 7;');
+ CompilationUnitMember member =
+ parser.parseCompilationUnitMember(emptyCommentAndMetadata());
+ expectNotNullIfNoErrors(member);
+ listener.assertNoErrors();
+ expect(member, new isInstanceOf<FunctionDeclaration>());
+ FunctionDeclaration function = member;
+ expect(function.functionExpression.parameters, isNull);
}
void test_topLevelOperator_withoutType() {
- parse3(
- "parseCompilationUnitMember",
- <Object>[emptyCommentAndMetadata()],
- "operator +(bool x, bool y) => x | y;",
- [ParserErrorCode.TOP_LEVEL_OPERATOR]);
+ createParser('operator +(bool x, bool y) => x | y;');
+ CompilationUnitMember member =
+ parser.parseCompilationUnitMember(emptyCommentAndMetadata());
+ expectNotNullIfNoErrors(member);
+ listener.assertErrorsWithCodes([ParserErrorCode.TOP_LEVEL_OPERATOR]);
}
void test_topLevelOperator_withType() {
- parse3(
- "parseCompilationUnitMember",
- <Object>[emptyCommentAndMetadata()],
- "bool operator +(bool x, bool y) => x | y;",
- [ParserErrorCode.TOP_LEVEL_OPERATOR]);
+ createParser('bool operator +(bool x, bool y) => x | y;');
+ CompilationUnitMember member =
+ parser.parseCompilationUnitMember(emptyCommentAndMetadata());
+ expectNotNullIfNoErrors(member);
+ listener.assertErrorsWithCodes([ParserErrorCode.TOP_LEVEL_OPERATOR]);
}
void test_topLevelOperator_withVoid() {
- parse3(
- "parseCompilationUnitMember",
- <Object>[emptyCommentAndMetadata()],
- "void operator +(bool x, bool y) => x | y;",
- [ParserErrorCode.TOP_LEVEL_OPERATOR]);
+ createParser('void operator +(bool x, bool y) => x | y;');
+ CompilationUnitMember member =
+ parser.parseCompilationUnitMember(emptyCommentAndMetadata());
+ expectNotNullIfNoErrors(member);
+ listener.assertErrorsWithCodes([ParserErrorCode.TOP_LEVEL_OPERATOR]);
}
void test_topLevelVariable_withMetadata() {
@@ -2136,12 +2510,18 @@
}
void test_unexpectedTerminatorForParameterGroup_named() {
- parse4("parseFormalParameterList", "(a, b})",
+ createParser('(a, b})');
+ FormalParameterList list = parser.parseFormalParameterList();
+ expectNotNullIfNoErrors(list);
+ listener.assertErrorsWithCodes(
[ParserErrorCode.UNEXPECTED_TERMINATOR_FOR_PARAMETER_GROUP]);
}
void test_unexpectedTerminatorForParameterGroup_optional() {
- parse4("parseFormalParameterList", "(a, b])",
+ createParser('(a, b])');
+ FormalParameterList list = parser.parseFormalParameterList();
+ expectNotNullIfNoErrors(list);
+ listener.assertErrorsWithCodes(
[ParserErrorCode.UNEXPECTED_TERMINATOR_FOR_PARAMETER_GROUP]);
}
@@ -2156,8 +2536,11 @@
}
void test_unexpectedToken_semicolonBetweenClassMembers() {
- parse3("parseClassDeclaration", <Object>[emptyCommentAndMetadata(), null],
- "class C { int x; ; int y;}", [ParserErrorCode.UNEXPECTED_TOKEN]);
+ createParser('class C { int x; ; int y;}');
+ ClassDeclaration declaration =
+ parser.parseClassDeclaration(emptyCommentAndMetadata(), null);
+ expectNotNullIfNoErrors(declaration);
+ listener.assertErrorsWithCodes([ParserErrorCode.UNEXPECTED_TOKEN]);
}
void test_unexpectedToken_semicolonBetweenCompilationUnitMembers() {
@@ -2240,11 +2623,13 @@
}
void test_useOfUnaryPlusOperator() {
- SimpleIdentifier expression = parse4(
- "parseUnaryExpression", "+x", [ParserErrorCode.MISSING_IDENTIFIER]);
- EngineTestCase.assertInstanceOf(
- (obj) => obj is SimpleIdentifier, SimpleIdentifier, expression);
- expect(expression.isSynthetic, isTrue);
+ createParser('+x');
+ Expression expression = parser.parseUnaryExpression();
+ expectNotNullIfNoErrors(expression);
+ listener.assertErrorsWithCodes([ParserErrorCode.MISSING_IDENTIFIER]);
+ expect(expression, new isInstanceOf<SimpleIdentifier>());
+ SimpleIdentifier identifier = expression;
+ expect(identifier.isSynthetic, isTrue);
}
void test_varAndType_field() {
@@ -2272,8 +2657,10 @@
}
void test_varReturnType() {
- parse3("parseClassMember", <Object>["C"], "var m() {}",
- [ParserErrorCode.VAR_RETURN_TYPE]);
+ createParser('var m() {}');
+ ClassMember member = parser.parseClassMember('C');
+ expectNotNullIfNoErrors(member);
+ listener.assertErrorsWithCodes([ParserErrorCode.VAR_RETURN_TYPE]);
}
void test_varTypedef() {
@@ -2282,18 +2669,24 @@
}
void test_voidParameter() {
- parse4("parseNormalFormalParameter", "void a)",
- [ParserErrorCode.VOID_PARAMETER]);
+ createParser('void a)');
+ NormalFormalParameter parameter = parser.parseNormalFormalParameter();
+ expectNotNullIfNoErrors(parameter);
+ listener.assertErrorsWithCodes([ParserErrorCode.VOID_PARAMETER]);
}
void test_voidVariable_parseClassMember_initializer() {
- parse3("parseClassMember", <Object>["C"], "void x = 0;",
- [ParserErrorCode.VOID_VARIABLE]);
+ createParser('void x = 0;');
+ ClassMember member = parser.parseClassMember('C');
+ expectNotNullIfNoErrors(member);
+ listener.assertErrorsWithCodes([ParserErrorCode.VOID_VARIABLE]);
}
void test_voidVariable_parseClassMember_noInitializer() {
- parse3("parseClassMember", <Object>["C"], "void x;",
- [ParserErrorCode.VOID_VARIABLE]);
+ createParser('void x;');
+ ClassMember member = parser.parseClassMember('C');
+ expectNotNullIfNoErrors(member);
+ listener.assertErrorsWithCodes([ParserErrorCode.VOID_VARIABLE]);
}
void test_voidVariable_parseCompilationUnit_initializer() {
@@ -2307,13 +2700,19 @@
}
void test_voidVariable_parseCompilationUnitMember_initializer() {
- parse3("parseCompilationUnitMember", <Object>[emptyCommentAndMetadata()],
- "void a = 0;", [ParserErrorCode.VOID_VARIABLE]);
+ createParser('void a = 0;');
+ CompilationUnitMember member =
+ parser.parseCompilationUnitMember(emptyCommentAndMetadata());
+ expectNotNullIfNoErrors(member);
+ listener.assertErrorsWithCodes([ParserErrorCode.VOID_VARIABLE]);
}
void test_voidVariable_parseCompilationUnitMember_noInitializer() {
- parse3("parseCompilationUnitMember", <Object>[emptyCommentAndMetadata()],
- "void a;", [ParserErrorCode.VOID_VARIABLE]);
+ createParser('void a;');
+ CompilationUnitMember member =
+ parser.parseCompilationUnitMember(emptyCommentAndMetadata());
+ expectNotNullIfNoErrors(member);
+ listener.assertErrorsWithCodes([ParserErrorCode.VOID_VARIABLE]);
}
void test_voidVariable_statement_initializer() {
@@ -2336,27 +2735,42 @@
}
void test_withWithoutExtends() {
- parse3("parseClassDeclaration", <Object>[emptyCommentAndMetadata(), null],
- "class A with B, C {}", [ParserErrorCode.WITH_WITHOUT_EXTENDS]);
+ createParser('class A with B, C {}');
+ ClassDeclaration declaration =
+ parser.parseClassDeclaration(emptyCommentAndMetadata(), null);
+ expectNotNullIfNoErrors(declaration);
+ listener.assertErrorsWithCodes([ParserErrorCode.WITH_WITHOUT_EXTENDS]);
}
void test_wrongSeparatorForNamedParameter() {
- parse4("parseFormalParameterList", "(a, {b = 0})",
+ createParser('(a, {b = 0})');
+ FormalParameterList list = parser.parseFormalParameterList();
+ expectNotNullIfNoErrors(list);
+ listener.assertErrorsWithCodes(
[ParserErrorCode.WRONG_SEPARATOR_FOR_NAMED_PARAMETER]);
}
void test_wrongSeparatorForPositionalParameter() {
- parse4("parseFormalParameterList", "(a, [b : 0])",
+ createParser('(a, [b : 0])');
+ FormalParameterList list = parser.parseFormalParameterList();
+ expectNotNullIfNoErrors(list);
+ listener.assertErrorsWithCodes(
[ParserErrorCode.WRONG_SEPARATOR_FOR_POSITIONAL_PARAMETER]);
}
void test_wrongTerminatorForParameterGroup_named() {
- parse4("parseFormalParameterList", "(a, {b, c])",
+ createParser('(a, {b, c])');
+ FormalParameterList list = parser.parseFormalParameterList();
+ expectNotNullIfNoErrors(list);
+ listener.assertErrorsWithCodes(
[ParserErrorCode.WRONG_TERMINATOR_FOR_PARAMETER_GROUP]);
}
void test_wrongTerminatorForParameterGroup_optional() {
- parse4("parseFormalParameterList", "(a, [b, c})",
+ createParser('(a, [b, c})');
+ FormalParameterList list = parser.parseFormalParameterList();
+ expectNotNullIfNoErrors(list);
+ listener.assertErrorsWithCodes(
[ParserErrorCode.WRONG_TERMINATOR_FOR_PARAMETER_GROUP]);
}
}
@@ -2370,7 +2784,10 @@
void test_staticMethod_notParsingFunctionBodies() {
ParserTestCase.parseFunctionBodies = false;
try {
- parse4("parseCompilationUnit", "class C { static void m() {} }");
+ createParser('class C { static void m() {} }');
+ CompilationUnit unit = parser.parseCompilationUnit2();
+ expectNotNullIfNoErrors(unit);
+ listener.assertNoErrors();
} finally {
ParserTestCase.parseFunctionBodies = true;
}
@@ -2417,6 +2834,26 @@
bool enableLazyAssignmentOperators = false;
/**
+ * A flag indicating whether the parser is to parse the non-nullable modifier
+ * in type names.
+ */
+ bool enableNnbd = false;
+
+ /**
+ * The error listener to which scanner and parser errors will be reported.
+ *
+ * This field is typically initialized by invoking [createParser].
+ */
+ GatheringErrorListener listener;
+
+ /**
+ * The parser used by the test.
+ *
+ * This field is typically initialized by invoking [createParser].
+ */
+ Parser parser;
+
+ /**
* Return a CommentAndMetadata object with the given values that can be used for testing.
*
* @param comment the comment to be wrapped in the object
@@ -2429,6 +2866,35 @@
}
/**
+ * Create the [parser] and [listener] used by a test. The [parser] will be
+ * prepared to parse the tokens scanned from the given [content].
+ */
+ void createParser(String content) {
+ listener = new GatheringErrorListener();
+ //
+ // Scan the source.
+ //
+ TestSource source = new TestSource();
+ CharacterReader reader = new CharSequenceReader(content);
+ Scanner scanner = new Scanner(source, reader, listener);
+ scanner.scanGenericMethodComments = enableGenericMethodComments;
+ scanner.scanLazyAssignmentOperators = enableLazyAssignmentOperators;
+ Token tokenStream = scanner.tokenize();
+ listener.setLineInfo(source, scanner.lineStarts);
+ //
+ // Create and initialize the parser.
+ //
+ parser = new Parser(source, listener);
+ parser.enableAssertInitializer = enableAssertInitializer;
+ parser.parseAsync = parseAsync;
+ parser.parseGenericMethods = enableGenericMethods;
+ parser.parseGenericMethodComments = enableGenericMethodComments;
+ parser.parseFunctionBodies = parseFunctionBodies;
+ parser.enableNnbd = enableNnbd;
+ parser.currentToken = tokenStream;
+ }
+
+ /**
* Return an empty CommentAndMetadata object that can be used for testing.
*
* @return an empty CommentAndMetadata object that can be used for testing
@@ -2436,6 +2902,12 @@
CommentAndMetadata emptyCommentAndMetadata() =>
new CommentAndMetadata(null, null);
+ void expectNotNullIfNoErrors(Object result) {
+ if (!listener.hasErrors) {
+ expect(result, isNotNull);
+ }
+ }
+
/**
* Invoke a method in [Parser]. The method is assumed to have the given number and type of
* parameters and will be invoked with the given arguments.
@@ -2446,79 +2918,20 @@
* @param methodName the name of the method that should be invoked
* @param objects the values of the arguments to the method
* @param source the source to be processed by the parse method
- * @param listener the error listener that will be used for both scanning and parsing
* @return the result of invoking the method
* @throws Exception if the method could not be invoked or throws an exception
* @throws AssertionFailedError if the result is `null` or the errors produced while
* scanning and parsing the source do not match the expected errors
*/
- Object invokeParserMethod(String methodName, List<Object> objects,
- String source, GatheringErrorListener listener) {
- //
- // Scan the source.
- //
- Scanner scanner =
- new Scanner(null, new CharSequenceReader(source), listener);
- scanner.scanGenericMethodComments = enableGenericMethodComments;
- scanner.scanLazyAssignmentOperators = enableLazyAssignmentOperators;
- Token tokenStream = scanner.tokenize();
- listener.setLineInfo(new TestSource(), scanner.lineStarts);
- //
- // Parse the source.
- //
- Parser parser = createParser(listener);
- parser.enableAssertInitializer = enableAssertInitializer;
- parser.parseAsync = parseAsync;
- parser.parseGenericMethods = enableGenericMethods;
- parser.parseGenericMethodComments = enableGenericMethodComments;
- parser.parseFunctionBodies = parseFunctionBodies;
- Object result =
- invokeParserMethodImpl(parser, methodName, objects, tokenStream);
- //
- // Partially test the results.
- //
- if (!listener.hasErrors) {
- expect(result, isNotNull);
- }
+ Object invokeParserMethod(
+ String methodName, List<Object> objects, String source) {
+ createParser(source);
+ Object result = invokeParserMethodImpl(parser, methodName, objects);
+ expectNotNullIfNoErrors(result);
return result;
}
/**
- * Invoke a method in [Parser]. The method is assumed to have no arguments.
- *
- * The given source is scanned and the parser is initialized to start with the first token in the
- * source before the method is invoked.
- *
- * @param methodName the name of the method that should be invoked
- * @param source the source to be processed by the parse method
- * @param listener the error listener that will be used for both scanning and parsing
- * @return the result of invoking the method
- * @throws Exception if the method could not be invoked or throws an exception
- * @throws AssertionFailedError if the result is `null` or the errors produced while
- * scanning and parsing the source do not match the expected errors
- */
- Object invokeParserMethod2(
- String methodName, String source, GatheringErrorListener listener) =>
- invokeParserMethod(methodName, _EMPTY_ARGUMENTS, source, listener);
-
- /**
- * Invoke a parse method in [Parser]. The method is assumed to have the given number and
- * type of parameters and will be invoked with the given arguments.
- *
- * The given source is scanned and the parser is initialized to start with the first token in the
- * source before the parse method is invoked.
- *
- * @param methodName the name of the parse method that should be invoked to parse the source
- * @param objects the values of the arguments to the method
- * @param source the source to be parsed by the parse method
- * @return the result of invoking the method
- * @throws Exception if the method could not be invoked or throws an exception
- * @throws AssertionFailedError if the result is `null` or if any errors are produced
- */
- Object parse(String methodName, List<Object> objects, String source) =>
- parse2(methodName, objects, source);
-
- /**
* Invoke a parse method in [Parser]. The method is assumed to have the given number and
* type of parameters and will be invoked with the given arguments.
*
@@ -2534,39 +2947,14 @@
* @throws AssertionFailedError if the result is `null` or the errors produced while
* scanning and parsing the source do not match the expected errors
*/
- Object parse2(String methodName, List<Object> objects, String source,
+ Object parse(String methodName, List<Object> objects, String source,
[List<AnalysisError> errors = AnalysisError.NO_ERRORS]) {
- GatheringErrorListener listener = new GatheringErrorListener();
- Object result = invokeParserMethod(methodName, objects, source, listener);
+ Object result = invokeParserMethod(methodName, objects, source);
listener.assertErrors(errors);
return result;
}
/**
- * Invoke a parse method in [Parser]. The method is assumed to have the given number and
- * type of parameters and will be invoked with the given arguments.
- *
- * The given source is scanned and the parser is initialized to start with the first token in the
- * source before the parse method is invoked.
- *
- * @param methodName the name of the parse method that should be invoked to parse the source
- * @param objects the values of the arguments to the method
- * @param source the source to be parsed by the parse method
- * @param errorCodes the error codes of the errors that should be generated
- * @return the result of invoking the method
- * @throws Exception if the method could not be invoked or throws an exception
- * @throws AssertionFailedError if the result is `null` or the errors produced while
- * scanning and parsing the source do not match the expected errors
- */
- Object parse3(String methodName, List<Object> objects, String source,
- [List<ErrorCode> errorCodes = ErrorCode.EMPTY_LIST]) {
- GatheringErrorListener listener = new GatheringErrorListener();
- Object result = invokeParserMethod(methodName, objects, source, listener);
- listener.assertErrorsWithCodes(errorCodes);
- return result;
- }
-
- /**
* Invoke a parse method in [Parser]. The method is assumed to have no arguments.
*
* The given source is scanned and the parser is initialized to start with the first token in the
@@ -2581,8 +2969,11 @@
* scanning and parsing the source do not match the expected errors
*/
Object parse4(String methodName, String source,
- [List<ErrorCode> errorCodes = ErrorCode.EMPTY_LIST]) =>
- parse3(methodName, _EMPTY_ARGUMENTS, source, errorCodes);
+ [List<ErrorCode> errorCodes = ErrorCode.EMPTY_LIST]) {
+ Object result = invokeParserMethod(methodName, _EMPTY_ARGUMENTS, source);
+ listener.assertErrorsWithCodes(errorCodes);
+ return result;
+ }
/**
* Parse the given [source] as a compilation unit. Throw an exception if the
@@ -2591,18 +2982,8 @@
*/
CompilationUnit parseCompilationUnitWithOptions(String source,
[List<ErrorCode> errorCodes = ErrorCode.EMPTY_LIST]) {
- GatheringErrorListener listener = new GatheringErrorListener();
- Scanner scanner =
- new Scanner(null, new CharSequenceReader(source), listener);
- listener.setLineInfo(new TestSource(), scanner.lineStarts);
- Token token = scanner.tokenize();
- Parser parser = createParser(listener);
- parser.enableAssertInitializer = enableAssertInitializer;
- parser.parseAsync = parseAsync;
- parser.parseFunctionBodies = parseFunctionBodies;
- parser.parseGenericMethods = enableGenericMethods;
- parser.parseGenericMethodComments = enableGenericMethodComments;
- CompilationUnit unit = parser.parseCompilationUnit(token);
+ createParser(source);
+ CompilationUnit unit = parser.parseCompilationUnit2();
expect(unit, isNotNull);
listener.assertErrorsWithCodes(errorCodes);
return unit;
@@ -2619,16 +3000,8 @@
*/
Expression parseExpression(String source,
[List<ErrorCode> errorCodes = ErrorCode.EMPTY_LIST]) {
- GatheringErrorListener listener = new GatheringErrorListener();
- Scanner scanner =
- new Scanner(null, new CharSequenceReader(source), listener);
- scanner.scanGenericMethodComments = enableGenericMethodComments;
- listener.setLineInfo(new TestSource(), scanner.lineStarts);
- Token token = scanner.tokenize();
- Parser parser = createParser(listener);
- parser.parseGenericMethods = enableGenericMethods;
- parser.parseGenericMethodComments = enableGenericMethodComments;
- Expression expression = parser.parseExpression(token);
+ createParser(source);
+ Expression expression = parser.parseExpression2();
expect(expression, isNotNull);
listener.assertErrorsWithCodes(errorCodes);
return expression;
@@ -2641,16 +3014,6 @@
}
/**
- * Create a parser.
- *
- * @param listener the listener to be passed to the parser
- * @return the parser that was created
- */
- static Parser createParser(GatheringErrorListener listener) {
- return new Parser(null, listener);
- }
-
- /**
* Parse the given source as a compilation unit.
*
* @param source the source to be parsed
@@ -2666,7 +3029,7 @@
new Scanner(null, new CharSequenceReader(source), listener);
listener.setLineInfo(new TestSource(), scanner.lineStarts);
Token token = scanner.tokenize();
- Parser parser = createParser(listener);
+ Parser parser = new Parser(null, listener);
CompilationUnit unit = parser.parseCompilationUnit(token);
expect(unit, isNotNull);
listener.assertErrorsWithCodes(errorCodes);
@@ -2688,7 +3051,7 @@
scanner.scanLazyAssignmentOperators = enableLazyAssignmentOperators;
listener.setLineInfo(new TestSource(), scanner.lineStarts);
Token token = scanner.tokenize();
- Parser parser = createParser(listener);
+ Parser parser = new Parser(null, listener);
Statement statement = parser.parseStatement(token);
expect(statement, isNotNull);
listener.assertErrorsWithCodes(errorCodes);
@@ -2713,7 +3076,7 @@
new Scanner(null, new CharSequenceReader(source), listener);
listener.setLineInfo(new TestSource(), scanner.lineStarts);
Token token = scanner.tokenize();
- Parser parser = createParser(listener);
+ Parser parser = new Parser(null, listener);
List<Statement> statements = parser.parseStatements(token);
expect(statements, hasLength(expectedCount));
listener.assertErrorsWithCodes(errorCodes);
@@ -3057,19 +3420,27 @@
}
void test_conditionalExpression_missingElse() {
- ConditionalExpression expression = parse4("parseConditionalExpression",
- "x ? y :", [ParserErrorCode.MISSING_IDENTIFIER]);
- EngineTestCase.assertInstanceOf((obj) => obj is SimpleIdentifier,
- SimpleIdentifier, expression.elseExpression);
- expect(expression.elseExpression.isSynthetic, isTrue);
+ createParser('x ? y :');
+ Expression expression = parser.parseConditionalExpression();
+ expectNotNullIfNoErrors(expression);
+ listener.assertErrorsWithCodes([ParserErrorCode.MISSING_IDENTIFIER]);
+ expect(expression, new isInstanceOf<ConditionalExpression>());
+ ConditionalExpression conditionalExpression = expression;
+ expect(conditionalExpression.elseExpression,
+ new isInstanceOf<SimpleIdentifier>());
+ expect(conditionalExpression.elseExpression.isSynthetic, isTrue);
}
void test_conditionalExpression_missingThen() {
- ConditionalExpression expression = parse4("parseConditionalExpression",
- "x ? : z", [ParserErrorCode.MISSING_IDENTIFIER]);
- EngineTestCase.assertInstanceOf((obj) => obj is SimpleIdentifier,
- SimpleIdentifier, expression.thenExpression);
- expect(expression.thenExpression.isSynthetic, isTrue);
+ createParser('x ? : z');
+ Expression expression = parser.parseConditionalExpression();
+ expectNotNullIfNoErrors(expression);
+ listener.assertErrorsWithCodes([ParserErrorCode.MISSING_IDENTIFIER]);
+ expect(expression, new isInstanceOf<ConditionalExpression>());
+ ConditionalExpression conditionalExpression = expression;
+ expect(conditionalExpression.thenExpression,
+ new isInstanceOf<SimpleIdentifier>());
+ expect(conditionalExpression.thenExpression.isSynthetic, isTrue);
}
void test_declarationBeforeDirective() {
@@ -3151,8 +3522,10 @@
}
void test_expressionList_multiple_end() {
- List<Expression> result = parse4("parseExpressionList", ", 2, 3, 4",
- [ParserErrorCode.MISSING_IDENTIFIER]) as List<Expression>;
+ createParser(', 2, 3, 4');
+ List<Expression> result = parser.parseExpressionList();
+ expectNotNullIfNoErrors(result);
+ listener.assertErrorsWithCodes([ParserErrorCode.MISSING_IDENTIFIER]);
expect(result, hasLength(4));
Expression syntheticExpression = result[0];
EngineTestCase.assertInstanceOf((obj) => obj is SimpleIdentifier,
@@ -3161,8 +3534,10 @@
}
void test_expressionList_multiple_middle() {
- List<Expression> result = parse4("parseExpressionList", "1, 2, , 4",
- [ParserErrorCode.MISSING_IDENTIFIER]) as List<Expression>;
+ createParser('1, 2, , 4');
+ List<Expression> result = parser.parseExpressionList();
+ expectNotNullIfNoErrors(result);
+ listener.assertErrorsWithCodes([ParserErrorCode.MISSING_IDENTIFIER]);
expect(result, hasLength(4));
Expression syntheticExpression = result[2];
EngineTestCase.assertInstanceOf((obj) => obj is SimpleIdentifier,
@@ -3171,8 +3546,10 @@
}
void test_expressionList_multiple_start() {
- List<Expression> result = parse4("parseExpressionList", "1, 2, 3,",
- [ParserErrorCode.MISSING_IDENTIFIER]) as List<Expression>;
+ createParser('1, 2, 3,');
+ List<Expression> result = parser.parseExpressionList();
+ expectNotNullIfNoErrors(result);
+ listener.assertErrorsWithCodes([ParserErrorCode.MISSING_IDENTIFIER]);
expect(result, hasLength(4));
Expression syntheticExpression = result[3];
EngineTestCase.assertInstanceOf((obj) => obj is SimpleIdentifier,
@@ -3233,12 +3610,17 @@
}
void test_incomplete_constructorInitializers_empty() {
- parse3("parseClassMember", ["C"], "C() : {}",
- [ParserErrorCode.MISSING_INITIALIZER]);
+ createParser('C() : {}');
+ ClassMember member = parser.parseClassMember('C');
+ expectNotNullIfNoErrors(member);
+ listener.assertErrorsWithCodes([ParserErrorCode.MISSING_INITIALIZER]);
}
void test_incomplete_constructorInitializers_missingEquals() {
- ClassMember member = parse3("parseClassMember", ["C"], "C() : x(3) {}",
+ createParser('C() : x(3) {}');
+ ClassMember member = parser.parseClassMember('C');
+ expectNotNullIfNoErrors(member);
+ listener.assertErrorsWithCodes(
[ParserErrorCode.MISSING_ASSIGNMENT_IN_INITIALIZER]);
expect(member, new isInstanceOf<ConstructorDeclaration>());
NodeList<ConstructorInitializer> initializers =
@@ -3253,7 +3635,10 @@
}
void test_incomplete_constructorInitializers_variable() {
- parse3("parseClassMember", ["C"], "C() : x {}",
+ createParser('C() : x {}');
+ ClassMember member = parser.parseClassMember('C');
+ expectNotNullIfNoErrors(member);
+ listener.assertErrorsWithCodes(
[ParserErrorCode.MISSING_ASSIGNMENT_IN_INITIALIZER]);
}
@@ -3655,8 +4040,12 @@
}
void test_missingIdentifier_afterAnnotation() {
- MethodDeclaration method = parse3("parseClassMember", <Object>["C"],
- "@override }", [ParserErrorCode.EXPECTED_CLASS_MEMBER]);
+ createParser('@override }');
+ ClassMember member = parser.parseClassMember('C');
+ expectNotNullIfNoErrors(member);
+ listener.assertErrorsWithCodes([ParserErrorCode.EXPECTED_CLASS_MEMBER]);
+ expect(member, new isInstanceOf<MethodDeclaration>());
+ MethodDeclaration method = member;
expect(method.documentationComment, isNull);
NodeList<Annotation> metadata = method.metadata;
expect(metadata, hasLength(1));
@@ -3766,10 +4155,11 @@
}
void test_primaryExpression_argumentDefinitionTest() {
- Expression expression = parse4(
- "parsePrimaryExpression", "?a", [ParserErrorCode.UNEXPECTED_TOKEN]);
- EngineTestCase.assertInstanceOf(
- (obj) => obj is SimpleIdentifier, SimpleIdentifier, expression);
+ createParser('?a');
+ Expression expression = parser.parsePrimaryExpression();
+ expectNotNullIfNoErrors(expression);
+ listener.assertErrorsWithCodes([ParserErrorCode.UNEXPECTED_TOKEN]);
+ expect(expression, new isInstanceOf<SimpleIdentifier>());
}
void test_relationalExpression_missing_LHS() {
@@ -3940,9 +4330,13 @@
void fail_parseStatement_functionDeclaration_noReturnType_typeParameters() {
enableGenericMethods = true;
- FunctionDeclarationStatement statement =
- parse4("parseStatement", "f<E>(a, b) {};");
- expect(statement.functionDeclaration, isNotNull);
+ createParser('f<E>(a, b) {};');
+ Statement statement = parser.parseStatement2();
+ expectNotNullIfNoErrors(statement);
+ listener.assertNoErrors();
+ expect(statement, new isInstanceOf<FunctionDeclarationStatement>());
+ FunctionDeclarationStatement declaration = statement;
+ expect(declaration.functionDeclaration, isNotNull);
}
void test_computeStringValue_emptyInterpolationPrefix() {
@@ -4030,12 +4424,16 @@
}
void test_createSyntheticIdentifier() {
- SimpleIdentifier identifier = _createSyntheticIdentifier();
+ createParser('');
+ SimpleIdentifier identifier = parser.createSyntheticIdentifier();
+ expectNotNullIfNoErrors(identifier);
expect(identifier.isSynthetic, isTrue);
}
void test_createSyntheticStringLiteral() {
- SimpleStringLiteral literal = _createSyntheticStringLiteral();
+ createParser('');
+ SimpleStringLiteral literal = parser.createSyntheticStringLiteral();
+ expectNotNullIfNoErrors(literal);
expect(literal.isSynthetic, isTrue);
}
@@ -4286,25 +4684,36 @@
}
void test_parseAdditiveExpression_normal() {
- BinaryExpression expression = parse4("parseAdditiveExpression", "x + y");
- expect(expression.leftOperand, isNotNull);
- expect(expression.operator, isNotNull);
- expect(expression.operator.type, TokenType.PLUS);
- expect(expression.rightOperand, isNotNull);
+ createParser('x + y');
+ Expression expression = parser.parseAdditiveExpression();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<BinaryExpression>());
+ BinaryExpression binaryExpression = expression;
+ expect(binaryExpression.leftOperand, isNotNull);
+ expect(binaryExpression.operator, isNotNull);
+ expect(binaryExpression.operator.type, TokenType.PLUS);
+ expect(binaryExpression.rightOperand, isNotNull);
}
void test_parseAdditiveExpression_super() {
- BinaryExpression expression =
- parse4("parseAdditiveExpression", "super + y");
- EngineTestCase.assertInstanceOf((obj) => obj is SuperExpression,
- SuperExpression, expression.leftOperand);
- expect(expression.operator, isNotNull);
- expect(expression.operator.type, TokenType.PLUS);
- expect(expression.rightOperand, isNotNull);
+ createParser('super + y');
+ Expression expression = parser.parseAdditiveExpression();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<BinaryExpression>());
+ BinaryExpression binaryExpression = expression;
+ expect(binaryExpression.leftOperand, new isInstanceOf<SuperExpression>());
+ expect(binaryExpression.operator, isNotNull);
+ expect(binaryExpression.operator.type, TokenType.PLUS);
+ expect(binaryExpression.rightOperand, isNotNull);
}
void test_parseAnnotation_n1() {
- Annotation annotation = parse4("parseAnnotation", "@A");
+ createParser('@A');
+ Annotation annotation = parser.parseAnnotation();
+ expectNotNullIfNoErrors(annotation);
+ listener.assertNoErrors();
expect(annotation.atSign, isNotNull);
expect(annotation.name, isNotNull);
expect(annotation.period, isNull);
@@ -4313,7 +4722,10 @@
}
void test_parseAnnotation_n1_a() {
- Annotation annotation = parse4("parseAnnotation", "@A(x,y)");
+ createParser('@A(x,y)');
+ Annotation annotation = parser.parseAnnotation();
+ expectNotNullIfNoErrors(annotation);
+ listener.assertNoErrors();
expect(annotation.atSign, isNotNull);
expect(annotation.name, isNotNull);
expect(annotation.period, isNull);
@@ -4322,7 +4734,10 @@
}
void test_parseAnnotation_n2() {
- Annotation annotation = parse4("parseAnnotation", "@A.B");
+ createParser('@A.B');
+ Annotation annotation = parser.parseAnnotation();
+ expectNotNullIfNoErrors(annotation);
+ listener.assertNoErrors();
expect(annotation.atSign, isNotNull);
expect(annotation.name, isNotNull);
expect(annotation.period, isNull);
@@ -4331,7 +4746,10 @@
}
void test_parseAnnotation_n2_a() {
- Annotation annotation = parse4("parseAnnotation", "@A.B(x,y)");
+ createParser('@A.B(x,y)');
+ Annotation annotation = parser.parseAnnotation();
+ expectNotNullIfNoErrors(annotation);
+ listener.assertNoErrors();
expect(annotation.atSign, isNotNull);
expect(annotation.name, isNotNull);
expect(annotation.period, isNull);
@@ -4340,7 +4758,10 @@
}
void test_parseAnnotation_n3() {
- Annotation annotation = parse4("parseAnnotation", "@A.B.C");
+ createParser('@A.B.C');
+ Annotation annotation = parser.parseAnnotation();
+ expectNotNullIfNoErrors(annotation);
+ listener.assertNoErrors();
expect(annotation.atSign, isNotNull);
expect(annotation.name, isNotNull);
expect(annotation.period, isNotNull);
@@ -4349,7 +4770,10 @@
}
void test_parseAnnotation_n3_a() {
- Annotation annotation = parse4("parseAnnotation", "@A.B.C(x,y)");
+ createParser('@A.B.C(x,y)');
+ Annotation annotation = parser.parseAnnotation();
+ expectNotNullIfNoErrors(annotation);
+ listener.assertNoErrors();
expect(annotation.atSign, isNotNull);
expect(annotation.name, isNotNull);
expect(annotation.period, isNotNull);
@@ -4358,53 +4782,80 @@
}
void test_parseArgument_named() {
- NamedExpression expression = parse4("parseArgument", "n: x");
- Label name = expression.name;
+ createParser('n: x');
+ Expression expression = parser.parseArgument();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<NamedExpression>());
+ NamedExpression namedExpression = expression;
+ Label name = namedExpression.name;
expect(name, isNotNull);
expect(name.label, isNotNull);
expect(name.colon, isNotNull);
- expect(expression.expression, isNotNull);
+ expect(namedExpression.expression, isNotNull);
}
void test_parseArgument_unnamed() {
String lexeme = "x";
- SimpleIdentifier identifier = parse4("parseArgument", lexeme);
+ createParser(lexeme);
+ Expression expression = parser.parseArgument();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<SimpleIdentifier>());
+ SimpleIdentifier identifier = expression;
expect(identifier.name, lexeme);
}
void test_parseArgumentList_empty() {
- ArgumentList argumentList = parse4("parseArgumentList", "()");
+ createParser('()');
+ ArgumentList argumentList = parser.parseArgumentList();
+ expectNotNullIfNoErrors(argumentList);
+ listener.assertNoErrors();
NodeList<Expression> arguments = argumentList.arguments;
expect(arguments, hasLength(0));
}
void test_parseArgumentList_mixed() {
- ArgumentList argumentList =
- parse4("parseArgumentList", "(w, x, y: y, z: z)");
+ createParser('(w, x, y: y, z: z)');
+ ArgumentList argumentList = parser.parseArgumentList();
+ expectNotNullIfNoErrors(argumentList);
+ listener.assertNoErrors();
NodeList<Expression> arguments = argumentList.arguments;
expect(arguments, hasLength(4));
}
void test_parseArgumentList_noNamed() {
- ArgumentList argumentList = parse4("parseArgumentList", "(x, y, z)");
+ createParser('(x, y, z)');
+ ArgumentList argumentList = parser.parseArgumentList();
+ expectNotNullIfNoErrors(argumentList);
+ listener.assertNoErrors();
NodeList<Expression> arguments = argumentList.arguments;
expect(arguments, hasLength(3));
}
void test_parseArgumentList_onlyNamed() {
- ArgumentList argumentList = parse4("parseArgumentList", "(x: x, y: y)");
+ createParser('(x: x, y: y)');
+ ArgumentList argumentList = parser.parseArgumentList();
+ expectNotNullIfNoErrors(argumentList);
+ listener.assertNoErrors();
NodeList<Expression> arguments = argumentList.arguments;
expect(arguments, hasLength(2));
}
void test_parseArgumentList_trailing_comma() {
- ArgumentList argumentList = parse4("parseArgumentList", "(x, y, z,)");
+ createParser('(x, y, z,)');
+ ArgumentList argumentList = parser.parseArgumentList();
+ expectNotNullIfNoErrors(argumentList);
+ listener.assertNoErrors();
NodeList<Expression> arguments = argumentList.arguments;
expect(arguments, hasLength(3));
}
void test_parseAssertStatement() {
- AssertStatement statement = parse4("parseAssertStatement", "assert (x);");
+ createParser('assert (x);');
+ AssertStatement statement = parser.parseAssertStatement();
+ expectNotNullIfNoErrors(statement);
+ listener.assertNoErrors();
expect(statement.assertKeyword, isNotNull);
expect(statement.leftParenthesis, isNotNull);
expect(statement.condition, isNotNull);
@@ -4419,8 +4870,10 @@
// practice, but it's the lowest precedence expression type, so verifying
// that it works should give us high confidence that other expression types
// will work as well.
- AssertStatement statement =
- parse4('parseAssertStatement', 'assert (x, throw "foo");');
+ createParser('assert (x, throw "foo");');
+ AssertStatement statement = parser.parseAssertStatement();
+ expectNotNullIfNoErrors(statement);
+ listener.assertNoErrors();
expect(statement.assertKeyword, isNotNull);
expect(statement.leftParenthesis, isNotNull);
expect(statement.condition, isNotNull);
@@ -4431,8 +4884,10 @@
}
void test_parseAssertStatement_messageString() {
- AssertStatement statement =
- parse4('parseAssertStatement', 'assert (x, "foo");');
+ createParser('assert (x, "foo");');
+ AssertStatement statement = parser.parseAssertStatement();
+ expectNotNullIfNoErrors(statement);
+ listener.assertNoErrors();
expect(statement.assertKeyword, isNotNull);
expect(statement.leftParenthesis, isNotNull);
expect(statement.condition, isNotNull);
@@ -4634,7 +5089,10 @@
}
void test_parseAwaitExpression() {
- AwaitExpression expression = parse4("parseAwaitExpression", "await x;");
+ createParser('await x;');
+ AwaitExpression expression = parser.parseAwaitExpression();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
expect(expression.awaitKeyword, isNotNull);
expect(expression.expression, isNotNull);
}
@@ -4669,90 +5127,130 @@
}
void test_parseBitwiseAndExpression_normal() {
- BinaryExpression expression = parse4("parseBitwiseAndExpression", "x & y");
- expect(expression.leftOperand, isNotNull);
- expect(expression.operator, isNotNull);
- expect(expression.operator.type, TokenType.AMPERSAND);
- expect(expression.rightOperand, isNotNull);
+ createParser('x & y');
+ Expression expression = parser.parseBitwiseAndExpression();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<BinaryExpression>());
+ BinaryExpression binaryExpression = expression;
+ expect(binaryExpression.leftOperand, isNotNull);
+ expect(binaryExpression.operator, isNotNull);
+ expect(binaryExpression.operator.type, TokenType.AMPERSAND);
+ expect(binaryExpression.rightOperand, isNotNull);
}
void test_parseBitwiseAndExpression_super() {
- BinaryExpression expression =
- parse4("parseBitwiseAndExpression", "super & y");
- EngineTestCase.assertInstanceOf((obj) => obj is SuperExpression,
- SuperExpression, expression.leftOperand);
- expect(expression.operator, isNotNull);
- expect(expression.operator.type, TokenType.AMPERSAND);
- expect(expression.rightOperand, isNotNull);
+ createParser('super & y');
+ Expression expression = parser.parseBitwiseAndExpression();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<BinaryExpression>());
+ BinaryExpression binaryExpression = expression;
+ expect(binaryExpression.leftOperand, new isInstanceOf<SuperExpression>());
+ expect(binaryExpression.operator, isNotNull);
+ expect(binaryExpression.operator.type, TokenType.AMPERSAND);
+ expect(binaryExpression.rightOperand, isNotNull);
}
void test_parseBitwiseOrExpression_normal() {
- BinaryExpression expression = parse4("parseBitwiseOrExpression", "x | y");
- expect(expression.leftOperand, isNotNull);
- expect(expression.operator, isNotNull);
- expect(expression.operator.type, TokenType.BAR);
- expect(expression.rightOperand, isNotNull);
+ createParser('x | y');
+ Expression expression = parser.parseBitwiseOrExpression();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<BinaryExpression>());
+ BinaryExpression binaryExpression = expression;
+ expect(binaryExpression.leftOperand, isNotNull);
+ expect(binaryExpression.operator, isNotNull);
+ expect(binaryExpression.operator.type, TokenType.BAR);
+ expect(binaryExpression.rightOperand, isNotNull);
}
void test_parseBitwiseOrExpression_super() {
- BinaryExpression expression =
- parse4("parseBitwiseOrExpression", "super | y");
- EngineTestCase.assertInstanceOf((obj) => obj is SuperExpression,
- SuperExpression, expression.leftOperand);
- expect(expression.operator, isNotNull);
- expect(expression.operator.type, TokenType.BAR);
- expect(expression.rightOperand, isNotNull);
+ createParser('super | y');
+ Expression expression = parser.parseBitwiseOrExpression();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<BinaryExpression>());
+ BinaryExpression binaryExpression = expression;
+ expect(binaryExpression.leftOperand, new isInstanceOf<SuperExpression>());
+ expect(binaryExpression.operator, isNotNull);
+ expect(binaryExpression.operator.type, TokenType.BAR);
+ expect(binaryExpression.rightOperand, isNotNull);
}
void test_parseBitwiseXorExpression_normal() {
- BinaryExpression expression = parse4("parseBitwiseXorExpression", "x ^ y");
- expect(expression.leftOperand, isNotNull);
- expect(expression.operator, isNotNull);
- expect(expression.operator.type, TokenType.CARET);
- expect(expression.rightOperand, isNotNull);
+ createParser('x ^ y');
+ Expression expression = parser.parseBitwiseXorExpression();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<BinaryExpression>());
+ BinaryExpression binaryExpression = expression;
+ expect(binaryExpression.leftOperand, isNotNull);
+ expect(binaryExpression.operator, isNotNull);
+ expect(binaryExpression.operator.type, TokenType.CARET);
+ expect(binaryExpression.rightOperand, isNotNull);
}
void test_parseBitwiseXorExpression_super() {
- BinaryExpression expression =
- parse4("parseBitwiseXorExpression", "super ^ y");
- EngineTestCase.assertInstanceOf((obj) => obj is SuperExpression,
- SuperExpression, expression.leftOperand);
- expect(expression.operator, isNotNull);
- expect(expression.operator.type, TokenType.CARET);
- expect(expression.rightOperand, isNotNull);
+ createParser('super ^ y');
+ Expression expression = parser.parseBitwiseXorExpression();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<BinaryExpression>());
+ BinaryExpression binaryExpression = expression;
+ expect(binaryExpression.leftOperand, new isInstanceOf<SuperExpression>());
+ expect(binaryExpression.operator, isNotNull);
+ expect(binaryExpression.operator.type, TokenType.CARET);
+ expect(binaryExpression.rightOperand, isNotNull);
}
void test_parseBlock_empty() {
- Block block = parse4("parseBlock", "{}");
+ createParser('{}');
+ Block block = parser.parseBlock();
+ expectNotNullIfNoErrors(block);
+ listener.assertNoErrors();
expect(block.leftBracket, isNotNull);
expect(block.statements, hasLength(0));
expect(block.rightBracket, isNotNull);
}
void test_parseBlock_nonEmpty() {
- Block block = parse4("parseBlock", "{;}");
+ createParser('{;}');
+ Block block = parser.parseBlock();
+ expectNotNullIfNoErrors(block);
+ listener.assertNoErrors();
expect(block.leftBracket, isNotNull);
expect(block.statements, hasLength(1));
expect(block.rightBracket, isNotNull);
}
void test_parseBreakStatement_label() {
- BreakStatement statement = parse4("parseBreakStatement", "break foo;");
+ createParser('break foo;');
+ BreakStatement statement = parser.parseBreakStatement();
+ expectNotNullIfNoErrors(statement);
+ listener.assertNoErrors();
expect(statement.breakKeyword, isNotNull);
expect(statement.label, isNotNull);
expect(statement.semicolon, isNotNull);
}
void test_parseBreakStatement_noLabel() {
- BreakStatement statement = parse4("parseBreakStatement", "break;",
- [ParserErrorCode.BREAK_OUTSIDE_OF_LOOP]);
+ createParser('break;');
+ BreakStatement statement = parser.parseBreakStatement();
+ expectNotNullIfNoErrors(statement);
+ listener.assertErrorsWithCodes([ParserErrorCode.BREAK_OUTSIDE_OF_LOOP]);
expect(statement.breakKeyword, isNotNull);
expect(statement.label, isNull);
expect(statement.semicolon, isNotNull);
}
void test_parseCascadeSection_i() {
- IndexExpression section = parse4("parseCascadeSection", "..[i]");
+ createParser('..[i]');
+ Expression expression = parser.parseCascadeSection();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<IndexExpression>());
+ IndexExpression section = expression;
expect(section.target, isNull);
expect(section.leftBracket, isNotNull);
expect(section.index, isNotNull);
@@ -4760,38 +5258,51 @@
}
void test_parseCascadeSection_ia() {
- FunctionExpressionInvocation section =
- parse4("parseCascadeSection", "..[i](b)");
- EngineTestCase.assertInstanceOf(
- (obj) => obj is IndexExpression, IndexExpression, section.function);
+ createParser('..[i](b)');
+ Expression expression = parser.parseCascadeSection();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<FunctionExpressionInvocation>());
+ FunctionExpressionInvocation section = expression;
+ expect(section.function, new isInstanceOf<IndexExpression>());
expect(section.typeArguments, isNull);
expect(section.argumentList, isNotNull);
}
void test_parseCascadeSection_ia_typeArgumentComments() {
enableGenericMethodComments = true;
- FunctionExpressionInvocation section =
- parse4("parseCascadeSection", "..[i]/*<E>*/(b)");
- EngineTestCase.assertInstanceOf(
- (obj) => obj is IndexExpression, IndexExpression, section.function);
+ createParser('..[i]/*<E>*/(b)');
+ Expression expression = parser.parseCascadeSection();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<FunctionExpressionInvocation>());
+ FunctionExpressionInvocation section = expression;
+ expect(section.function, new isInstanceOf<IndexExpression>());
expect(section.typeArguments, isNotNull);
expect(section.argumentList, isNotNull);
}
void test_parseCascadeSection_ia_typeArguments() {
enableGenericMethods = true;
- FunctionExpressionInvocation section =
- parse4("parseCascadeSection", "..[i]<E>(b)");
- EngineTestCase.assertInstanceOf(
- (obj) => obj is IndexExpression, IndexExpression, section.function);
+ createParser('..[i]<E>(b)');
+ Expression expression = parser.parseCascadeSection();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<FunctionExpressionInvocation>());
+ FunctionExpressionInvocation section = expression;
+ expect(section.function, new isInstanceOf<IndexExpression>());
expect(section.typeArguments, isNotNull);
expect(section.argumentList, isNotNull);
}
void test_parseCascadeSection_ii() {
- MethodInvocation section = parse4("parseCascadeSection", "..a(b).c(d)");
- EngineTestCase.assertInstanceOf(
- (obj) => obj is MethodInvocation, MethodInvocation, section.target);
+ createParser('..a(b).c(d)');
+ Expression expression = parser.parseCascadeSection();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<MethodInvocation>());
+ MethodInvocation section = expression;
+ expect(section.target, new isInstanceOf<MethodInvocation>());
expect(section.operator, isNotNull);
expect(section.methodName, isNotNull);
expect(section.typeArguments, isNull);
@@ -4801,10 +5312,13 @@
void test_parseCascadeSection_ii_typeArgumentComments() {
enableGenericMethodComments = true;
- MethodInvocation section =
- parse4("parseCascadeSection", "..a/*<E>*/(b).c/*<F>*/(d)");
- EngineTestCase.assertInstanceOf(
- (obj) => obj is MethodInvocation, MethodInvocation, section.target);
+ createParser('..a/*<E>*/(b).c/*<F>*/(d)');
+ Expression expression = parser.parseCascadeSection();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<MethodInvocation>());
+ MethodInvocation section = expression;
+ expect(section.target, new isInstanceOf<MethodInvocation>());
expect(section.operator, isNotNull);
expect(section.methodName, isNotNull);
expect(section.typeArguments, isNotNull);
@@ -4814,10 +5328,13 @@
void test_parseCascadeSection_ii_typeArguments() {
enableGenericMethods = true;
- MethodInvocation section =
- parse4("parseCascadeSection", "..a<E>(b).c<F>(d)");
- EngineTestCase.assertInstanceOf(
- (obj) => obj is MethodInvocation, MethodInvocation, section.target);
+ createParser('..a<E>(b).c<F>(d)');
+ Expression expression = parser.parseCascadeSection();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<MethodInvocation>());
+ MethodInvocation section = expression;
+ expect(section.target, new isInstanceOf<MethodInvocation>());
expect(section.operator, isNotNull);
expect(section.methodName, isNotNull);
expect(section.typeArguments, isNotNull);
@@ -4826,14 +5343,24 @@
}
void test_parseCascadeSection_p() {
- PropertyAccess section = parse4("parseCascadeSection", "..a");
+ createParser('..a');
+ Expression expression = parser.parseCascadeSection();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<PropertyAccess>());
+ PropertyAccess section = expression;
expect(section.target, isNull);
expect(section.operator, isNotNull);
expect(section.propertyName, isNotNull);
}
void test_parseCascadeSection_p_assign() {
- AssignmentExpression section = parse4("parseCascadeSection", "..a = 3");
+ createParser('..a = 3');
+ Expression expression = parser.parseCascadeSection();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<AssignmentExpression>());
+ AssignmentExpression section = expression;
expect(section.leftHandSide, isNotNull);
expect(section.operator, isNotNull);
Expression rhs = section.rightHandSide;
@@ -4841,8 +5368,12 @@
}
void test_parseCascadeSection_p_assign_withCascade() {
- AssignmentExpression section =
- parse4("parseCascadeSection", "..a = 3..m()");
+ createParser('..a = 3..m()');
+ Expression expression = parser.parseCascadeSection();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<AssignmentExpression>());
+ AssignmentExpression section = expression;
expect(section.leftHandSide, isNotNull);
expect(section.operator, isNotNull);
Expression rhs = section.rightHandSide;
@@ -4852,8 +5383,12 @@
void test_parseCascadeSection_p_assign_withCascade_typeArgumentComments() {
enableGenericMethodComments = true;
- AssignmentExpression section =
- parse4("parseCascadeSection", "..a = 3..m/*<E>*/()");
+ createParser('..a = 3..m/*<E>*/()');
+ Expression expression = parser.parseCascadeSection();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<AssignmentExpression>());
+ AssignmentExpression section = expression;
expect(section.leftHandSide, isNotNull);
expect(section.operator, isNotNull);
Expression rhs = section.rightHandSide;
@@ -4863,8 +5398,12 @@
void test_parseCascadeSection_p_assign_withCascade_typeArguments() {
enableGenericMethods = true;
- AssignmentExpression section =
- parse4("parseCascadeSection", "..a = 3..m<E>()");
+ createParser('..a = 3..m<E>()');
+ Expression expression = parser.parseCascadeSection();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<AssignmentExpression>());
+ AssignmentExpression section = expression;
expect(section.leftHandSide, isNotNull);
expect(section.operator, isNotNull);
Expression rhs = section.rightHandSide;
@@ -4873,14 +5412,24 @@
}
void test_parseCascadeSection_p_builtIn() {
- PropertyAccess section = parse4("parseCascadeSection", "..as");
+ createParser('..as');
+ Expression expression = parser.parseCascadeSection();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<PropertyAccess>());
+ PropertyAccess section = expression;
expect(section.target, isNull);
expect(section.operator, isNotNull);
expect(section.propertyName, isNotNull);
}
void test_parseCascadeSection_pa() {
- MethodInvocation section = parse4("parseCascadeSection", "..a(b)");
+ createParser('..a(b)');
+ Expression expression = parser.parseCascadeSection();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<MethodInvocation>());
+ MethodInvocation section = expression;
expect(section.target, isNull);
expect(section.operator, isNotNull);
expect(section.methodName, isNotNull);
@@ -4891,7 +5440,12 @@
void test_parseCascadeSection_pa_typeArgumentComments() {
enableGenericMethodComments = true;
- MethodInvocation section = parse4("parseCascadeSection", "..a/*<E>*/(b)");
+ createParser('..a/*<E>*/(b)');
+ Expression expression = parser.parseCascadeSection();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<MethodInvocation>());
+ MethodInvocation section = expression;
expect(section.target, isNull);
expect(section.operator, isNotNull);
expect(section.methodName, isNotNull);
@@ -4902,7 +5456,12 @@
void test_parseCascadeSection_pa_typeArguments() {
enableGenericMethods = true;
- MethodInvocation section = parse4("parseCascadeSection", "..a<E>(b)");
+ createParser('..a<E>(b)');
+ Expression expression = parser.parseCascadeSection();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<MethodInvocation>());
+ MethodInvocation section = expression;
expect(section.target, isNull);
expect(section.operator, isNotNull);
expect(section.methodName, isNotNull);
@@ -4912,10 +5471,13 @@
}
void test_parseCascadeSection_paa() {
- FunctionExpressionInvocation section =
- parse4("parseCascadeSection", "..a(b)(c)");
- EngineTestCase.assertInstanceOf(
- (obj) => obj is MethodInvocation, MethodInvocation, section.function);
+ createParser('..a(b)(c)');
+ Expression expression = parser.parseCascadeSection();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<FunctionExpressionInvocation>());
+ FunctionExpressionInvocation section = expression;
+ expect(section.function, new isInstanceOf<MethodInvocation>());
expect(section.typeArguments, isNull);
expect(section.argumentList, isNotNull);
expect(section.argumentList.arguments, hasLength(1));
@@ -4923,10 +5485,13 @@
void test_parseCascadeSection_paa_typeArgumentComments() {
enableGenericMethodComments = true;
- FunctionExpressionInvocation section =
- parse4("parseCascadeSection", "..a/*<E>*/(b)/*<F>*/(c)");
- EngineTestCase.assertInstanceOf(
- (obj) => obj is MethodInvocation, MethodInvocation, section.function);
+ createParser('..a/*<E>*/(b)/*<F>*/(c)');
+ Expression expression = parser.parseCascadeSection();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<FunctionExpressionInvocation>());
+ FunctionExpressionInvocation section = expression;
+ expect(section.function, new isInstanceOf<MethodInvocation>());
expect(section.typeArguments, isNotNull);
expect(section.argumentList, isNotNull);
expect(section.argumentList.arguments, hasLength(1));
@@ -4934,20 +5499,26 @@
void test_parseCascadeSection_paa_typeArguments() {
enableGenericMethods = true;
- FunctionExpressionInvocation section =
- parse4("parseCascadeSection", "..a<E>(b)<F>(c)");
- EngineTestCase.assertInstanceOf(
- (obj) => obj is MethodInvocation, MethodInvocation, section.function);
+ createParser('..a<E>(b)<F>(c)');
+ Expression expression = parser.parseCascadeSection();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<FunctionExpressionInvocation>());
+ FunctionExpressionInvocation section = expression;
+ expect(section.function, new isInstanceOf<MethodInvocation>());
expect(section.typeArguments, isNotNull);
expect(section.argumentList, isNotNull);
expect(section.argumentList.arguments, hasLength(1));
}
void test_parseCascadeSection_paapaa() {
- FunctionExpressionInvocation section =
- parse4("parseCascadeSection", "..a(b)(c).d(e)(f)");
- EngineTestCase.assertInstanceOf(
- (obj) => obj is MethodInvocation, MethodInvocation, section.function);
+ createParser('..a(b)(c).d(e)(f)');
+ Expression expression = parser.parseCascadeSection();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<FunctionExpressionInvocation>());
+ FunctionExpressionInvocation section = expression;
+ expect(section.function, new isInstanceOf<MethodInvocation>());
expect(section.typeArguments, isNull);
expect(section.argumentList, isNotNull);
expect(section.argumentList.arguments, hasLength(1));
@@ -4955,10 +5526,13 @@
void test_parseCascadeSection_paapaa_typeArgumentComments() {
enableGenericMethodComments = true;
- FunctionExpressionInvocation section = parse4(
- "parseCascadeSection", "..a/*<E>*/(b)/*<F>*/(c).d/*<G>*/(e)/*<H>*/(f)");
- EngineTestCase.assertInstanceOf(
- (obj) => obj is MethodInvocation, MethodInvocation, section.function);
+ createParser('..a/*<E>*/(b)/*<F>*/(c).d/*<G>*/(e)/*<H>*/(f)');
+ Expression expression = parser.parseCascadeSection();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<FunctionExpressionInvocation>());
+ FunctionExpressionInvocation section = expression;
+ expect(section.function, new isInstanceOf<MethodInvocation>());
expect(section.typeArguments, isNotNull);
expect(section.argumentList, isNotNull);
expect(section.argumentList.arguments, hasLength(1));
@@ -4966,17 +5540,25 @@
void test_parseCascadeSection_paapaa_typeArguments() {
enableGenericMethods = true;
- FunctionExpressionInvocation section =
- parse4("parseCascadeSection", "..a<E>(b)<F>(c).d<G>(e)<H>(f)");
- EngineTestCase.assertInstanceOf(
- (obj) => obj is MethodInvocation, MethodInvocation, section.function);
+ createParser('..a<E>(b)<F>(c).d<G>(e)<H>(f)');
+ Expression expression = parser.parseCascadeSection();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<FunctionExpressionInvocation>());
+ FunctionExpressionInvocation section = expression;
+ expect(section.function, new isInstanceOf<MethodInvocation>());
expect(section.typeArguments, isNotNull);
expect(section.argumentList, isNotNull);
expect(section.argumentList.arguments, hasLength(1));
}
void test_parseCascadeSection_pap() {
- PropertyAccess section = parse4("parseCascadeSection", "..a(b).c");
+ createParser('..a(b).c');
+ Expression expression = parser.parseCascadeSection();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<PropertyAccess>());
+ PropertyAccess section = expression;
expect(section.target, isNotNull);
expect(section.operator, isNotNull);
expect(section.propertyName, isNotNull);
@@ -4984,7 +5566,12 @@
void test_parseCascadeSection_pap_typeArgumentComments() {
enableGenericMethodComments = true;
- PropertyAccess section = parse4("parseCascadeSection", "..a/*<E>*/(b).c");
+ createParser('..a/*<E>*/(b).c');
+ Expression expression = parser.parseCascadeSection();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<PropertyAccess>());
+ PropertyAccess section = expression;
expect(section.target, isNotNull);
expect(section.operator, isNotNull);
expect(section.propertyName, isNotNull);
@@ -4992,7 +5579,12 @@
void test_parseCascadeSection_pap_typeArguments() {
enableGenericMethods = true;
- PropertyAccess section = parse4("parseCascadeSection", "..a<E>(b).c");
+ createParser('..a<E>(b).c');
+ Expression expression = parser.parseCascadeSection();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<PropertyAccess>());
+ PropertyAccess section = expression;
expect(section.target, isNotNull);
expect(section.operator, isNotNull);
expect(section.propertyName, isNotNull);
@@ -5726,22 +6318,32 @@
}
void test_parseCombinator_hide() {
- HideCombinator combinator = parse4('parseCombinator', 'hide a;');
+ createParser('hide a;');
+ Combinator combinator = parser.parseCombinator();
+ expectNotNullIfNoErrors(combinator);
+ listener.assertNoErrors();
expect(combinator, new isInstanceOf<HideCombinator>());
- expect(combinator.keyword, isNotNull);
- expect(combinator.hiddenNames, hasLength(1));
+ HideCombinator hideCombinator = combinator;
+ expect(hideCombinator.keyword, isNotNull);
+ expect(hideCombinator.hiddenNames, hasLength(1));
}
void test_parseCombinator_show() {
- ShowCombinator combinator = parse4('parseCombinator', 'show a;');
+ createParser('show a;');
+ Combinator combinator = parser.parseCombinator();
+ expectNotNullIfNoErrors(combinator);
+ listener.assertNoErrors();
expect(combinator, new isInstanceOf<ShowCombinator>());
- expect(combinator.keyword, isNotNull);
- expect(combinator.shownNames, hasLength(1));
+ ShowCombinator showCombinator = combinator;
+ expect(showCombinator.keyword, isNotNull);
+ expect(showCombinator.shownNames, hasLength(1));
}
void test_parseCombinators_h() {
- List<Combinator> combinators =
- parse4("parseCombinators", "hide a;") as List<Combinator>;
+ createParser('hide a;');
+ List<Combinator> combinators = parser.parseCombinators();
+ expectNotNullIfNoErrors(combinators);
+ listener.assertNoErrors();
expect(combinators, hasLength(1));
HideCombinator combinator = combinators[0] as HideCombinator;
expect(combinator, isNotNull);
@@ -5750,8 +6352,10 @@
}
void test_parseCombinators_hs() {
- List<Combinator> combinators =
- parse4("parseCombinators", "hide a show b;") as List<Combinator>;
+ createParser('hide a show b;');
+ List<Combinator> combinators = parser.parseCombinators();
+ expectNotNullIfNoErrors(combinators);
+ listener.assertNoErrors();
expect(combinators, hasLength(2));
HideCombinator hideCombinator = combinators[0] as HideCombinator;
expect(hideCombinator, isNotNull);
@@ -5764,15 +6368,18 @@
}
void test_parseCombinators_hshs() {
- List<Combinator> combinators =
- parse4("parseCombinators", "hide a show b hide c show d;")
- as List<Combinator>;
+ createParser('hide a show b hide c show d;');
+ List<Combinator> combinators = parser.parseCombinators();
+ expectNotNullIfNoErrors(combinators);
+ listener.assertNoErrors();
expect(combinators, hasLength(4));
}
void test_parseCombinators_s() {
- List<Combinator> combinators =
- parse4("parseCombinators", "show a;") as List<Combinator>;
+ createParser('show a;');
+ List<Combinator> combinators = parser.parseCombinators();
+ expectNotNullIfNoErrors(combinators);
+ listener.assertNoErrors();
expect(combinators, hasLength(1));
ShowCombinator combinator = combinators[0] as ShowCombinator;
expect(combinator, isNotNull);
@@ -5781,75 +6388,94 @@
}
void test_parseCommentAndMetadata_c() {
- CommentAndMetadata commentAndMetadata =
- parse4("parseCommentAndMetadata", "/** 1 */ void");
+ createParser('/** 1 */ void');
+ CommentAndMetadata commentAndMetadata = parser.parseCommentAndMetadata();
+ expectNotNullIfNoErrors(commentAndMetadata);
+ listener.assertNoErrors();
expect(commentAndMetadata.comment, isNotNull);
expect(commentAndMetadata.metadata, isNull);
}
void test_parseCommentAndMetadata_cmc() {
- CommentAndMetadata commentAndMetadata =
- parse4("parseCommentAndMetadata", "/** 1 */ @A /** 2 */ void");
+ createParser('/** 1 */ @A /** 2 */ void');
+ CommentAndMetadata commentAndMetadata = parser.parseCommentAndMetadata();
+ expectNotNullIfNoErrors(commentAndMetadata);
+ listener.assertNoErrors();
expect(commentAndMetadata.comment, isNotNull);
expect(commentAndMetadata.metadata, hasLength(1));
}
void test_parseCommentAndMetadata_cmcm() {
- CommentAndMetadata commentAndMetadata =
- parse4("parseCommentAndMetadata", "/** 1 */ @A /** 2 */ @B void");
+ createParser('/** 1 */ @A /** 2 */ @B void');
+ CommentAndMetadata commentAndMetadata = parser.parseCommentAndMetadata();
+ expectNotNullIfNoErrors(commentAndMetadata);
+ listener.assertNoErrors();
expect(commentAndMetadata.comment, isNotNull);
expect(commentAndMetadata.metadata, hasLength(2));
}
void test_parseCommentAndMetadata_cmm() {
- CommentAndMetadata commentAndMetadata =
- parse4("parseCommentAndMetadata", "/** 1 */ @A @B void");
+ createParser('/** 1 */ @A @B void');
+ CommentAndMetadata commentAndMetadata = parser.parseCommentAndMetadata();
+ expectNotNullIfNoErrors(commentAndMetadata);
+ listener.assertNoErrors();
expect(commentAndMetadata.comment, isNotNull);
expect(commentAndMetadata.metadata, hasLength(2));
}
void test_parseCommentAndMetadata_m() {
- CommentAndMetadata commentAndMetadata =
- parse4("parseCommentAndMetadata", "@A void");
+ createParser('@A void');
+ CommentAndMetadata commentAndMetadata = parser.parseCommentAndMetadata();
+ expectNotNullIfNoErrors(commentAndMetadata);
+ listener.assertNoErrors();
expect(commentAndMetadata.comment, isNull);
expect(commentAndMetadata.metadata, hasLength(1));
}
void test_parseCommentAndMetadata_mcm() {
- CommentAndMetadata commentAndMetadata =
- parse4("parseCommentAndMetadata", "@A /** 1 */ @B void");
+ createParser('@A /** 1 */ @B void');
+ CommentAndMetadata commentAndMetadata = parser.parseCommentAndMetadata();
+ expectNotNullIfNoErrors(commentAndMetadata);
+ listener.assertNoErrors();
expect(commentAndMetadata.comment, isNotNull);
expect(commentAndMetadata.metadata, hasLength(2));
}
void test_parseCommentAndMetadata_mcmc() {
- CommentAndMetadata commentAndMetadata =
- parse4("parseCommentAndMetadata", "@A /** 1 */ @B /** 2 */ void");
+ createParser('@A /** 1 */ @B /** 2 */ void');
+ CommentAndMetadata commentAndMetadata = parser.parseCommentAndMetadata();
+ expectNotNullIfNoErrors(commentAndMetadata);
+ listener.assertNoErrors();
expect(commentAndMetadata.comment, isNotNull);
expect(commentAndMetadata.metadata, hasLength(2));
}
void test_parseCommentAndMetadata_mm() {
- CommentAndMetadata commentAndMetadata =
- parse4("parseCommentAndMetadata", "@A @B(x) void");
+ createParser('@A @B(x) void');
+ CommentAndMetadata commentAndMetadata = parser.parseCommentAndMetadata();
+ expectNotNullIfNoErrors(commentAndMetadata);
+ listener.assertNoErrors();
expect(commentAndMetadata.comment, isNull);
expect(commentAndMetadata.metadata, hasLength(2));
}
void test_parseCommentAndMetadata_none() {
- CommentAndMetadata commentAndMetadata =
- parse4("parseCommentAndMetadata", "void");
+ createParser('void');
+ CommentAndMetadata commentAndMetadata = parser.parseCommentAndMetadata();
+ expectNotNullIfNoErrors(commentAndMetadata);
+ listener.assertNoErrors();
expect(commentAndMetadata.comment, isNull);
expect(commentAndMetadata.metadata, isNull);
}
void test_parseCommentAndMetadata_singleLine() {
- CommentAndMetadata commentAndMetadata = parse4(
- "parseCommentAndMetadata",
- r'''
+ createParser(r'''
/// 1
/// 2
void''');
+ CommentAndMetadata commentAndMetadata = parser.parseCommentAndMetadata();
+ expectNotNullIfNoErrors(commentAndMetadata);
+ listener.assertNoErrors();
expect(commentAndMetadata.comment, isNotNull);
expect(commentAndMetadata.metadata, isNull);
}
@@ -6263,79 +6889,98 @@
}
void test_parseCompilationUnit_abstractAsPrefix_parameterized() {
- CompilationUnit unit = parse4("parseCompilationUnit",
- "abstract<dynamic> _abstract = new abstract.A();");
+ createParser('abstract<dynamic> _abstract = new abstract.A();');
+ CompilationUnit unit = parser.parseCompilationUnit2();
+ expectNotNullIfNoErrors(unit);
+ listener.assertNoErrors();
expect(unit.scriptTag, isNull);
expect(unit.directives, hasLength(0));
expect(unit.declarations, hasLength(1));
}
void test_parseCompilationUnit_builtIn_asFunctionName() {
- parse4("parseCompilationUnit", "abstract(x) => 0;");
- parse4("parseCompilationUnit", "as(x) => 0;");
- parse4("parseCompilationUnit", "dynamic(x) => 0;");
- parse4("parseCompilationUnit", "export(x) => 0;");
- parse4("parseCompilationUnit", "external(x) => 0;");
- parse4("parseCompilationUnit", "factory(x) => 0;");
- parse4("parseCompilationUnit", "get(x) => 0;");
- parse4("parseCompilationUnit", "implements(x) => 0;");
- parse4("parseCompilationUnit", "import(x) => 0;");
- parse4("parseCompilationUnit", "library(x) => 0;");
- parse4("parseCompilationUnit", "operator(x) => 0;");
- parse4("parseCompilationUnit", "part(x) => 0;");
- parse4("parseCompilationUnit", "set(x) => 0;");
- parse4("parseCompilationUnit", "static(x) => 0;");
- parse4("parseCompilationUnit", "typedef(x) => 0;");
+ ParserTestCase.parseCompilationUnit('abstract(x) => 0;');
+ ParserTestCase.parseCompilationUnit('as(x) => 0;');
+ ParserTestCase.parseCompilationUnit('dynamic(x) => 0;');
+ ParserTestCase.parseCompilationUnit('export(x) => 0;');
+ ParserTestCase.parseCompilationUnit('external(x) => 0;');
+ ParserTestCase.parseCompilationUnit('factory(x) => 0;');
+ ParserTestCase.parseCompilationUnit('get(x) => 0;');
+ ParserTestCase.parseCompilationUnit('implements(x) => 0;');
+ ParserTestCase.parseCompilationUnit('import(x) => 0;');
+ ParserTestCase.parseCompilationUnit('library(x) => 0;');
+ ParserTestCase.parseCompilationUnit('operator(x) => 0;');
+ ParserTestCase.parseCompilationUnit('part(x) => 0;');
+ ParserTestCase.parseCompilationUnit('set(x) => 0;');
+ ParserTestCase.parseCompilationUnit('static(x) => 0;');
+ ParserTestCase.parseCompilationUnit('typedef(x) => 0;');
}
void test_parseCompilationUnit_directives_multiple() {
- CompilationUnit unit =
- parse4("parseCompilationUnit", "library l;\npart 'a.dart';");
+ createParser("library l;\npart 'a.dart';");
+ CompilationUnit unit = parser.parseCompilationUnit2();
+ expectNotNullIfNoErrors(unit);
+ listener.assertNoErrors();
expect(unit.scriptTag, isNull);
expect(unit.directives, hasLength(2));
expect(unit.declarations, hasLength(0));
}
void test_parseCompilationUnit_directives_single() {
- CompilationUnit unit = parse4("parseCompilationUnit", "library l;");
+ createParser('library l;');
+ CompilationUnit unit = parser.parseCompilationUnit2();
+ expectNotNullIfNoErrors(unit);
+ listener.assertNoErrors();
expect(unit.scriptTag, isNull);
expect(unit.directives, hasLength(1));
expect(unit.declarations, hasLength(0));
}
void test_parseCompilationUnit_empty() {
- CompilationUnit unit = parse4("parseCompilationUnit", "");
+ createParser('');
+ CompilationUnit unit = parser.parseCompilationUnit2();
+ expectNotNullIfNoErrors(unit);
+ listener.assertNoErrors();
expect(unit.scriptTag, isNull);
expect(unit.directives, hasLength(0));
expect(unit.declarations, hasLength(0));
}
void test_parseCompilationUnit_exportAsPrefix() {
- CompilationUnit unit =
- parse4("parseCompilationUnit", "export.A _export = new export.A();");
+ createParser('export.A _export = new export.A();');
+ CompilationUnit unit = parser.parseCompilationUnit2();
+ expectNotNullIfNoErrors(unit);
+ listener.assertNoErrors();
expect(unit.scriptTag, isNull);
expect(unit.directives, hasLength(0));
expect(unit.declarations, hasLength(1));
}
void test_parseCompilationUnit_exportAsPrefix_parameterized() {
- CompilationUnit unit = parse4(
- "parseCompilationUnit", "export<dynamic> _export = new export.A();");
+ createParser('export<dynamic> _export = new export.A();');
+ CompilationUnit unit = parser.parseCompilationUnit2();
+ expectNotNullIfNoErrors(unit);
+ listener.assertNoErrors();
expect(unit.scriptTag, isNull);
expect(unit.directives, hasLength(0));
expect(unit.declarations, hasLength(1));
}
void test_parseCompilationUnit_operatorAsPrefix_parameterized() {
- CompilationUnit unit = parse4("parseCompilationUnit",
- "operator<dynamic> _operator = new operator.A();");
+ createParser('operator<dynamic> _operator = new operator.A();');
+ CompilationUnit unit = parser.parseCompilationUnit2();
+ expectNotNullIfNoErrors(unit);
+ listener.assertNoErrors();
expect(unit.scriptTag, isNull);
expect(unit.directives, hasLength(0));
expect(unit.declarations, hasLength(1));
}
void test_parseCompilationUnit_script() {
- CompilationUnit unit = parse4("parseCompilationUnit", "#! /bin/dart");
+ createParser('#! /bin/dart');
+ CompilationUnit unit = parser.parseCompilationUnit2();
+ expectNotNullIfNoErrors(unit);
+ listener.assertNoErrors();
expect(unit.scriptTag, isNotNull);
expect(unit.directives, hasLength(0));
expect(unit.declarations, hasLength(0));
@@ -6343,21 +6988,29 @@
void test_parseCompilationUnit_skipFunctionBody_withInterpolation() {
ParserTestCase.parseFunctionBodies = false;
- CompilationUnit unit = parse4("parseCompilationUnit", "f() { '\${n}'; }");
+ createParser('f() { "\${n}"; }');
+ CompilationUnit unit = parser.parseCompilationUnit2();
+ expectNotNullIfNoErrors(unit);
+ listener.assertNoErrors();
expect(unit.scriptTag, isNull);
expect(unit.declarations, hasLength(1));
}
void test_parseCompilationUnit_topLevelDeclaration() {
- CompilationUnit unit = parse4("parseCompilationUnit", "class A {}");
+ createParser('class A {}');
+ CompilationUnit unit = parser.parseCompilationUnit2();
+ expectNotNullIfNoErrors(unit);
+ listener.assertNoErrors();
expect(unit.scriptTag, isNull);
expect(unit.directives, hasLength(0));
expect(unit.declarations, hasLength(1));
}
void test_parseCompilationUnit_typedefAsPrefix() {
- CompilationUnit unit =
- parse4("parseCompilationUnit", "typedef.A _typedef = new typedef.A();");
+ createParser('typedef.A _typedef = new typedef.A();');
+ CompilationUnit unit = parser.parseCompilationUnit2();
+ expectNotNullIfNoErrors(unit);
+ listener.assertNoErrors();
expect(unit.scriptTag, isNull);
expect(unit.directives, hasLength(0));
expect(unit.declarations, hasLength(1));
@@ -6629,8 +7282,10 @@
}
void test_parseConditionalExpression() {
- ConditionalExpression expression =
- parse4("parseConditionalExpression", "x ? y : z");
+ createParser('x ? y : z');
+ ConditionalExpression expression = parser.parseConditionalExpression();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
expect(expression.condition, isNotNull);
expect(expression.question, isNotNull);
expect(expression.thenExpression, isNotNull);
@@ -6639,67 +7294,84 @@
}
void test_parseConfiguration_noOperator_dottedIdentifier() {
- Configuration configuration =
- parse4('parseConfiguration', "if (a.b) 'c.dart'");
+ createParser("if (a.b) 'c.dart'");
+ Configuration configuration = parser.parseConfiguration();
+ expectNotNullIfNoErrors(configuration);
+ listener.assertNoErrors();
expect(configuration.ifKeyword, isNotNull);
expect(configuration.leftParenthesis, isNotNull);
_expectDottedName(configuration.name, ["a", "b"]);
expect(configuration.equalToken, isNull);
expect(configuration.value, isNull);
expect(configuration.rightParenthesis, isNotNull);
- expect(configuration.libraryUri, isNotNull);
+ expect(configuration.uri, isNotNull);
}
void test_parseConfiguration_noOperator_simpleIdentifier() {
- Configuration configuration =
- parse4('parseConfiguration', "if (a) 'b.dart'");
+ createParser("if (a) 'b.dart'");
+ Configuration configuration = parser.parseConfiguration();
+ expectNotNullIfNoErrors(configuration);
+ listener.assertNoErrors();
expect(configuration.ifKeyword, isNotNull);
expect(configuration.leftParenthesis, isNotNull);
_expectDottedName(configuration.name, ["a"]);
expect(configuration.equalToken, isNull);
expect(configuration.value, isNull);
expect(configuration.rightParenthesis, isNotNull);
- expect(configuration.libraryUri, isNotNull);
+ expect(configuration.uri, isNotNull);
}
void test_parseConfiguration_operator_dottedIdentifier() {
- Configuration configuration =
- parse4('parseConfiguration', "if (a.b == 'c') 'd.dart'");
+ createParser("if (a.b == 'c') 'd.dart'");
+ Configuration configuration = parser.parseConfiguration();
+ expectNotNullIfNoErrors(configuration);
+ listener.assertNoErrors();
expect(configuration.ifKeyword, isNotNull);
expect(configuration.leftParenthesis, isNotNull);
_expectDottedName(configuration.name, ["a", "b"]);
expect(configuration.equalToken, isNotNull);
expect(configuration.value, isNotNull);
expect(configuration.rightParenthesis, isNotNull);
- expect(configuration.libraryUri, isNotNull);
+ expect(configuration.uri, isNotNull);
}
void test_parseConfiguration_operator_simpleIdentifier() {
- Configuration configuration =
- parse4('parseConfiguration', "if (a == 'b') 'c.dart'");
+ createParser("if (a == 'b') 'c.dart'");
+ Configuration configuration = parser.parseConfiguration();
+ expectNotNullIfNoErrors(configuration);
+ listener.assertNoErrors();
expect(configuration.ifKeyword, isNotNull);
expect(configuration.leftParenthesis, isNotNull);
_expectDottedName(configuration.name, ["a"]);
expect(configuration.equalToken, isNotNull);
expect(configuration.value, isNotNull);
expect(configuration.rightParenthesis, isNotNull);
- expect(configuration.libraryUri, isNotNull);
+ expect(configuration.uri, isNotNull);
}
void test_parseConstExpression_instanceCreation() {
- InstanceCreationExpression expression =
- parse4("parseConstExpression", "const A()");
- expect(expression.keyword, isNotNull);
- ConstructorName name = expression.constructorName;
+ createParser('const A()');
+ Expression expression = parser.parseConstExpression();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<InstanceCreationExpression>());
+ InstanceCreationExpression instanceCreation = expression;
+ expect(instanceCreation.keyword, isNotNull);
+ ConstructorName name = instanceCreation.constructorName;
expect(name, isNotNull);
expect(name.type, isNotNull);
expect(name.period, isNull);
expect(name.name, isNull);
- expect(expression.argumentList, isNotNull);
+ expect(instanceCreation.argumentList, isNotNull);
}
void test_parseConstExpression_listLiteral_typed() {
- ListLiteral literal = parse4("parseConstExpression", "const <A> []");
+ createParser('const <A> []');
+ Expression expression = parser.parseConstExpression();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<ListLiteral>());
+ ListLiteral literal = expression;
expect(literal.constKeyword, isNotNull);
expect(literal.typeArguments, isNotNull);
expect(literal.leftBracket, isNotNull);
@@ -6709,7 +7381,12 @@
void test_parseConstExpression_listLiteral_typed_genericComment() {
enableGenericMethodComments = true;
- ListLiteral literal = parse4("parseConstExpression", "const /*<A>*/ []");
+ createParser('const /*<A>*/ []');
+ Expression expression = parser.parseConstExpression();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<ListLiteral>());
+ ListLiteral literal = expression;
expect(literal.constKeyword, isNotNull);
expect(literal.typeArguments, isNotNull);
expect(literal.leftBracket, isNotNull);
@@ -6718,7 +7395,12 @@
}
void test_parseConstExpression_listLiteral_untyped() {
- ListLiteral literal = parse4("parseConstExpression", "const []");
+ createParser('const []');
+ Expression expression = parser.parseConstExpression();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<ListLiteral>());
+ ListLiteral literal = expression;
expect(literal.constKeyword, isNotNull);
expect(literal.typeArguments, isNull);
expect(literal.leftBracket, isNotNull);
@@ -6727,7 +7409,12 @@
}
void test_parseConstExpression_mapLiteral_typed() {
- MapLiteral literal = parse4("parseConstExpression", "const <A, B> {}");
+ createParser('const <A, B> {}');
+ Expression expression = parser.parseConstExpression();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<MapLiteral>());
+ MapLiteral literal = expression;
expect(literal.leftBracket, isNotNull);
expect(literal.entries, hasLength(0));
expect(literal.rightBracket, isNotNull);
@@ -6736,7 +7423,12 @@
void test_parseConstExpression_mapLiteral_typed_genericComment() {
enableGenericMethodComments = true;
- MapLiteral literal = parse4("parseConstExpression", "const /*<A, B>*/ {}");
+ createParser('const /*<A, B>*/ {}');
+ Expression expression = parser.parseConstExpression();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<MapLiteral>());
+ MapLiteral literal = expression;
expect(literal.leftBracket, isNotNull);
expect(literal.entries, hasLength(0));
expect(literal.rightBracket, isNotNull);
@@ -6744,7 +7436,12 @@
}
void test_parseConstExpression_mapLiteral_untyped() {
- MapLiteral literal = parse4("parseConstExpression", "const {}");
+ createParser('const {}');
+ Expression expression = parser.parseConstExpression();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<MapLiteral>());
+ MapLiteral literal = expression;
expect(literal.leftBracket, isNotNull);
expect(literal.entries, hasLength(0));
expect(literal.rightBracket, isNotNull);
@@ -6792,7 +7489,7 @@
void test_parseConstructorFieldInitializer_qualified() {
ConstructorFieldInitializer invocation =
- parse2("parseConstructorFieldInitializer", [true], "this.a = b");
+ parse("parseConstructorFieldInitializer", [true], "this.a = b");
expect(invocation.equals, isNotNull);
expect(invocation.expression, isNotNull);
expect(invocation.fieldName, isNotNull);
@@ -6802,7 +7499,7 @@
void test_parseConstructorFieldInitializer_unqualified() {
ConstructorFieldInitializer invocation =
- parse2("parseConstructorFieldInitializer", [false], "a = b");
+ parse("parseConstructorFieldInitializer", [false], "a = b");
expect(invocation.equals, isNotNull);
expect(invocation.expression, isNotNull);
expect(invocation.fieldName, isNotNull);
@@ -6811,44 +7508,60 @@
}
void test_parseConstructorName_named_noPrefix() {
- ConstructorName name = parse4("parseConstructorName", "A.n;");
+ createParser('A.n;');
+ ConstructorName name = parser.parseConstructorName();
+ expectNotNullIfNoErrors(name);
+ listener.assertNoErrors();
expect(name.type, isNotNull);
expect(name.period, isNull);
expect(name.name, isNull);
}
void test_parseConstructorName_named_prefixed() {
- ConstructorName name = parse4("parseConstructorName", "p.A.n;");
+ createParser('p.A.n;');
+ ConstructorName name = parser.parseConstructorName();
+ expectNotNullIfNoErrors(name);
+ listener.assertNoErrors();
expect(name.type, isNotNull);
expect(name.period, isNotNull);
expect(name.name, isNotNull);
}
void test_parseConstructorName_unnamed_noPrefix() {
- ConstructorName name = parse4("parseConstructorName", "A;");
+ createParser('A;');
+ ConstructorName name = parser.parseConstructorName();
+ expectNotNullIfNoErrors(name);
+ listener.assertNoErrors();
expect(name.type, isNotNull);
expect(name.period, isNull);
expect(name.name, isNull);
}
void test_parseConstructorName_unnamed_prefixed() {
- ConstructorName name = parse4("parseConstructorName", "p.A;");
+ createParser('p.A;');
+ ConstructorName name = parser.parseConstructorName();
+ expectNotNullIfNoErrors(name);
+ listener.assertNoErrors();
expect(name.type, isNotNull);
expect(name.period, isNull);
expect(name.name, isNull);
}
void test_parseContinueStatement_label() {
- ContinueStatement statement = parse4("parseContinueStatement",
- "continue foo;", [ParserErrorCode.CONTINUE_OUTSIDE_OF_LOOP]);
+ createParser('continue foo;');
+ ContinueStatement statement = parser.parseContinueStatement();
+ expectNotNullIfNoErrors(statement);
+ listener.assertErrorsWithCodes([ParserErrorCode.CONTINUE_OUTSIDE_OF_LOOP]);
expect(statement.continueKeyword, isNotNull);
expect(statement.label, isNotNull);
expect(statement.semicolon, isNotNull);
}
void test_parseContinueStatement_noLabel() {
- ContinueStatement statement = parse4("parseContinueStatement", "continue;",
- [ParserErrorCode.CONTINUE_OUTSIDE_OF_LOOP]);
+ createParser('continue;');
+ ContinueStatement statement = parser.parseContinueStatement();
+ expectNotNullIfNoErrors(statement);
+ listener.assertErrorsWithCodes([ParserErrorCode.CONTINUE_OUTSIDE_OF_LOOP]);
expect(statement.continueKeyword, isNotNull);
expect(statement.label, isNull);
expect(statement.semicolon, isNotNull);
@@ -6944,14 +7657,22 @@
}
void test_parseDocumentationComment_block() {
- Comment comment = parse4("parseDocumentationComment", "/** */ class");
+ createParser('/** */ class');
+ Comment comment = parser
+ .parseDocumentationComment(parser.parseDocumentationCommentTokens());
+ expectNotNullIfNoErrors(comment);
+ listener.assertNoErrors();
expect(comment.isBlock, isFalse);
expect(comment.isDocumentation, isTrue);
expect(comment.isEndOfLine, isFalse);
}
void test_parseDocumentationComment_block_withReference() {
- Comment comment = parse4("parseDocumentationComment", "/** [a] */ class");
+ createParser('/** [a] */ class');
+ Comment comment = parser
+ .parseDocumentationComment(parser.parseDocumentationCommentTokens());
+ expectNotNullIfNoErrors(comment);
+ listener.assertNoErrors();
expect(comment.isBlock, isFalse);
expect(comment.isDocumentation, isTrue);
expect(comment.isEndOfLine, isFalse);
@@ -6963,14 +7684,21 @@
}
void test_parseDocumentationComment_endOfLine() {
- Comment comment = parse4("parseDocumentationComment", "/// \n/// \n class");
+ createParser('/// \n/// \n class');
+ Comment comment = parser
+ .parseDocumentationComment(parser.parseDocumentationCommentTokens());
+ expectNotNullIfNoErrors(comment);
+ listener.assertNoErrors();
expect(comment.isBlock, isFalse);
expect(comment.isDocumentation, isTrue);
expect(comment.isEndOfLine, isFalse);
}
void test_parseDoStatement() {
- DoStatement statement = parse4("parseDoStatement", "do {} while (x);");
+ createParser('do {} while (x);');
+ DoStatement statement = parser.parseDoStatement();
+ expectNotNullIfNoErrors(statement);
+ listener.assertNoErrors();
expect(statement.doKeyword, isNotNull);
expect(statement.body, isNotNull);
expect(statement.whileKeyword, isNotNull);
@@ -6981,17 +7709,26 @@
}
void test_parseDottedName_multiple() {
- DottedName name = parse4("parseDottedName", "a.b.c");
+ createParser('a.b.c');
+ DottedName name = parser.parseDottedName();
+ expectNotNullIfNoErrors(name);
+ listener.assertNoErrors();
_expectDottedName(name, ["a", "b", "c"]);
}
void test_parseDottedName_single() {
- DottedName name = parse4("parseDottedName", "a");
+ createParser('a');
+ DottedName name = parser.parseDottedName();
+ expectNotNullIfNoErrors(name);
+ listener.assertNoErrors();
_expectDottedName(name, ["a"]);
}
void test_parseEmptyStatement() {
- EmptyStatement statement = parse4("parseEmptyStatement", ";");
+ createParser(';');
+ EmptyStatement statement = parser.parseEmptyStatement();
+ expectNotNullIfNoErrors(statement);
+ listener.assertNoErrors();
expect(statement.semicolon, isNotNull);
}
@@ -7531,397 +8268,488 @@
}
void test_parseFormalParameterList_empty() {
- FormalParameterList parameterList =
- parse4("parseFormalParameterList", "()");
- expect(parameterList.leftParenthesis, isNotNull);
- expect(parameterList.leftDelimiter, isNull);
- expect(parameterList.parameters, hasLength(0));
- expect(parameterList.rightDelimiter, isNull);
- expect(parameterList.rightParenthesis, isNotNull);
+ createParser('()');
+ FormalParameterList list = parser.parseFormalParameterList();
+ expectNotNullIfNoErrors(list);
+ listener.assertNoErrors();
+ expect(list.leftParenthesis, isNotNull);
+ expect(list.leftDelimiter, isNull);
+ expect(list.parameters, hasLength(0));
+ expect(list.rightDelimiter, isNull);
+ expect(list.rightParenthesis, isNotNull);
}
void test_parseFormalParameterList_named_multiple() {
- FormalParameterList parameterList =
- parse4("parseFormalParameterList", "({A a : 1, B b, C c : 3})");
- expect(parameterList.leftParenthesis, isNotNull);
- expect(parameterList.leftDelimiter, isNotNull);
- expect(parameterList.parameters, hasLength(3));
- expect(parameterList.rightDelimiter, isNotNull);
- expect(parameterList.rightParenthesis, isNotNull);
+ createParser('({A a : 1, B b, C c : 3})');
+ FormalParameterList list = parser.parseFormalParameterList();
+ expectNotNullIfNoErrors(list);
+ listener.assertNoErrors();
+ expect(list.leftParenthesis, isNotNull);
+ expect(list.leftDelimiter, isNotNull);
+ expect(list.parameters, hasLength(3));
+ expect(list.rightDelimiter, isNotNull);
+ expect(list.rightParenthesis, isNotNull);
}
void test_parseFormalParameterList_named_single() {
- FormalParameterList parameterList =
- parse4("parseFormalParameterList", "({A a})");
- expect(parameterList.leftParenthesis, isNotNull);
- expect(parameterList.leftDelimiter, isNotNull);
- expect(parameterList.parameters, hasLength(1));
- expect(parameterList.rightDelimiter, isNotNull);
- expect(parameterList.rightParenthesis, isNotNull);
+ createParser('({A a})');
+ FormalParameterList list = parser.parseFormalParameterList();
+ expectNotNullIfNoErrors(list);
+ listener.assertNoErrors();
+ expect(list.leftParenthesis, isNotNull);
+ expect(list.leftDelimiter, isNotNull);
+ expect(list.parameters, hasLength(1));
+ expect(list.rightDelimiter, isNotNull);
+ expect(list.rightParenthesis, isNotNull);
}
void test_parseFormalParameterList_named_trailing_comma() {
- FormalParameterList parameterList =
- parse4("parseFormalParameterList", "(A a, {B b,})");
- expect(parameterList.leftParenthesis, isNotNull);
- expect(parameterList.leftDelimiter, isNotNull);
- expect(parameterList.parameters, hasLength(2));
- expect(parameterList.rightDelimiter, isNotNull);
- expect(parameterList.rightParenthesis, isNotNull);
+ createParser('(A a, {B b,})');
+ FormalParameterList list = parser.parseFormalParameterList();
+ expectNotNullIfNoErrors(list);
+ listener.assertNoErrors();
+ expect(list.leftParenthesis, isNotNull);
+ expect(list.leftDelimiter, isNotNull);
+ expect(list.parameters, hasLength(2));
+ expect(list.rightDelimiter, isNotNull);
+ expect(list.rightParenthesis, isNotNull);
}
void test_parseFormalParameterList_normal_multiple() {
- FormalParameterList parameterList =
- parse4("parseFormalParameterList", "(A a, B b, C c)");
- expect(parameterList.leftParenthesis, isNotNull);
- expect(parameterList.leftDelimiter, isNull);
- expect(parameterList.parameters, hasLength(3));
- expect(parameterList.rightDelimiter, isNull);
- expect(parameterList.rightParenthesis, isNotNull);
+ createParser('(A a, B b, C c)');
+ FormalParameterList list = parser.parseFormalParameterList();
+ expectNotNullIfNoErrors(list);
+ listener.assertNoErrors();
+ expect(list.leftParenthesis, isNotNull);
+ expect(list.leftDelimiter, isNull);
+ expect(list.parameters, hasLength(3));
+ expect(list.rightDelimiter, isNull);
+ expect(list.rightParenthesis, isNotNull);
}
void test_parseFormalParameterList_normal_named() {
- FormalParameterList parameterList =
- parse4("parseFormalParameterList", "(A a, {B b})");
- expect(parameterList.leftParenthesis, isNotNull);
- expect(parameterList.leftDelimiter, isNotNull);
- expect(parameterList.parameters, hasLength(2));
- expect(parameterList.rightDelimiter, isNotNull);
- expect(parameterList.rightParenthesis, isNotNull);
+ createParser('(A a, {B b})');
+ FormalParameterList list = parser.parseFormalParameterList();
+ expectNotNullIfNoErrors(list);
+ listener.assertNoErrors();
+ expect(list.leftParenthesis, isNotNull);
+ expect(list.leftDelimiter, isNotNull);
+ expect(list.parameters, hasLength(2));
+ expect(list.rightDelimiter, isNotNull);
+ expect(list.rightParenthesis, isNotNull);
}
void test_parseFormalParameterList_normal_positional() {
- FormalParameterList parameterList =
- parse4("parseFormalParameterList", "(A a, [B b])");
- expect(parameterList.leftParenthesis, isNotNull);
- expect(parameterList.leftDelimiter, isNotNull);
- expect(parameterList.parameters, hasLength(2));
- expect(parameterList.rightDelimiter, isNotNull);
- expect(parameterList.rightParenthesis, isNotNull);
+ createParser('(A a, [B b])');
+ FormalParameterList list = parser.parseFormalParameterList();
+ expectNotNullIfNoErrors(list);
+ listener.assertNoErrors();
+ expect(list.leftParenthesis, isNotNull);
+ expect(list.leftDelimiter, isNotNull);
+ expect(list.parameters, hasLength(2));
+ expect(list.rightDelimiter, isNotNull);
+ expect(list.rightParenthesis, isNotNull);
}
void test_parseFormalParameterList_normal_single() {
- FormalParameterList parameterList =
- parse4("parseFormalParameterList", "(A a)");
- expect(parameterList.leftParenthesis, isNotNull);
- expect(parameterList.leftDelimiter, isNull);
- expect(parameterList.parameters, hasLength(1));
- expect(parameterList.rightDelimiter, isNull);
- expect(parameterList.rightParenthesis, isNotNull);
+ createParser('(A a)');
+ FormalParameterList list = parser.parseFormalParameterList();
+ expectNotNullIfNoErrors(list);
+ listener.assertNoErrors();
+ expect(list.leftParenthesis, isNotNull);
+ expect(list.leftDelimiter, isNull);
+ expect(list.parameters, hasLength(1));
+ expect(list.rightDelimiter, isNull);
+ expect(list.rightParenthesis, isNotNull);
}
void test_parseFormalParameterList_normal_single_trailing_comma() {
- FormalParameterList parameterList =
- parse4("parseFormalParameterList", "(A a,)");
- expect(parameterList.leftParenthesis, isNotNull);
- expect(parameterList.leftDelimiter, isNull);
- expect(parameterList.parameters, hasLength(1));
- expect(parameterList.rightDelimiter, isNull);
- expect(parameterList.rightParenthesis, isNotNull);
+ createParser('(A a,)');
+ FormalParameterList list = parser.parseFormalParameterList();
+ expectNotNullIfNoErrors(list);
+ listener.assertNoErrors();
+ expect(list.leftParenthesis, isNotNull);
+ expect(list.leftDelimiter, isNull);
+ expect(list.parameters, hasLength(1));
+ expect(list.rightDelimiter, isNull);
+ expect(list.rightParenthesis, isNotNull);
}
void test_parseFormalParameterList_positional_multiple() {
- FormalParameterList parameterList =
- parse4("parseFormalParameterList", "([A a = null, B b, C c = null])");
- expect(parameterList.leftParenthesis, isNotNull);
- expect(parameterList.leftDelimiter, isNotNull);
- expect(parameterList.parameters, hasLength(3));
- expect(parameterList.rightDelimiter, isNotNull);
- expect(parameterList.rightParenthesis, isNotNull);
+ createParser('([A a = null, B b, C c = null])');
+ FormalParameterList list = parser.parseFormalParameterList();
+ expectNotNullIfNoErrors(list);
+ listener.assertNoErrors();
+ expect(list.leftParenthesis, isNotNull);
+ expect(list.leftDelimiter, isNotNull);
+ expect(list.parameters, hasLength(3));
+ expect(list.rightDelimiter, isNotNull);
+ expect(list.rightParenthesis, isNotNull);
}
void test_parseFormalParameterList_positional_single() {
- FormalParameterList parameterList =
- parse4("parseFormalParameterList", "([A a = null])");
- expect(parameterList.leftParenthesis, isNotNull);
- expect(parameterList.leftDelimiter, isNotNull);
- expect(parameterList.parameters, hasLength(1));
- expect(parameterList.rightDelimiter, isNotNull);
- expect(parameterList.rightParenthesis, isNotNull);
+ createParser('([A a = null])');
+ FormalParameterList list = parser.parseFormalParameterList();
+ expectNotNullIfNoErrors(list);
+ listener.assertNoErrors();
+ expect(list.leftParenthesis, isNotNull);
+ expect(list.leftDelimiter, isNotNull);
+ expect(list.parameters, hasLength(1));
+ expect(list.rightDelimiter, isNotNull);
+ expect(list.rightParenthesis, isNotNull);
}
void test_parseFormalParameterList_positional_trailing_comma() {
- FormalParameterList parameterList =
- parse4("parseFormalParameterList", "(A a, [B b,])");
- expect(parameterList.leftParenthesis, isNotNull);
- expect(parameterList.leftDelimiter, isNotNull);
- expect(parameterList.parameters, hasLength(2));
- expect(parameterList.rightDelimiter, isNotNull);
- expect(parameterList.rightParenthesis, isNotNull);
+ createParser('(A a, [B b,])');
+ FormalParameterList list = parser.parseFormalParameterList();
+ expectNotNullIfNoErrors(list);
+ listener.assertNoErrors();
+ expect(list.leftParenthesis, isNotNull);
+ expect(list.leftDelimiter, isNotNull);
+ expect(list.parameters, hasLength(2));
+ expect(list.rightDelimiter, isNotNull);
+ expect(list.rightParenthesis, isNotNull);
}
void test_parseFormalParameterList_prefixedType() {
- FormalParameterList parameterList =
- parse4("parseFormalParameterList", "(io.File f)");
- expect(parameterList.leftParenthesis, isNotNull);
- expect(parameterList.leftDelimiter, isNull);
- expect(parameterList.parameters, hasLength(1));
- expect(parameterList.parameters[0].toSource(), 'io.File f');
- expect(parameterList.rightDelimiter, isNull);
- expect(parameterList.rightParenthesis, isNotNull);
+ createParser('(io.File f)');
+ FormalParameterList list = parser.parseFormalParameterList();
+ expectNotNullIfNoErrors(list);
+ listener.assertNoErrors();
+ expect(list.leftParenthesis, isNotNull);
+ expect(list.leftDelimiter, isNull);
+ expect(list.parameters, hasLength(1));
+ expect(list.parameters[0].toSource(), 'io.File f');
+ expect(list.rightDelimiter, isNull);
+ expect(list.rightParenthesis, isNotNull);
}
void test_parseFormalParameterList_prefixedType_partial() {
- FormalParameterList parameterList = parse4(
- "parseFormalParameterList", "(io.)", [
+ createParser('(io.)');
+ FormalParameterList list = parser.parseFormalParameterList();
+ expectNotNullIfNoErrors(list);
+ listener.assertErrorsWithCodes([
ParserErrorCode.MISSING_IDENTIFIER,
ParserErrorCode.MISSING_IDENTIFIER
]);
- expect(parameterList.leftParenthesis, isNotNull);
- expect(parameterList.leftDelimiter, isNull);
- expect(parameterList.parameters, hasLength(1));
- expect(parameterList.parameters[0].toSource(), 'io. ');
- expect(parameterList.rightDelimiter, isNull);
- expect(parameterList.rightParenthesis, isNotNull);
+ expect(list.leftParenthesis, isNotNull);
+ expect(list.leftDelimiter, isNull);
+ expect(list.parameters, hasLength(1));
+ expect(list.parameters[0].toSource(), 'io. ');
+ expect(list.rightDelimiter, isNull);
+ expect(list.rightParenthesis, isNotNull);
}
void test_parseFormalParameterList_prefixedType_partial2() {
- FormalParameterList parameterList = parse4(
- "parseFormalParameterList", "(io.,a)", [
+ createParser('(io.,a)');
+ FormalParameterList list = parser.parseFormalParameterList();
+ expectNotNullIfNoErrors(list);
+ listener.assertErrorsWithCodes([
ParserErrorCode.MISSING_IDENTIFIER,
ParserErrorCode.MISSING_IDENTIFIER
]);
- expect(parameterList.leftParenthesis, isNotNull);
- expect(parameterList.leftDelimiter, isNull);
- expect(parameterList.parameters, hasLength(2));
- expect(parameterList.parameters[0].toSource(), 'io. ');
- expect(parameterList.parameters[1].toSource(), 'a');
- expect(parameterList.rightDelimiter, isNull);
- expect(parameterList.rightParenthesis, isNotNull);
+ expect(list.leftParenthesis, isNotNull);
+ expect(list.leftDelimiter, isNull);
+ expect(list.parameters, hasLength(2));
+ expect(list.parameters[0].toSource(), 'io. ');
+ expect(list.parameters[1].toSource(), 'a');
+ expect(list.rightDelimiter, isNull);
+ expect(list.rightParenthesis, isNotNull);
}
void test_parseForStatement_each_await() {
- ForEachStatement statement =
- parse4("parseForStatement", "await for (element in list) {}");
- expect(statement.awaitKeyword, isNotNull);
- expect(statement.forKeyword, isNotNull);
- expect(statement.leftParenthesis, isNotNull);
- expect(statement.loopVariable, isNull);
- expect(statement.identifier, isNotNull);
- expect(statement.inKeyword, isNotNull);
- expect(statement.iterable, isNotNull);
- expect(statement.rightParenthesis, isNotNull);
- expect(statement.body, isNotNull);
+ createParser('await for (element in list) {}');
+ Statement statement = parser.parseForStatement();
+ expectNotNullIfNoErrors(statement);
+ listener.assertNoErrors();
+ expect(statement, new isInstanceOf<ForEachStatement>());
+ ForEachStatement forStatement = statement;
+ expect(forStatement.awaitKeyword, isNotNull);
+ expect(forStatement.forKeyword, isNotNull);
+ expect(forStatement.leftParenthesis, isNotNull);
+ expect(forStatement.loopVariable, isNull);
+ expect(forStatement.identifier, isNotNull);
+ expect(forStatement.inKeyword, isNotNull);
+ expect(forStatement.iterable, isNotNull);
+ expect(forStatement.rightParenthesis, isNotNull);
+ expect(forStatement.body, isNotNull);
}
void test_parseForStatement_each_identifier() {
- ForEachStatement statement =
- parse4("parseForStatement", "for (element in list) {}");
- expect(statement.awaitKeyword, isNull);
- expect(statement.forKeyword, isNotNull);
- expect(statement.leftParenthesis, isNotNull);
- expect(statement.loopVariable, isNull);
- expect(statement.identifier, isNotNull);
- expect(statement.inKeyword, isNotNull);
- expect(statement.iterable, isNotNull);
- expect(statement.rightParenthesis, isNotNull);
- expect(statement.body, isNotNull);
+ createParser('for (element in list) {}');
+ Statement statement = parser.parseForStatement();
+ expectNotNullIfNoErrors(statement);
+ listener.assertNoErrors();
+ expect(statement, new isInstanceOf<ForEachStatement>());
+ ForEachStatement forStatement = statement;
+ expect(forStatement.awaitKeyword, isNull);
+ expect(forStatement.forKeyword, isNotNull);
+ expect(forStatement.leftParenthesis, isNotNull);
+ expect(forStatement.loopVariable, isNull);
+ expect(forStatement.identifier, isNotNull);
+ expect(forStatement.inKeyword, isNotNull);
+ expect(forStatement.iterable, isNotNull);
+ expect(forStatement.rightParenthesis, isNotNull);
+ expect(forStatement.body, isNotNull);
}
void test_parseForStatement_each_noType_metadata() {
- ForEachStatement statement =
- parse4("parseForStatement", "for (@A var element in list) {}");
- expect(statement.awaitKeyword, isNull);
- expect(statement.forKeyword, isNotNull);
- expect(statement.leftParenthesis, isNotNull);
- expect(statement.loopVariable, isNotNull);
- expect(statement.loopVariable.metadata, hasLength(1));
- expect(statement.identifier, isNull);
- expect(statement.inKeyword, isNotNull);
- expect(statement.iterable, isNotNull);
- expect(statement.rightParenthesis, isNotNull);
- expect(statement.body, isNotNull);
+ createParser('for (@A var element in list) {}');
+ Statement statement = parser.parseForStatement();
+ expectNotNullIfNoErrors(statement);
+ listener.assertNoErrors();
+ expect(statement, new isInstanceOf<ForEachStatement>());
+ ForEachStatement forStatement = statement;
+ expect(forStatement.awaitKeyword, isNull);
+ expect(forStatement.forKeyword, isNotNull);
+ expect(forStatement.leftParenthesis, isNotNull);
+ expect(forStatement.loopVariable, isNotNull);
+ expect(forStatement.loopVariable.metadata, hasLength(1));
+ expect(forStatement.identifier, isNull);
+ expect(forStatement.inKeyword, isNotNull);
+ expect(forStatement.iterable, isNotNull);
+ expect(forStatement.rightParenthesis, isNotNull);
+ expect(forStatement.body, isNotNull);
}
void test_parseForStatement_each_type() {
- ForEachStatement statement =
- parse4("parseForStatement", "for (A element in list) {}");
- expect(statement.awaitKeyword, isNull);
- expect(statement.forKeyword, isNotNull);
- expect(statement.leftParenthesis, isNotNull);
- expect(statement.loopVariable, isNotNull);
- expect(statement.identifier, isNull);
- expect(statement.inKeyword, isNotNull);
- expect(statement.iterable, isNotNull);
- expect(statement.rightParenthesis, isNotNull);
- expect(statement.body, isNotNull);
+ createParser('for (A element in list) {}');
+ Statement statement = parser.parseForStatement();
+ expectNotNullIfNoErrors(statement);
+ listener.assertNoErrors();
+ expect(statement, new isInstanceOf<ForEachStatement>());
+ ForEachStatement forStatement = statement;
+ expect(forStatement.awaitKeyword, isNull);
+ expect(forStatement.forKeyword, isNotNull);
+ expect(forStatement.leftParenthesis, isNotNull);
+ expect(forStatement.loopVariable, isNotNull);
+ expect(forStatement.identifier, isNull);
+ expect(forStatement.inKeyword, isNotNull);
+ expect(forStatement.iterable, isNotNull);
+ expect(forStatement.rightParenthesis, isNotNull);
+ expect(forStatement.body, isNotNull);
}
void test_parseForStatement_each_var() {
- ForEachStatement statement =
- parse4("parseForStatement", "for (var element in list) {}");
- expect(statement.awaitKeyword, isNull);
- expect(statement.forKeyword, isNotNull);
- expect(statement.leftParenthesis, isNotNull);
- expect(statement.loopVariable, isNotNull);
- expect(statement.identifier, isNull);
- expect(statement.inKeyword, isNotNull);
- expect(statement.iterable, isNotNull);
- expect(statement.rightParenthesis, isNotNull);
- expect(statement.body, isNotNull);
+ createParser('for (var element in list) {}');
+ Statement statement = parser.parseForStatement();
+ expectNotNullIfNoErrors(statement);
+ listener.assertNoErrors();
+ expect(statement, new isInstanceOf<ForEachStatement>());
+ ForEachStatement forStatement = statement;
+ expect(forStatement.awaitKeyword, isNull);
+ expect(forStatement.forKeyword, isNotNull);
+ expect(forStatement.leftParenthesis, isNotNull);
+ expect(forStatement.loopVariable, isNotNull);
+ expect(forStatement.identifier, isNull);
+ expect(forStatement.inKeyword, isNotNull);
+ expect(forStatement.iterable, isNotNull);
+ expect(forStatement.rightParenthesis, isNotNull);
+ expect(forStatement.body, isNotNull);
}
void test_parseForStatement_loop_c() {
- ForStatement statement =
- parse4("parseForStatement", "for (; i < count;) {}");
- expect(statement.forKeyword, isNotNull);
- expect(statement.leftParenthesis, isNotNull);
- expect(statement.variables, isNull);
- expect(statement.initialization, isNull);
- expect(statement.leftSeparator, isNotNull);
- expect(statement.condition, isNotNull);
- expect(statement.rightSeparator, isNotNull);
- expect(statement.updaters, hasLength(0));
- expect(statement.rightParenthesis, isNotNull);
- expect(statement.body, isNotNull);
+ createParser('for (; i < count;) {}');
+ Statement statement = parser.parseForStatement();
+ expectNotNullIfNoErrors(statement);
+ listener.assertNoErrors();
+ expect(statement, new isInstanceOf<ForStatement>());
+ ForStatement forStatement = statement;
+ expect(forStatement.forKeyword, isNotNull);
+ expect(forStatement.leftParenthesis, isNotNull);
+ expect(forStatement.variables, isNull);
+ expect(forStatement.initialization, isNull);
+ expect(forStatement.leftSeparator, isNotNull);
+ expect(forStatement.condition, isNotNull);
+ expect(forStatement.rightSeparator, isNotNull);
+ expect(forStatement.updaters, hasLength(0));
+ expect(forStatement.rightParenthesis, isNotNull);
+ expect(forStatement.body, isNotNull);
}
void test_parseForStatement_loop_cu() {
- ForStatement statement =
- parse4("parseForStatement", "for (; i < count; i++) {}");
- expect(statement.forKeyword, isNotNull);
- expect(statement.leftParenthesis, isNotNull);
- expect(statement.variables, isNull);
- expect(statement.initialization, isNull);
- expect(statement.leftSeparator, isNotNull);
- expect(statement.condition, isNotNull);
- expect(statement.rightSeparator, isNotNull);
- expect(statement.updaters, hasLength(1));
- expect(statement.rightParenthesis, isNotNull);
- expect(statement.body, isNotNull);
+ createParser('for (; i < count; i++) {}');
+ Statement statement = parser.parseForStatement();
+ expectNotNullIfNoErrors(statement);
+ listener.assertNoErrors();
+ expect(statement, new isInstanceOf<ForStatement>());
+ ForStatement forStatement = statement;
+ expect(forStatement.forKeyword, isNotNull);
+ expect(forStatement.leftParenthesis, isNotNull);
+ expect(forStatement.variables, isNull);
+ expect(forStatement.initialization, isNull);
+ expect(forStatement.leftSeparator, isNotNull);
+ expect(forStatement.condition, isNotNull);
+ expect(forStatement.rightSeparator, isNotNull);
+ expect(forStatement.updaters, hasLength(1));
+ expect(forStatement.rightParenthesis, isNotNull);
+ expect(forStatement.body, isNotNull);
}
void test_parseForStatement_loop_ecu() {
- ForStatement statement =
- parse4("parseForStatement", "for (i--; i < count; i++) {}");
- expect(statement.forKeyword, isNotNull);
- expect(statement.leftParenthesis, isNotNull);
- expect(statement.variables, isNull);
- expect(statement.initialization, isNotNull);
- expect(statement.leftSeparator, isNotNull);
- expect(statement.condition, isNotNull);
- expect(statement.rightSeparator, isNotNull);
- expect(statement.updaters, hasLength(1));
- expect(statement.rightParenthesis, isNotNull);
- expect(statement.body, isNotNull);
+ createParser('for (i--; i < count; i++) {}');
+ Statement statement = parser.parseForStatement();
+ expectNotNullIfNoErrors(statement);
+ listener.assertNoErrors();
+ expect(statement, new isInstanceOf<ForStatement>());
+ ForStatement forStatement = statement;
+ expect(forStatement.forKeyword, isNotNull);
+ expect(forStatement.leftParenthesis, isNotNull);
+ expect(forStatement.variables, isNull);
+ expect(forStatement.initialization, isNotNull);
+ expect(forStatement.leftSeparator, isNotNull);
+ expect(forStatement.condition, isNotNull);
+ expect(forStatement.rightSeparator, isNotNull);
+ expect(forStatement.updaters, hasLength(1));
+ expect(forStatement.rightParenthesis, isNotNull);
+ expect(forStatement.body, isNotNull);
}
void test_parseForStatement_loop_i() {
- ForStatement statement =
- parse4("parseForStatement", "for (var i = 0;;) {}");
- expect(statement.forKeyword, isNotNull);
- expect(statement.leftParenthesis, isNotNull);
- VariableDeclarationList variables = statement.variables;
+ createParser('for (var i = 0;;) {}');
+ Statement statement = parser.parseForStatement();
+ expectNotNullIfNoErrors(statement);
+ listener.assertNoErrors();
+ expect(statement, new isInstanceOf<ForStatement>());
+ ForStatement forStatement = statement;
+ expect(forStatement.forKeyword, isNotNull);
+ expect(forStatement.leftParenthesis, isNotNull);
+ VariableDeclarationList variables = forStatement.variables;
expect(variables, isNotNull);
expect(variables.metadata, hasLength(0));
expect(variables.variables, hasLength(1));
- expect(statement.initialization, isNull);
- expect(statement.leftSeparator, isNotNull);
- expect(statement.condition, isNull);
- expect(statement.rightSeparator, isNotNull);
- expect(statement.updaters, hasLength(0));
- expect(statement.rightParenthesis, isNotNull);
- expect(statement.body, isNotNull);
+ expect(forStatement.initialization, isNull);
+ expect(forStatement.leftSeparator, isNotNull);
+ expect(forStatement.condition, isNull);
+ expect(forStatement.rightSeparator, isNotNull);
+ expect(forStatement.updaters, hasLength(0));
+ expect(forStatement.rightParenthesis, isNotNull);
+ expect(forStatement.body, isNotNull);
}
void test_parseForStatement_loop_i_withMetadata() {
- ForStatement statement =
- parse4("parseForStatement", "for (@A var i = 0;;) {}");
- expect(statement.forKeyword, isNotNull);
- expect(statement.leftParenthesis, isNotNull);
- VariableDeclarationList variables = statement.variables;
+ createParser('for (@A var i = 0;;) {}');
+ Statement statement = parser.parseForStatement();
+ expectNotNullIfNoErrors(statement);
+ listener.assertNoErrors();
+ expect(statement, new isInstanceOf<ForStatement>());
+ ForStatement forStatement = statement;
+ expect(forStatement.forKeyword, isNotNull);
+ expect(forStatement.leftParenthesis, isNotNull);
+ VariableDeclarationList variables = forStatement.variables;
expect(variables, isNotNull);
expect(variables.metadata, hasLength(1));
expect(variables.variables, hasLength(1));
- expect(statement.initialization, isNull);
- expect(statement.leftSeparator, isNotNull);
- expect(statement.condition, isNull);
- expect(statement.rightSeparator, isNotNull);
- expect(statement.updaters, hasLength(0));
- expect(statement.rightParenthesis, isNotNull);
- expect(statement.body, isNotNull);
+ expect(forStatement.initialization, isNull);
+ expect(forStatement.leftSeparator, isNotNull);
+ expect(forStatement.condition, isNull);
+ expect(forStatement.rightSeparator, isNotNull);
+ expect(forStatement.updaters, hasLength(0));
+ expect(forStatement.rightParenthesis, isNotNull);
+ expect(forStatement.body, isNotNull);
}
void test_parseForStatement_loop_ic() {
- ForStatement statement =
- parse4("parseForStatement", "for (var i = 0; i < count;) {}");
- expect(statement.forKeyword, isNotNull);
- expect(statement.leftParenthesis, isNotNull);
- VariableDeclarationList variables = statement.variables;
+ createParser('for (var i = 0; i < count;) {}');
+ Statement statement = parser.parseForStatement();
+ expectNotNullIfNoErrors(statement);
+ listener.assertNoErrors();
+ expect(statement, new isInstanceOf<ForStatement>());
+ ForStatement forStatement = statement;
+ expect(forStatement.forKeyword, isNotNull);
+ expect(forStatement.leftParenthesis, isNotNull);
+ VariableDeclarationList variables = forStatement.variables;
expect(variables, isNotNull);
expect(variables.variables, hasLength(1));
- expect(statement.initialization, isNull);
- expect(statement.leftSeparator, isNotNull);
- expect(statement.condition, isNotNull);
- expect(statement.rightSeparator, isNotNull);
- expect(statement.updaters, hasLength(0));
- expect(statement.rightParenthesis, isNotNull);
- expect(statement.body, isNotNull);
+ expect(forStatement.initialization, isNull);
+ expect(forStatement.leftSeparator, isNotNull);
+ expect(forStatement.condition, isNotNull);
+ expect(forStatement.rightSeparator, isNotNull);
+ expect(forStatement.updaters, hasLength(0));
+ expect(forStatement.rightParenthesis, isNotNull);
+ expect(forStatement.body, isNotNull);
}
void test_parseForStatement_loop_icu() {
- ForStatement statement =
- parse4("parseForStatement", "for (var i = 0; i < count; i++) {}");
- expect(statement.forKeyword, isNotNull);
- expect(statement.leftParenthesis, isNotNull);
- VariableDeclarationList variables = statement.variables;
+ createParser('for (var i = 0; i < count; i++) {}');
+ Statement statement = parser.parseForStatement();
+ expectNotNullIfNoErrors(statement);
+ listener.assertNoErrors();
+ expect(statement, new isInstanceOf<ForStatement>());
+ ForStatement forStatement = statement;
+ expect(forStatement.forKeyword, isNotNull);
+ expect(forStatement.leftParenthesis, isNotNull);
+ VariableDeclarationList variables = forStatement.variables;
expect(variables, isNotNull);
expect(variables.variables, hasLength(1));
- expect(statement.initialization, isNull);
- expect(statement.leftSeparator, isNotNull);
- expect(statement.condition, isNotNull);
- expect(statement.rightSeparator, isNotNull);
- expect(statement.updaters, hasLength(1));
- expect(statement.rightParenthesis, isNotNull);
- expect(statement.body, isNotNull);
+ expect(forStatement.initialization, isNull);
+ expect(forStatement.leftSeparator, isNotNull);
+ expect(forStatement.condition, isNotNull);
+ expect(forStatement.rightSeparator, isNotNull);
+ expect(forStatement.updaters, hasLength(1));
+ expect(forStatement.rightParenthesis, isNotNull);
+ expect(forStatement.body, isNotNull);
}
void test_parseForStatement_loop_iicuu() {
- ForStatement statement = parse4(
- "parseForStatement", "for (int i = 0, j = count; i < j; i++, j--) {}");
- expect(statement.forKeyword, isNotNull);
- expect(statement.leftParenthesis, isNotNull);
- VariableDeclarationList variables = statement.variables;
+ createParser('for (int i = 0, j = count; i < j; i++, j--) {}');
+ Statement statement = parser.parseForStatement();
+ expectNotNullIfNoErrors(statement);
+ listener.assertNoErrors();
+ expect(statement, new isInstanceOf<ForStatement>());
+ ForStatement forStatement = statement;
+ expect(forStatement.forKeyword, isNotNull);
+ expect(forStatement.leftParenthesis, isNotNull);
+ VariableDeclarationList variables = forStatement.variables;
expect(variables, isNotNull);
expect(variables.variables, hasLength(2));
- expect(statement.initialization, isNull);
- expect(statement.leftSeparator, isNotNull);
- expect(statement.condition, isNotNull);
- expect(statement.rightSeparator, isNotNull);
- expect(statement.updaters, hasLength(2));
- expect(statement.rightParenthesis, isNotNull);
- expect(statement.body, isNotNull);
+ expect(forStatement.initialization, isNull);
+ expect(forStatement.leftSeparator, isNotNull);
+ expect(forStatement.condition, isNotNull);
+ expect(forStatement.rightSeparator, isNotNull);
+ expect(forStatement.updaters, hasLength(2));
+ expect(forStatement.rightParenthesis, isNotNull);
+ expect(forStatement.body, isNotNull);
}
void test_parseForStatement_loop_iu() {
- ForStatement statement =
- parse4("parseForStatement", "for (var i = 0;; i++) {}");
- expect(statement.forKeyword, isNotNull);
- expect(statement.leftParenthesis, isNotNull);
- VariableDeclarationList variables = statement.variables;
+ createParser('for (var i = 0;; i++) {}');
+ Statement statement = parser.parseForStatement();
+ expectNotNullIfNoErrors(statement);
+ listener.assertNoErrors();
+ expect(statement, new isInstanceOf<ForStatement>());
+ ForStatement forStatement = statement;
+ expect(forStatement.forKeyword, isNotNull);
+ expect(forStatement.leftParenthesis, isNotNull);
+ VariableDeclarationList variables = forStatement.variables;
expect(variables, isNotNull);
expect(variables.variables, hasLength(1));
- expect(statement.initialization, isNull);
- expect(statement.leftSeparator, isNotNull);
- expect(statement.condition, isNull);
- expect(statement.rightSeparator, isNotNull);
- expect(statement.updaters, hasLength(1));
- expect(statement.rightParenthesis, isNotNull);
- expect(statement.body, isNotNull);
+ expect(forStatement.initialization, isNull);
+ expect(forStatement.leftSeparator, isNotNull);
+ expect(forStatement.condition, isNull);
+ expect(forStatement.rightSeparator, isNotNull);
+ expect(forStatement.updaters, hasLength(1));
+ expect(forStatement.rightParenthesis, isNotNull);
+ expect(forStatement.body, isNotNull);
}
void test_parseForStatement_loop_u() {
- ForStatement statement = parse4("parseForStatement", "for (;; i++) {}");
- expect(statement.forKeyword, isNotNull);
- expect(statement.leftParenthesis, isNotNull);
- expect(statement.variables, isNull);
- expect(statement.initialization, isNull);
- expect(statement.leftSeparator, isNotNull);
- expect(statement.condition, isNull);
- expect(statement.rightSeparator, isNotNull);
- expect(statement.updaters, hasLength(1));
- expect(statement.rightParenthesis, isNotNull);
- expect(statement.body, isNotNull);
+ createParser('for (;; i++) {}');
+ Statement statement = parser.parseForStatement();
+ expectNotNullIfNoErrors(statement);
+ listener.assertNoErrors();
+ expect(statement, new isInstanceOf<ForStatement>());
+ ForStatement forStatement = statement;
+ expect(forStatement.forKeyword, isNotNull);
+ expect(forStatement.leftParenthesis, isNotNull);
+ expect(forStatement.variables, isNull);
+ expect(forStatement.initialization, isNull);
+ expect(forStatement.leftSeparator, isNotNull);
+ expect(forStatement.condition, isNull);
+ expect(forStatement.rightSeparator, isNotNull);
+ expect(forStatement.updaters, hasLength(1));
+ expect(forStatement.rightParenthesis, isNotNull);
+ expect(forStatement.body, isNotNull);
}
void test_parseFunctionBody_block() {
@@ -8020,10 +8848,11 @@
void test_parseFunctionBody_skip_block_invalid() {
ParserTestCase.parseFunctionBodies = false;
- FunctionBody functionBody = parse3("parseFunctionBody",
- <Object>[false, null, false], "{", [ParserErrorCode.EXPECTED_TOKEN]);
- EngineTestCase.assertInstanceOf(
- (obj) => obj is EmptyFunctionBody, EmptyFunctionBody, functionBody);
+ createParser('{');
+ FunctionBody functionBody = parser.parseFunctionBody(false, null, false);
+ expectNotNullIfNoErrors(functionBody);
+ listener.assertErrorsWithCodes([ParserErrorCode.EXPECTED_TOKEN]);
+ expect(functionBody, new isInstanceOf<EmptyFunctionBody>());
}
void test_parseFunctionBody_skip_blocks() {
@@ -8236,7 +9065,10 @@
}
void test_parseIfStatement_else_block() {
- IfStatement statement = parse4("parseIfStatement", "if (x) {} else {}");
+ createParser('if (x) {} else {}');
+ IfStatement statement = parser.parseIfStatement();
+ expectNotNullIfNoErrors(statement);
+ listener.assertNoErrors();
expect(statement.ifKeyword, isNotNull);
expect(statement.leftParenthesis, isNotNull);
expect(statement.condition, isNotNull);
@@ -8247,8 +9079,10 @@
}
void test_parseIfStatement_else_statement() {
- IfStatement statement =
- parse4("parseIfStatement", "if (x) f(x); else f(y);");
+ createParser('if (x) f(x); else f(y);');
+ IfStatement statement = parser.parseIfStatement();
+ expectNotNullIfNoErrors(statement);
+ listener.assertNoErrors();
expect(statement.ifKeyword, isNotNull);
expect(statement.leftParenthesis, isNotNull);
expect(statement.condition, isNotNull);
@@ -8259,7 +9093,10 @@
}
void test_parseIfStatement_noElse_block() {
- IfStatement statement = parse4("parseIfStatement", "if (x) {}");
+ createParser('if (x) {}');
+ IfStatement statement = parser.parseIfStatement();
+ expectNotNullIfNoErrors(statement);
+ listener.assertNoErrors();
expect(statement.ifKeyword, isNotNull);
expect(statement.leftParenthesis, isNotNull);
expect(statement.condition, isNotNull);
@@ -8270,7 +9107,10 @@
}
void test_parseIfStatement_noElse_statement() {
- IfStatement statement = parse4("parseIfStatement", "if (x) f(x);");
+ createParser('if (x) f(x);');
+ IfStatement statement = parser.parseIfStatement();
+ expectNotNullIfNoErrors(statement);
+ listener.assertNoErrors();
expect(statement.ifKeyword, isNotNull);
expect(statement.leftParenthesis, isNotNull);
expect(statement.condition, isNotNull);
@@ -9095,6 +9935,17 @@
expect(parameter.parameters, isNotNull);
}
+ void test_parseNormalFormalParameter_function_noType_nullable() {
+ enableNnbd = true;
+ FunctionTypedFormalParameter parameter =
+ parse4("parseNormalFormalParameter", "a()?)");
+ expect(parameter.returnType, isNull);
+ expect(parameter.identifier, isNotNull);
+ expect(parameter.typeParameters, isNull);
+ expect(parameter.parameters, isNotNull);
+ expect(parameter.question, isNotNull);
+ }
+
void test_parseNormalFormalParameter_function_noType_typeParameterComments() {
enableGenericMethodComments = true;
FunctionTypedFormalParameter parameter =
@@ -9113,6 +9964,21 @@
expect(parameter.identifier, isNotNull);
expect(parameter.typeParameters, isNotNull);
expect(parameter.parameters, isNotNull);
+ expect(parameter.question, isNull);
+ expect(parameter.question, isNull);
+ }
+
+ void
+ test_parseNormalFormalParameter_function_noType_typeParameters_nullable() {
+ enableGenericMethods = true;
+ enableNnbd = true;
+ FunctionTypedFormalParameter parameter =
+ parse4("parseNormalFormalParameter", "a<E>()?)");
+ expect(parameter.returnType, isNull);
+ expect(parameter.identifier, isNotNull);
+ expect(parameter.typeParameters, isNotNull);
+ expect(parameter.parameters, isNotNull);
+ expect(parameter.question, isNotNull);
}
void test_parseNormalFormalParameter_function_type() {
@@ -9122,6 +9988,18 @@
expect(parameter.identifier, isNotNull);
expect(parameter.typeParameters, isNull);
expect(parameter.parameters, isNotNull);
+ expect(parameter.question, isNull);
+ }
+
+ void test_parseNormalFormalParameter_function_type_nullable() {
+ enableNnbd = true;
+ FunctionTypedFormalParameter parameter =
+ parse4("parseNormalFormalParameter", "A a()?)");
+ expect(parameter.returnType, isNotNull);
+ expect(parameter.identifier, isNotNull);
+ expect(parameter.typeParameters, isNull);
+ expect(parameter.parameters, isNotNull);
+ expect(parameter.question, isNotNull);
}
void test_parseNormalFormalParameter_function_type_typeParameterComments() {
@@ -9132,6 +10010,7 @@
expect(parameter.identifier, isNotNull);
expect(parameter.typeParameters, isNotNull);
expect(parameter.parameters, isNotNull);
+ expect(parameter.question, isNull);
}
void test_parseNormalFormalParameter_function_type_typeParameters() {
@@ -9142,6 +10021,19 @@
expect(parameter.identifier, isNotNull);
expect(parameter.typeParameters, isNotNull);
expect(parameter.parameters, isNotNull);
+ expect(parameter.question, isNull);
+ }
+
+ void test_parseNormalFormalParameter_function_type_typeParameters_nullable() {
+ enableGenericMethods = true;
+ enableNnbd = true;
+ FunctionTypedFormalParameter parameter =
+ parse4("parseNormalFormalParameter", "A a<E>()?)");
+ expect(parameter.returnType, isNotNull);
+ expect(parameter.identifier, isNotNull);
+ expect(parameter.typeParameters, isNotNull);
+ expect(parameter.parameters, isNotNull);
+ expect(parameter.question, isNotNull);
}
void test_parseNormalFormalParameter_function_void() {
@@ -9151,6 +10043,18 @@
expect(parameter.identifier, isNotNull);
expect(parameter.typeParameters, isNull);
expect(parameter.parameters, isNotNull);
+ expect(parameter.question, isNull);
+ }
+
+ void test_parseNormalFormalParameter_function_void_nullable() {
+ enableNnbd = true;
+ FunctionTypedFormalParameter parameter =
+ parse4("parseNormalFormalParameter", "void a()?)");
+ expect(parameter.returnType, isNotNull);
+ expect(parameter.identifier, isNotNull);
+ expect(parameter.typeParameters, isNull);
+ expect(parameter.parameters, isNotNull);
+ expect(parameter.question, isNotNull);
}
void test_parseNormalFormalParameter_function_void_typeParameterComments() {
@@ -9161,6 +10065,7 @@
expect(parameter.identifier, isNotNull);
expect(parameter.typeParameters, isNotNull);
expect(parameter.parameters, isNotNull);
+ expect(parameter.question, isNull);
}
void test_parseNormalFormalParameter_function_void_typeParameters() {
@@ -9171,6 +10076,19 @@
expect(parameter.identifier, isNotNull);
expect(parameter.typeParameters, isNotNull);
expect(parameter.parameters, isNotNull);
+ expect(parameter.question, isNull);
+ }
+
+ void test_parseNormalFormalParameter_function_void_typeParameters_nullable() {
+ enableGenericMethods = true;
+ enableNnbd = true;
+ FunctionTypedFormalParameter parameter =
+ parse4("parseNormalFormalParameter", "void a<E>()?)");
+ expect(parameter.returnType, isNotNull);
+ expect(parameter.identifier, isNotNull);
+ expect(parameter.typeParameters, isNotNull);
+ expect(parameter.parameters, isNotNull);
+ expect(parameter.question, isNotNull);
}
void test_parseNormalFormalParameter_simple_const_noType() {
@@ -9366,140 +10284,242 @@
}
void test_parsePrimaryExpression_const() {
- InstanceCreationExpression expression =
- parse4("parsePrimaryExpression", "const A()");
+ createParser('const A()');
+ Expression expression = parser.parsePrimaryExpression();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
expect(expression, isNotNull);
}
void test_parsePrimaryExpression_double() {
String doubleLiteral = "3.2e4";
- DoubleLiteral literal = parse4("parsePrimaryExpression", doubleLiteral);
+ createParser(doubleLiteral);
+ Expression expression = parser.parsePrimaryExpression();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<DoubleLiteral>());
+ DoubleLiteral literal = expression;
expect(literal.literal, isNotNull);
expect(literal.value, double.parse(doubleLiteral));
}
void test_parsePrimaryExpression_false() {
- BooleanLiteral literal = parse4("parsePrimaryExpression", "false");
+ createParser('false');
+ Expression expression = parser.parsePrimaryExpression();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<BooleanLiteral>());
+ BooleanLiteral literal = expression;
expect(literal.literal, isNotNull);
expect(literal.value, isFalse);
}
void test_parsePrimaryExpression_function_arguments() {
- FunctionExpression expression =
- parse4("parsePrimaryExpression", "(int i) => i + 1");
- expect(expression.parameters, isNotNull);
- expect(expression.body, isNotNull);
+ createParser('(int i) => i + 1');
+ Expression expression = parser.parsePrimaryExpression();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<FunctionExpression>());
+ FunctionExpression functionExpression = expression;
+ expect(functionExpression.parameters, isNotNull);
+ expect(functionExpression.body, isNotNull);
}
void test_parsePrimaryExpression_function_noArguments() {
- FunctionExpression expression =
- parse4("parsePrimaryExpression", "() => 42");
- expect(expression.parameters, isNotNull);
- expect(expression.body, isNotNull);
+ createParser('() => 42');
+ Expression expression = parser.parsePrimaryExpression();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<FunctionExpression>());
+ FunctionExpression functionExpression = expression;
+ expect(functionExpression.parameters, isNotNull);
+ expect(functionExpression.body, isNotNull);
}
void test_parsePrimaryExpression_hex() {
String hexLiteral = "3F";
- IntegerLiteral literal = parse4("parsePrimaryExpression", "0x$hexLiteral");
+ createParser('0x$hexLiteral');
+ Expression expression = parser.parsePrimaryExpression();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<IntegerLiteral>());
+ IntegerLiteral literal = expression;
expect(literal.literal, isNotNull);
expect(literal.value, int.parse(hexLiteral, radix: 16));
}
void test_parsePrimaryExpression_identifier() {
- SimpleIdentifier identifier = parse4("parsePrimaryExpression", "a");
+ createParser('a');
+ Expression expression = parser.parsePrimaryExpression();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<SimpleIdentifier>());
+ SimpleIdentifier identifier = expression;
expect(identifier, isNotNull);
}
void test_parsePrimaryExpression_int() {
String intLiteral = "472";
- IntegerLiteral literal = parse4("parsePrimaryExpression", intLiteral);
+ createParser(intLiteral);
+ Expression expression = parser.parsePrimaryExpression();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<IntegerLiteral>());
+ IntegerLiteral literal = expression;
expect(literal.literal, isNotNull);
expect(literal.value, int.parse(intLiteral));
}
void test_parsePrimaryExpression_listLiteral() {
- ListLiteral literal = parse4("parsePrimaryExpression", "[ ]");
+ createParser('[ ]');
+ Expression expression = parser.parsePrimaryExpression();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<ListLiteral>());
+ ListLiteral literal = expression;
expect(literal, isNotNull);
}
void test_parsePrimaryExpression_listLiteral_index() {
- ListLiteral literal = parse4("parsePrimaryExpression", "[]");
+ createParser('[]');
+ Expression expression = parser.parsePrimaryExpression();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<ListLiteral>());
+ ListLiteral literal = expression;
expect(literal, isNotNull);
}
void test_parsePrimaryExpression_listLiteral_typed() {
- ListLiteral literal = parse4("parsePrimaryExpression", "<A>[ ]");
+ createParser('<A>[ ]');
+ Expression expression = parser.parsePrimaryExpression();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<ListLiteral>());
+ ListLiteral literal = expression;
expect(literal.typeArguments, isNotNull);
expect(literal.typeArguments.arguments, hasLength(1));
}
void test_parsePrimaryExpression_listLiteral_typed_genericComment() {
enableGenericMethodComments = true;
- ListLiteral literal = parse4("parsePrimaryExpression", "/*<A>*/[ ]");
+ createParser('/*<A>*/[ ]');
+ Expression expression = parser.parsePrimaryExpression();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<ListLiteral>());
+ ListLiteral literal = expression;
expect(literal.typeArguments, isNotNull);
expect(literal.typeArguments.arguments, hasLength(1));
}
void test_parsePrimaryExpression_mapLiteral() {
- MapLiteral literal = parse4("parsePrimaryExpression", "{}");
+ createParser('{}');
+ Expression expression = parser.parsePrimaryExpression();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<MapLiteral>());
+ MapLiteral literal = expression;
+ expect(literal.typeArguments, isNull);
expect(literal, isNotNull);
}
void test_parsePrimaryExpression_mapLiteral_typed() {
- MapLiteral literal = parse4("parsePrimaryExpression", "<A, B>{}");
+ createParser('<A, B>{}');
+ Expression expression = parser.parsePrimaryExpression();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<MapLiteral>());
+ MapLiteral literal = expression;
expect(literal.typeArguments, isNotNull);
expect(literal.typeArguments.arguments, hasLength(2));
}
void test_parsePrimaryExpression_mapLiteral_typed_genericComment() {
enableGenericMethodComments = true;
- MapLiteral literal = parse4("parsePrimaryExpression", "/*<A, B>*/{}");
+ createParser('/*<A, B>*/{}');
+ Expression expression = parser.parsePrimaryExpression();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<MapLiteral>());
+ MapLiteral literal = expression;
expect(literal.typeArguments, isNotNull);
expect(literal.typeArguments.arguments, hasLength(2));
}
void test_parsePrimaryExpression_new() {
- InstanceCreationExpression expression =
- parse4("parsePrimaryExpression", "new A()");
- expect(expression, isNotNull);
+ createParser('new A()');
+ Expression expression = parser.parsePrimaryExpression();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<InstanceCreationExpression>());
+ InstanceCreationExpression creation = expression;
+ expect(creation, isNotNull);
}
void test_parsePrimaryExpression_null() {
- NullLiteral literal = parse4("parsePrimaryExpression", "null");
+ createParser('null');
+ Expression expression = parser.parsePrimaryExpression();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<NullLiteral>());
+ NullLiteral literal = expression;
expect(literal.literal, isNotNull);
}
void test_parsePrimaryExpression_parenthesized() {
- ParenthesizedExpression expression =
- parse4("parsePrimaryExpression", "(x)");
- expect(expression, isNotNull);
+ createParser('(x)');
+ Expression expression = parser.parsePrimaryExpression();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<ParenthesizedExpression>());
+ ParenthesizedExpression parens = expression;
+ expect(parens, isNotNull);
}
void test_parsePrimaryExpression_string() {
- SimpleStringLiteral literal =
- parse4("parsePrimaryExpression", "\"string\"");
+ createParser('"string"');
+ Expression expression = parser.parsePrimaryExpression();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<SimpleStringLiteral>());
+ SimpleStringLiteral literal = expression;
expect(literal.isMultiline, isFalse);
expect(literal.isRaw, isFalse);
expect(literal.value, "string");
}
void test_parsePrimaryExpression_string_multiline() {
- SimpleStringLiteral literal =
- parse4("parsePrimaryExpression", "'''string'''");
+ createParser("'''string'''");
+ Expression expression = parser.parsePrimaryExpression();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<SimpleStringLiteral>());
+ SimpleStringLiteral literal = expression;
expect(literal.isMultiline, isTrue);
expect(literal.isRaw, isFalse);
expect(literal.value, "string");
}
void test_parsePrimaryExpression_string_raw() {
- SimpleStringLiteral literal = parse4("parsePrimaryExpression", "r'string'");
+ createParser("r'string'");
+ Expression expression = parser.parsePrimaryExpression();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<SimpleStringLiteral>());
+ SimpleStringLiteral literal = expression;
expect(literal.isMultiline, isFalse);
expect(literal.isRaw, isTrue);
expect(literal.value, "string");
}
void test_parsePrimaryExpression_super() {
- PropertyAccess propertyAccess = parse4("parsePrimaryExpression", "super.x");
+ createParser('super.x');
+ Expression expression = parser.parsePrimaryExpression();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<PropertyAccess>());
+ PropertyAccess propertyAccess = expression;
expect(propertyAccess.target is SuperExpression, isTrue);
expect(propertyAccess.operator, isNotNull);
expect(propertyAccess.operator.type, TokenType.PERIOD);
@@ -9507,12 +10527,22 @@
}
void test_parsePrimaryExpression_this() {
- ThisExpression expression = parse4("parsePrimaryExpression", "this");
- expect(expression.thisKeyword, isNotNull);
+ createParser('this');
+ Expression expression = parser.parsePrimaryExpression();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<ThisExpression>());
+ ThisExpression thisExpression = expression;
+ expect(thisExpression.thisKeyword, isNotNull);
}
void test_parsePrimaryExpression_true() {
- BooleanLiteral literal = parse4("parsePrimaryExpression", "true");
+ createParser('true');
+ Expression expression = parser.parsePrimaryExpression();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<BooleanLiteral>());
+ BooleanLiteral literal = expression;
expect(literal.literal, isNotNull);
expect(literal.value, isTrue);
}
@@ -9523,7 +10553,7 @@
void test_parseRedirectingConstructorInvocation_named() {
RedirectingConstructorInvocation invocation =
- parse2("parseRedirectingConstructorInvocation", [true], "this.a()");
+ parse("parseRedirectingConstructorInvocation", [true], "this.a()");
expect(invocation.argumentList, isNotNull);
expect(invocation.constructorName, isNotNull);
expect(invocation.thisKeyword, isNotNull);
@@ -9532,7 +10562,7 @@
void test_parseRedirectingConstructorInvocation_unnamed() {
RedirectingConstructorInvocation invocation =
- parse2("parseRedirectingConstructorInvocation", [false], "this()");
+ parse("parseRedirectingConstructorInvocation", [false], "this()");
expect(invocation.argumentList, isNotNull);
expect(invocation.constructorName, isNull);
expect(invocation.thisKeyword, isNotNull);
@@ -9540,72 +10570,111 @@
}
void test_parseRelationalExpression_as() {
- AsExpression expression = parse4("parseRelationalExpression", "x as Y");
- expect(expression.expression, isNotNull);
- expect(expression.asOperator, isNotNull);
- expect(expression.type, isNotNull);
+ createParser('x as Y');
+ Expression expression = parser.parseRelationalExpression();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<AsExpression>());
+ AsExpression asExpression = expression;
+ expect(asExpression.expression, isNotNull);
+ expect(asExpression.asOperator, isNotNull);
+ expect(asExpression.type, isNotNull);
}
void test_parseRelationalExpression_is() {
- IsExpression expression = parse4("parseRelationalExpression", "x is y");
- expect(expression.expression, isNotNull);
- expect(expression.isOperator, isNotNull);
- expect(expression.notOperator, isNull);
- expect(expression.type, isNotNull);
+ createParser('x is y');
+ Expression expression = parser.parseRelationalExpression();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<IsExpression>());
+ IsExpression isExpression = expression;
+ expect(isExpression.expression, isNotNull);
+ expect(isExpression.isOperator, isNotNull);
+ expect(isExpression.notOperator, isNull);
+ expect(isExpression.type, isNotNull);
}
void test_parseRelationalExpression_isNot() {
- IsExpression expression = parse4("parseRelationalExpression", "x is! y");
- expect(expression.expression, isNotNull);
- expect(expression.isOperator, isNotNull);
- expect(expression.notOperator, isNotNull);
- expect(expression.type, isNotNull);
+ createParser('x is! y');
+ Expression expression = parser.parseRelationalExpression();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<IsExpression>());
+ IsExpression isExpression = expression;
+ expect(isExpression.expression, isNotNull);
+ expect(isExpression.isOperator, isNotNull);
+ expect(isExpression.notOperator, isNotNull);
+ expect(isExpression.type, isNotNull);
}
void test_parseRelationalExpression_normal() {
- BinaryExpression expression = parse4("parseRelationalExpression", "x < y");
- expect(expression.leftOperand, isNotNull);
- expect(expression.operator, isNotNull);
- expect(expression.operator.type, TokenType.LT);
- expect(expression.rightOperand, isNotNull);
+ createParser('x < y');
+ Expression expression = parser.parseRelationalExpression();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<BinaryExpression>());
+ BinaryExpression binaryExpression = expression;
+ expect(binaryExpression.leftOperand, isNotNull);
+ expect(binaryExpression.operator, isNotNull);
+ expect(binaryExpression.operator.type, TokenType.LT);
+ expect(binaryExpression.rightOperand, isNotNull);
}
void test_parseRelationalExpression_super() {
- BinaryExpression expression =
- parse4("parseRelationalExpression", "super < y");
- expect(expression.leftOperand, isNotNull);
- expect(expression.operator, isNotNull);
- expect(expression.operator.type, TokenType.LT);
- expect(expression.rightOperand, isNotNull);
+ createParser('super < y');
+ Expression expression = parser.parseRelationalExpression();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<BinaryExpression>());
+ BinaryExpression binaryExpression = expression;
+ expect(binaryExpression.leftOperand, isNotNull);
+ expect(binaryExpression.operator, isNotNull);
+ expect(binaryExpression.operator.type, TokenType.LT);
+ expect(binaryExpression.rightOperand, isNotNull);
}
void test_parseRethrowExpression() {
- RethrowExpression expression = parse4("parseRethrowExpression", "rethrow;");
+ createParser('rethrow;');
+ RethrowExpression expression = parser.parseRethrowExpression();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
expect(expression.rethrowKeyword, isNotNull);
}
void test_parseReturnStatement_noValue() {
- ReturnStatement statement = parse4("parseReturnStatement", "return;");
+ createParser('return;');
+ ReturnStatement statement = parser.parseReturnStatement();
+ expectNotNullIfNoErrors(statement);
+ listener.assertNoErrors();
expect(statement.returnKeyword, isNotNull);
expect(statement.expression, isNull);
expect(statement.semicolon, isNotNull);
}
void test_parseReturnStatement_value() {
- ReturnStatement statement = parse4("parseReturnStatement", "return x;");
+ createParser('return x;');
+ ReturnStatement statement = parser.parseReturnStatement();
+ expectNotNullIfNoErrors(statement);
+ listener.assertNoErrors();
expect(statement.returnKeyword, isNotNull);
expect(statement.expression, isNotNull);
expect(statement.semicolon, isNotNull);
}
void test_parseReturnType_nonVoid() {
- TypeName typeName = parse4("parseReturnType", "A<B>");
+ createParser('A<B>');
+ TypeName typeName = parser.parseReturnType();
+ expectNotNullIfNoErrors(typeName);
+ listener.assertNoErrors();
expect(typeName.name, isNotNull);
expect(typeName.typeArguments, isNotNull);
}
void test_parseReturnType_void() {
- TypeName typeName = parse4("parseReturnType", "void");
+ createParser('void');
+ TypeName typeName = parser.parseReturnType();
+ expectNotNullIfNoErrors(typeName);
+ listener.assertNoErrors();
expect(typeName.name, isNotNull);
expect(typeName.typeArguments, isNull);
}
@@ -9650,7 +10719,10 @@
}
void test_parseShiftExpression_normal() {
- BinaryExpression expression = parse4("parseShiftExpression", "x << y");
+ createParser('x << y');
+ BinaryExpression expression = parser.parseShiftExpression();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
expect(expression.leftOperand, isNotNull);
expect(expression.operator, isNotNull);
expect(expression.operator.type, TokenType.LT_LT);
@@ -9658,7 +10730,10 @@
}
void test_parseShiftExpression_super() {
- BinaryExpression expression = parse4("parseShiftExpression", "super << y");
+ createParser('super << y');
+ BinaryExpression expression = parser.parseShiftExpression();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
expect(expression.leftOperand, isNotNull);
expect(expression.operator, isNotNull);
expect(expression.operator.type, TokenType.LT_LT);
@@ -9671,22 +10746,32 @@
void test_parseSimpleIdentifier_builtInIdentifier() {
String lexeme = "as";
- SimpleIdentifier identifier = parse4("parseSimpleIdentifier", lexeme);
+ createParser(lexeme);
+ SimpleIdentifier identifier = parser.parseSimpleIdentifier();
+ expectNotNullIfNoErrors(identifier);
+ listener.assertNoErrors();
expect(identifier.token, isNotNull);
expect(identifier.name, lexeme);
}
void test_parseSimpleIdentifier_normalIdentifier() {
String lexeme = "foo";
- SimpleIdentifier identifier = parse4("parseSimpleIdentifier", lexeme);
+ createParser(lexeme);
+ SimpleIdentifier identifier = parser.parseSimpleIdentifier();
+ expectNotNullIfNoErrors(identifier);
+ listener.assertNoErrors();
expect(identifier.token, isNotNull);
expect(identifier.name, lexeme);
}
void test_parseStatement_emptyTypeArgumentList() {
- VariableDeclarationStatement statement = parse4(
- "parseStatement", "C<> c;", [ParserErrorCode.EXPECTED_TYPE_NAME]);
- VariableDeclarationList variables = statement.variables;
+ createParser('C<> c;');
+ Statement statement = parser.parseStatement2();
+ expectNotNullIfNoErrors(statement);
+ listener.assertErrorsWithCodes([ParserErrorCode.EXPECTED_TYPE_NAME]);
+ expect(statement, new isInstanceOf<VariableDeclarationStatement>());
+ VariableDeclarationStatement declaration = statement;
+ VariableDeclarationList variables = declaration.variables;
TypeName type = variables.type;
TypeArgumentList argumentList = type.typeArguments;
expect(argumentList.leftBracket, isNotNull);
@@ -9696,50 +10781,79 @@
}
void test_parseStatement_functionDeclaration_noReturnType() {
- FunctionDeclarationStatement statement =
- parse4("parseStatement", "f(a, b) {};");
- expect(statement.functionDeclaration, isNotNull);
+ createParser('f(a, b) {};');
+ Statement statement = parser.parseStatement2();
+ expectNotNullIfNoErrors(statement);
+ listener.assertNoErrors();
+ expect(statement, new isInstanceOf<FunctionDeclarationStatement>());
+ FunctionDeclarationStatement declaration = statement;
+ expect(declaration.functionDeclaration, isNotNull);
}
void
test_parseStatement_functionDeclaration_noReturnType_typeParameterComments() {
enableGenericMethodComments = true;
- FunctionDeclarationStatement statement =
- parse4("parseStatement", "f/*<E>*/(a, b) {};");
- expect(statement.functionDeclaration, isNotNull);
- expect(statement.functionDeclaration.functionExpression.typeParameters,
+ createParser('f/*<E>*/(a, b) {};');
+ Statement statement = parser.parseStatement2();
+ expectNotNullIfNoErrors(statement);
+ listener.assertNoErrors();
+ expect(statement, new isInstanceOf<FunctionDeclarationStatement>());
+ FunctionDeclarationStatement declaration = statement;
+ expect(declaration.functionDeclaration, isNotNull);
+ expect(declaration.functionDeclaration.functionExpression.typeParameters,
isNotNull);
}
void test_parseStatement_functionDeclaration_returnType() {
// TODO(brianwilkerson) Implement more tests for this method.
- FunctionDeclarationStatement statement =
- parse4("parseStatement", "int f(a, b) {};", []);
- expect(statement.functionDeclaration, isNotNull);
+ createParser('int f(a, b) {};');
+ Statement statement = parser.parseStatement2();
+ expectNotNullIfNoErrors(statement);
+ listener.assertNoErrors();
+ expect(statement, new isInstanceOf<FunctionDeclarationStatement>());
+ FunctionDeclarationStatement declaration = statement;
+ expect(declaration.functionDeclaration, isNotNull);
}
void test_parseStatement_functionDeclaration_returnType_typeParameters() {
enableGenericMethods = true;
- FunctionDeclarationStatement statement =
- parse4("parseStatement", "int f<E>(a, b) {};");
- expect(statement.functionDeclaration, isNotNull);
+ createParser('int f<E>(a, b) {};');
+ Statement statement = parser.parseStatement2();
+ expectNotNullIfNoErrors(statement);
+ listener.assertNoErrors();
+ expect(statement, new isInstanceOf<FunctionDeclarationStatement>());
+ FunctionDeclarationStatement declaration = statement;
+ expect(declaration.functionDeclaration, isNotNull);
}
void test_parseStatement_mulipleLabels() {
- LabeledStatement statement = parse4("parseStatement", "l: m: return x;");
- expect(statement.labels, hasLength(2));
- expect(statement.statement, isNotNull);
+ createParser('l: m: return x;');
+ Statement statement = parser.parseStatement2();
+ expectNotNullIfNoErrors(statement);
+ listener.assertNoErrors();
+ expect(statement, new isInstanceOf<LabeledStatement>());
+ LabeledStatement labeledStatement = statement;
+ expect(labeledStatement.labels, hasLength(2));
+ expect(labeledStatement.statement, isNotNull);
}
void test_parseStatement_noLabels() {
- parse4("parseStatement", "return x;");
+ createParser('return x;');
+ Statement statement = parser.parseStatement2();
+ expectNotNullIfNoErrors(statement);
+ listener.assertNoErrors();
}
void test_parseStatement_singleLabel() {
- LabeledStatement statement = parse4("parseStatement", "l: return x;");
- expect(statement.labels, hasLength(1));
- expect(statement.labels[0].label.inDeclarationContext(), isTrue);
- expect(statement.statement, isNotNull);
+ createParser('l: return x;');
+ Statement statement = parser.parseStatement2();
+ expectNotNullIfNoErrors(statement);
+ listener.assertNoErrors();
+ expect(statement, new isInstanceOf<LabeledStatement>());
+ LabeledStatement labeledStatement = statement;
+ expect(labeledStatement.labels, hasLength(1));
+ expect(labeledStatement.labels[0].label.inDeclarationContext(), isTrue);
+ expect(labeledStatement.statement, isNotNull);
}
void test_parseStatements_multiple() {
@@ -9754,7 +10868,12 @@
}
void test_parseStringLiteral_adjacent() {
- AdjacentStrings literal = parse4("parseStringLiteral", "'a' 'b'");
+ createParser("'a' 'b'");
+ Expression expression = parser.parseStringLiteral();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<AdjacentStrings>());
+ AdjacentStrings literal = expression;
NodeList<StringLiteral> strings = literal.strings;
expect(strings, hasLength(2));
StringLiteral firstString = strings[0];
@@ -9764,9 +10883,12 @@
}
void test_parseStringLiteral_endsWithInterpolation() {
- StringLiteral literal = parse4('parseStringLiteral', r"'x$y'");
- expect(literal, new isInstanceOf<StringInterpolation>());
- StringInterpolation interpolation = literal;
+ createParser(r"'x$y'");
+ Expression expression = parser.parseStringLiteral();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<StringInterpolation>());
+ StringInterpolation interpolation = expression;
expect(interpolation.elements, hasLength(3));
expect(interpolation.elements[0], new isInstanceOf<InterpolationString>());
InterpolationString element0 = interpolation.elements[0];
@@ -9781,8 +10903,12 @@
}
void test_parseStringLiteral_interpolated() {
- StringInterpolation literal =
- parse4("parseStringLiteral", "'a \${b} c \$this d'");
+ createParser("'a \${b} c \$this d'");
+ Expression expression = parser.parseStringLiteral();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<StringInterpolation>());
+ StringInterpolation literal = expression;
NodeList<InterpolationElement> elements = literal.elements;
expect(elements, hasLength(5));
expect(elements[0] is InterpolationString, isTrue);
@@ -9793,16 +10919,23 @@
}
void test_parseStringLiteral_multiline_encodedSpace() {
- SimpleStringLiteral literal =
- parse4("parseStringLiteral", "'''\\x20\na'''");
+ createParser("'''\\x20\na'''");
+ Expression expression = parser.parseStringLiteral();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<SimpleStringLiteral>());
+ SimpleStringLiteral literal = expression;
expect(literal.literal, isNotNull);
expect(literal.value, " \na");
}
void test_parseStringLiteral_multiline_endsWithInterpolation() {
- StringLiteral literal = parse4('parseStringLiteral', r"'''x$y'''");
- expect(literal, new isInstanceOf<StringInterpolation>());
- StringInterpolation interpolation = literal;
+ createParser(r"'''x$y'''");
+ Expression expression = parser.parseStringLiteral();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<StringInterpolation>());
+ StringInterpolation interpolation = expression;
expect(interpolation.elements, hasLength(3));
expect(interpolation.elements[0], new isInstanceOf<InterpolationString>());
InterpolationString element0 = interpolation.elements[0];
@@ -9817,60 +10950,100 @@
}
void test_parseStringLiteral_multiline_escapedBackslash() {
- SimpleStringLiteral literal = parse4("parseStringLiteral", "'''\\\\\na'''");
+ createParser("'''\\\\\na'''");
+ Expression expression = parser.parseStringLiteral();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<SimpleStringLiteral>());
+ SimpleStringLiteral literal = expression;
expect(literal.literal, isNotNull);
expect(literal.value, "\\\na");
}
void test_parseStringLiteral_multiline_escapedBackslash_raw() {
- SimpleStringLiteral literal =
- parse4("parseStringLiteral", "r'''\\\\\na'''");
+ createParser("r'''\\\\\na'''");
+ Expression expression = parser.parseStringLiteral();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<SimpleStringLiteral>());
+ SimpleStringLiteral literal = expression;
expect(literal.literal, isNotNull);
expect(literal.value, "\\\\\na");
}
void test_parseStringLiteral_multiline_escapedEolMarker() {
- SimpleStringLiteral literal = parse4("parseStringLiteral", "'''\\\na'''");
+ createParser("'''\\\na'''");
+ Expression expression = parser.parseStringLiteral();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<SimpleStringLiteral>());
+ SimpleStringLiteral literal = expression;
expect(literal.literal, isNotNull);
expect(literal.value, "a");
}
void test_parseStringLiteral_multiline_escapedEolMarker_raw() {
- SimpleStringLiteral literal = parse4("parseStringLiteral", "r'''\\\na'''");
+ createParser("r'''\\\na'''");
+ Expression expression = parser.parseStringLiteral();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<SimpleStringLiteral>());
+ SimpleStringLiteral literal = expression;
expect(literal.literal, isNotNull);
expect(literal.value, "a");
}
void test_parseStringLiteral_multiline_escapedSpaceAndEolMarker() {
- SimpleStringLiteral literal =
- parse4("parseStringLiteral", "'''\\ \\\na'''");
+ createParser("'''\\ \\\na'''");
+ Expression expression = parser.parseStringLiteral();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<SimpleStringLiteral>());
+ SimpleStringLiteral literal = expression;
expect(literal.literal, isNotNull);
expect(literal.value, "a");
}
void test_parseStringLiteral_multiline_escapedSpaceAndEolMarker_raw() {
- SimpleStringLiteral literal =
- parse4("parseStringLiteral", "r'''\\ \\\na'''");
+ createParser("r'''\\ \\\na'''");
+ Expression expression = parser.parseStringLiteral();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<SimpleStringLiteral>());
+ SimpleStringLiteral literal = expression;
expect(literal.literal, isNotNull);
expect(literal.value, "a");
}
void test_parseStringLiteral_multiline_escapedTab() {
- SimpleStringLiteral literal = parse4("parseStringLiteral", "'''\\t\na'''");
+ createParser("'''\\t\na'''");
+ Expression expression = parser.parseStringLiteral();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<SimpleStringLiteral>());
+ SimpleStringLiteral literal = expression;
expect(literal.literal, isNotNull);
expect(literal.value, "\t\na");
}
void test_parseStringLiteral_multiline_escapedTab_raw() {
- SimpleStringLiteral literal = parse4("parseStringLiteral", "r'''\\t\na'''");
+ createParser("r'''\\t\na'''");
+ Expression expression = parser.parseStringLiteral();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<SimpleStringLiteral>());
+ SimpleStringLiteral literal = expression;
expect(literal.literal, isNotNull);
expect(literal.value, "\\t\na");
}
void test_parseStringLiteral_multiline_quoteAfterInterpolation() {
- StringLiteral literal = parse4('parseStringLiteral', r"""'''$x'y'''""");
- expect(literal, new isInstanceOf<StringInterpolation>());
- StringInterpolation interpolation = literal;
+ createParser(r"""'''$x'y'''""");
+ Expression expression = parser.parseStringLiteral();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<StringInterpolation>());
+ StringInterpolation interpolation = expression;
expect(interpolation.elements, hasLength(3));
expect(interpolation.elements[0], new isInstanceOf<InterpolationString>());
InterpolationString element0 = interpolation.elements[0];
@@ -9885,9 +11058,12 @@
}
void test_parseStringLiteral_multiline_startsWithInterpolation() {
- StringLiteral literal = parse4('parseStringLiteral', r"'''${x}y'''");
- expect(literal, new isInstanceOf<StringInterpolation>());
- StringInterpolation interpolation = literal;
+ createParser(r"'''${x}y'''");
+ Expression expression = parser.parseStringLiteral();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<StringInterpolation>());
+ StringInterpolation interpolation = expression;
expect(interpolation.elements, hasLength(3));
expect(interpolation.elements[0], new isInstanceOf<InterpolationString>());
InterpolationString element0 = interpolation.elements[0];
@@ -9902,27 +11078,45 @@
}
void test_parseStringLiteral_multiline_twoSpaces() {
- SimpleStringLiteral literal = parse4("parseStringLiteral", "''' \na'''");
+ createParser("''' \na'''");
+ Expression expression = parser.parseStringLiteral();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<SimpleStringLiteral>());
+ SimpleStringLiteral literal = expression;
expect(literal.literal, isNotNull);
expect(literal.value, "a");
}
void test_parseStringLiteral_multiline_twoSpaces_raw() {
- SimpleStringLiteral literal = parse4("parseStringLiteral", "r''' \na'''");
+ createParser("r''' \na'''");
+ Expression expression = parser.parseStringLiteral();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<SimpleStringLiteral>());
+ SimpleStringLiteral literal = expression;
expect(literal.literal, isNotNull);
expect(literal.value, "a");
}
void test_parseStringLiteral_multiline_untrimmed() {
- SimpleStringLiteral literal = parse4("parseStringLiteral", "''' a\nb'''");
+ createParser("''' a\nb'''");
+ Expression expression = parser.parseStringLiteral();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<SimpleStringLiteral>());
+ SimpleStringLiteral literal = expression;
expect(literal.literal, isNotNull);
expect(literal.value, " a\nb");
}
void test_parseStringLiteral_quoteAfterInterpolation() {
- StringLiteral literal = parse4('parseStringLiteral', r"""'$x"'""");
- expect(literal, new isInstanceOf<StringInterpolation>());
- StringInterpolation interpolation = literal;
+ createParser(r"""'$x"'""");
+ Expression expression = parser.parseStringLiteral();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<StringInterpolation>());
+ StringInterpolation interpolation = expression;
expect(interpolation.elements, hasLength(3));
expect(interpolation.elements[0], new isInstanceOf<InterpolationString>());
InterpolationString element0 = interpolation.elements[0];
@@ -9937,15 +11131,23 @@
}
void test_parseStringLiteral_single() {
- SimpleStringLiteral literal = parse4("parseStringLiteral", "'a'");
+ createParser("'a'");
+ Expression expression = parser.parseStringLiteral();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<SimpleStringLiteral>());
+ SimpleStringLiteral literal = expression;
expect(literal.literal, isNotNull);
expect(literal.value, "a");
}
void test_parseStringLiteral_startsWithInterpolation() {
- StringLiteral literal = parse4('parseStringLiteral', r"'${x}y'");
- expect(literal, new isInstanceOf<StringInterpolation>());
- StringInterpolation interpolation = literal;
+ createParser(r"'${x}y'");
+ Expression expression = parser.parseStringLiteral();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<StringInterpolation>());
+ StringInterpolation interpolation = expression;
expect(interpolation.elements, hasLength(3));
expect(interpolation.elements[0], new isInstanceOf<InterpolationString>());
InterpolationString element0 = interpolation.elements[0];
@@ -9960,8 +11162,11 @@
}
void test_parseSuperConstructorInvocation_named() {
+ createParser('super.a()');
SuperConstructorInvocation invocation =
- parse4("parseSuperConstructorInvocation", "super.a()");
+ parser.parseSuperConstructorInvocation();
+ expectNotNullIfNoErrors(invocation);
+ listener.assertNoErrors();
expect(invocation.argumentList, isNotNull);
expect(invocation.constructorName, isNotNull);
expect(invocation.superKeyword, isNotNull);
@@ -9969,8 +11174,11 @@
}
void test_parseSuperConstructorInvocation_unnamed() {
+ createParser('super()');
SuperConstructorInvocation invocation =
- parse4("parseSuperConstructorInvocation", "super()");
+ parser.parseSuperConstructorInvocation();
+ expectNotNullIfNoErrors(invocation);
+ listener.assertNoErrors();
expect(invocation.argumentList, isNotNull);
expect(invocation.constructorName, isNull);
expect(invocation.superKeyword, isNotNull);
@@ -9978,8 +11186,10 @@
}
void test_parseSwitchStatement_case() {
- SwitchStatement statement =
- parse4("parseSwitchStatement", "switch (a) {case 1: return 'I';}");
+ createParser('switch (a) {case 1: return "I";}');
+ SwitchStatement statement = parser.parseSwitchStatement();
+ expectNotNullIfNoErrors(statement);
+ listener.assertNoErrors();
expect(statement.switchKeyword, isNotNull);
expect(statement.leftParenthesis, isNotNull);
expect(statement.expression, isNotNull);
@@ -9990,7 +11200,10 @@
}
void test_parseSwitchStatement_empty() {
- SwitchStatement statement = parse4("parseSwitchStatement", "switch (a) {}");
+ createParser('switch (a) {}');
+ SwitchStatement statement = parser.parseSwitchStatement();
+ expectNotNullIfNoErrors(statement);
+ listener.assertNoErrors();
expect(statement.switchKeyword, isNotNull);
expect(statement.leftParenthesis, isNotNull);
expect(statement.expression, isNotNull);
@@ -10001,8 +11214,10 @@
}
void test_parseSwitchStatement_labeledCase() {
- SwitchStatement statement =
- parse4("parseSwitchStatement", "switch (a) {l1: l2: l3: case(1):}");
+ createParser('switch (a) {l1: l2: l3: case(1):}');
+ SwitchStatement statement = parser.parseSwitchStatement();
+ expectNotNullIfNoErrors(statement);
+ listener.assertNoErrors();
expect(statement.switchKeyword, isNotNull);
expect(statement.leftParenthesis, isNotNull);
expect(statement.expression, isNotNull);
@@ -10020,8 +11235,10 @@
}
void test_parseSwitchStatement_labeledDefault() {
- SwitchStatement statement =
- parse4("parseSwitchStatement", "switch (a) {l1: l2: l3: default:}");
+ createParser('switch (a) {l1: l2: l3: default:}');
+ SwitchStatement statement = parser.parseSwitchStatement();
+ expectNotNullIfNoErrors(statement);
+ listener.assertNoErrors();
expect(statement.switchKeyword, isNotNull);
expect(statement.leftParenthesis, isNotNull);
expect(statement.expression, isNotNull);
@@ -10039,8 +11256,10 @@
}
void test_parseSwitchStatement_labeledStatementInCase() {
- SwitchStatement statement = parse4(
- "parseSwitchStatement", "switch (a) {case 0: f(); l1: g(); break;}");
+ createParser('switch (a) {case 0: f(); l1: g(); break;}');
+ SwitchStatement statement = parser.parseSwitchStatement();
+ expectNotNullIfNoErrors(statement);
+ listener.assertNoErrors();
expect(statement.switchKeyword, isNotNull);
expect(statement.leftParenthesis, isNotNull);
expect(statement.expression, isNotNull);
@@ -10052,8 +11271,10 @@
}
void test_parseSymbolLiteral_builtInIdentifier() {
- SymbolLiteral literal =
- parse4("parseSymbolLiteral", "#dynamic.static.abstract");
+ createParser('#dynamic.static.abstract');
+ SymbolLiteral literal = parser.parseSymbolLiteral();
+ expectNotNullIfNoErrors(literal);
+ listener.assertNoErrors();
expect(literal.poundSign, isNotNull);
List<Token> components = literal.components;
expect(components, hasLength(3));
@@ -10063,7 +11284,10 @@
}
void test_parseSymbolLiteral_multiple() {
- SymbolLiteral literal = parse4("parseSymbolLiteral", "#a.b.c");
+ createParser('#a.b.c');
+ SymbolLiteral literal = parser.parseSymbolLiteral();
+ expectNotNullIfNoErrors(literal);
+ listener.assertNoErrors();
expect(literal.poundSign, isNotNull);
List<Token> components = literal.components;
expect(components, hasLength(3));
@@ -10073,7 +11297,10 @@
}
void test_parseSymbolLiteral_operator() {
- SymbolLiteral literal = parse4("parseSymbolLiteral", "#==");
+ createParser('#==');
+ SymbolLiteral literal = parser.parseSymbolLiteral();
+ expectNotNullIfNoErrors(literal);
+ listener.assertNoErrors();
expect(literal.poundSign, isNotNull);
List<Token> components = literal.components;
expect(components, hasLength(1));
@@ -10081,7 +11308,10 @@
}
void test_parseSymbolLiteral_single() {
- SymbolLiteral literal = parse4("parseSymbolLiteral", "#a");
+ createParser('#a');
+ SymbolLiteral literal = parser.parseSymbolLiteral();
+ expectNotNullIfNoErrors(literal);
+ listener.assertNoErrors();
expect(literal.poundSign, isNotNull);
List<Token> components = literal.components;
expect(components, hasLength(1));
@@ -10089,7 +11319,10 @@
}
void test_parseSymbolLiteral_void() {
- SymbolLiteral literal = parse4("parseSymbolLiteral", "#void");
+ createParser('#void');
+ SymbolLiteral literal = parser.parseSymbolLiteral();
+ expectNotNullIfNoErrors(literal);
+ listener.assertNoErrors();
expect(literal.poundSign, isNotNull);
List<Token> components = literal.components;
expect(components, hasLength(1));
@@ -10097,20 +11330,32 @@
}
void test_parseThrowExpression() {
- ThrowExpression expression = parse4("parseThrowExpression", "throw x;");
- expect(expression.throwKeyword, isNotNull);
- expect(expression.expression, isNotNull);
+ createParser('throw x;');
+ Expression expression = parser.parseThrowExpression();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<ThrowExpression>());
+ ThrowExpression throwExpression = expression;
+ expect(throwExpression.throwKeyword, isNotNull);
+ expect(throwExpression.expression, isNotNull);
}
void test_parseThrowExpressionWithoutCascade() {
- ThrowExpression expression =
- parse4("parseThrowExpressionWithoutCascade", "throw x;");
- expect(expression.throwKeyword, isNotNull);
- expect(expression.expression, isNotNull);
+ createParser('throw x;');
+ Expression expression = parser.parseThrowExpressionWithoutCascade();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
+ expect(expression, new isInstanceOf<ThrowExpression>());
+ ThrowExpression throwExpression = expression;
+ expect(throwExpression.throwKeyword, isNotNull);
+ expect(throwExpression.expression, isNotNull);
}
void test_parseTryStatement_catch() {
- TryStatement statement = parse4("parseTryStatement", "try {} catch (e) {}");
+ createParser('try {} catch (e) {}');
+ TryStatement statement = parser.parseTryStatement();
+ expectNotNullIfNoErrors(statement);
+ listener.assertNoErrors();
expect(statement.tryKeyword, isNotNull);
expect(statement.body, isNotNull);
NodeList<CatchClause> catchClauses = statement.catchClauses;
@@ -10128,8 +11373,10 @@
}
void test_parseTryStatement_catch_finally() {
- TryStatement statement =
- parse4("parseTryStatement", "try {} catch (e, s) {} finally {}");
+ createParser('try {} catch (e, s) {} finally {}');
+ TryStatement statement = parser.parseTryStatement();
+ expectNotNullIfNoErrors(statement);
+ listener.assertNoErrors();
expect(statement.tryKeyword, isNotNull);
expect(statement.body, isNotNull);
NodeList<CatchClause> catchClauses = statement.catchClauses;
@@ -10147,7 +11394,10 @@
}
void test_parseTryStatement_finally() {
- TryStatement statement = parse4("parseTryStatement", "try {} finally {}");
+ createParser('try {} finally {}');
+ TryStatement statement = parser.parseTryStatement();
+ expectNotNullIfNoErrors(statement);
+ listener.assertNoErrors();
expect(statement.tryKeyword, isNotNull);
expect(statement.body, isNotNull);
expect(statement.catchClauses, hasLength(0));
@@ -10156,8 +11406,10 @@
}
void test_parseTryStatement_multiple() {
- TryStatement statement = parse4("parseTryStatement",
- "try {} on NPE catch (e) {} on Error {} catch (e) {}");
+ createParser('try {} on NPE catch (e) {} on Error {} catch (e) {}');
+ TryStatement statement = parser.parseTryStatement();
+ expectNotNullIfNoErrors(statement);
+ listener.assertNoErrors();
expect(statement.tryKeyword, isNotNull);
expect(statement.body, isNotNull);
expect(statement.catchClauses, hasLength(3));
@@ -10166,7 +11418,10 @@
}
void test_parseTryStatement_on() {
- TryStatement statement = parse4("parseTryStatement", "try {} on Error {}");
+ createParser('try {} on Error {}');
+ TryStatement statement = parser.parseTryStatement();
+ expectNotNullIfNoErrors(statement);
+ listener.assertNoErrors();
expect(statement.tryKeyword, isNotNull);
expect(statement.body, isNotNull);
NodeList<CatchClause> catchClauses = statement.catchClauses;
@@ -10184,8 +11439,10 @@
}
void test_parseTryStatement_on_catch() {
- TryStatement statement =
- parse4("parseTryStatement", "try {} on Error catch (e, s) {}");
+ createParser('try {} on Error catch (e, s) {}');
+ TryStatement statement = parser.parseTryStatement();
+ expectNotNullIfNoErrors(statement);
+ listener.assertNoErrors();
expect(statement.tryKeyword, isNotNull);
expect(statement.body, isNotNull);
NodeList<CatchClause> catchClauses = statement.catchClauses;
@@ -10203,8 +11460,10 @@
}
void test_parseTryStatement_on_catch_finally() {
- TryStatement statement = parse4(
- "parseTryStatement", "try {} on Error catch (e, s) {} finally {}");
+ createParser('try {} on Error catch (e, s) {} finally {}');
+ TryStatement statement = parser.parseTryStatement();
+ expectNotNullIfNoErrors(statement);
+ listener.assertNoErrors();
expect(statement.tryKeyword, isNotNull);
expect(statement.body, isNotNull);
NodeList<CatchClause> catchClauses = statement.catchClauses;
@@ -10288,23 +11547,30 @@
}
void test_parseTypeArgumentList_empty() {
- TypeArgumentList argumentList = parse4(
- "parseTypeArgumentList", "<>", [ParserErrorCode.EXPECTED_TYPE_NAME]);
+ createParser('<>');
+ TypeArgumentList argumentList = parser.parseTypeArgumentList();
+ expectNotNullIfNoErrors(argumentList);
+ listener.assertErrorsWithCodes([ParserErrorCode.EXPECTED_TYPE_NAME]);
expect(argumentList.leftBracket, isNotNull);
expect(argumentList.arguments, hasLength(1));
expect(argumentList.rightBracket, isNotNull);
}
void test_parseTypeArgumentList_multiple() {
- TypeArgumentList argumentList =
- parse4("parseTypeArgumentList", "<int, int, int>");
+ createParser('<int, int, int>');
+ TypeArgumentList argumentList = parser.parseTypeArgumentList();
+ expectNotNullIfNoErrors(argumentList);
+ listener.assertNoErrors();
expect(argumentList.leftBracket, isNotNull);
expect(argumentList.arguments, hasLength(3));
expect(argumentList.rightBracket, isNotNull);
}
void test_parseTypeArgumentList_nested() {
- TypeArgumentList argumentList = parse4("parseTypeArgumentList", "<A<B>>");
+ createParser('<A<B>>');
+ TypeArgumentList argumentList = parser.parseTypeArgumentList();
+ expectNotNullIfNoErrors(argumentList);
+ listener.assertNoErrors();
expect(argumentList.leftBracket, isNotNull);
expect(argumentList.arguments, hasLength(1));
TypeName argument = argumentList.arguments[0];
@@ -10316,8 +11582,10 @@
}
void test_parseTypeArgumentList_nested_withComment_double() {
- TypeArgumentList argumentList =
- parse4("parseTypeArgumentList", "<A<B /* 0 */ >>");
+ createParser('<A<B /* 0 */ >>');
+ TypeArgumentList argumentList = parser.parseTypeArgumentList();
+ expectNotNullIfNoErrors(argumentList);
+ listener.assertNoErrors();
expect(argumentList.leftBracket, isNotNull);
expect(argumentList.rightBracket, isNotNull);
expect(argumentList.arguments, hasLength(1));
@@ -10334,8 +11602,10 @@
}
void test_parseTypeArgumentList_nested_withComment_tripple() {
- TypeArgumentList argumentList =
- parse4("parseTypeArgumentList", "<A<B<C /* 0 */ >>>");
+ createParser('<A<B<C /* 0 */ >>>');
+ TypeArgumentList argumentList = parser.parseTypeArgumentList();
+ expectNotNullIfNoErrors(argumentList);
+ listener.assertNoErrors();
expect(argumentList.leftBracket, isNotNull);
expect(argumentList.rightBracket, isNotNull);
expect(argumentList.arguments, hasLength(1));
@@ -10361,77 +11631,132 @@
}
void test_parseTypeArgumentList_single() {
- TypeArgumentList argumentList = parse4("parseTypeArgumentList", "<int>");
+ createParser('<int>');
+ TypeArgumentList argumentList = parser.parseTypeArgumentList();
+ expectNotNullIfNoErrors(argumentList);
+ listener.assertNoErrors();
expect(argumentList.leftBracket, isNotNull);
expect(argumentList.arguments, hasLength(1));
expect(argumentList.rightBracket, isNotNull);
}
void test_parseTypeName_parameterized() {
- TypeName typeName = parse4("parseTypeName", "List<int>");
+ createParser('List<int>');
+ TypeName typeName = parser.parseTypeName(false);
+ expectNotNullIfNoErrors(typeName);
+ listener.assertNoErrors();
expect(typeName.name, isNotNull);
expect(typeName.typeArguments, isNotNull);
+ expect(typeName.question, isNull);
+ }
+
+ void test_parseTypeName_parameterized_nullable() {
+ enableNnbd = true;
+ createParser('List<int>?');
+ TypeName typeName = parser.parseTypeName(false);
+ expectNotNullIfNoErrors(typeName);
+ listener.assertNoErrors();
+ expect(typeName.name, isNotNull);
+ expect(typeName.typeArguments, isNotNull);
+ expect(typeName.question, isNotNull);
}
void test_parseTypeName_simple() {
- TypeName typeName = parse4("parseTypeName", "int");
+ createParser('int');
+ TypeName typeName = parser.parseTypeName(false);
+ expectNotNullIfNoErrors(typeName);
+ listener.assertNoErrors();
expect(typeName.name, isNotNull);
expect(typeName.typeArguments, isNull);
+ expect(typeName.question, isNull);
+ }
+
+ void test_parseTypeName_simple_nullable() {
+ enableNnbd = true;
+ createParser('String?');
+ TypeName typeName = parser.parseTypeName(false);
+ expectNotNullIfNoErrors(typeName);
+ listener.assertNoErrors();
+ expect(typeName.name, isNotNull);
+ expect(typeName.typeArguments, isNull);
+ expect(typeName.question, isNotNull);
}
void test_parseTypeParameter_bounded() {
- TypeParameter parameter = parse4("parseTypeParameter", "A extends B");
+ createParser('A extends B');
+ TypeParameter parameter = parser.parseTypeParameter();
+ expectNotNullIfNoErrors(parameter);
+ listener.assertNoErrors();
expect(parameter.bound, isNotNull);
expect(parameter.extendsKeyword, isNotNull);
expect(parameter.name, isNotNull);
}
void test_parseTypeParameter_simple() {
- TypeParameter parameter = parse4("parseTypeParameter", "A");
+ createParser('A');
+ TypeParameter parameter = parser.parseTypeParameter();
+ expectNotNullIfNoErrors(parameter);
+ listener.assertNoErrors();
expect(parameter.bound, isNull);
expect(parameter.extendsKeyword, isNull);
expect(parameter.name, isNotNull);
}
void test_parseTypeParameterList_multiple() {
- TypeParameterList parameterList =
- parse4("parseTypeParameterList", "<A, B extends C, D>");
+ createParser('<A, B extends C, D>');
+ TypeParameterList parameterList = parser.parseTypeParameterList();
+ expectNotNullIfNoErrors(parameterList);
+ listener.assertNoErrors();
expect(parameterList.leftBracket, isNotNull);
expect(parameterList.rightBracket, isNotNull);
expect(parameterList.typeParameters, hasLength(3));
}
void test_parseTypeParameterList_parameterizedWithTrailingEquals() {
- TypeParameterList parameterList =
- parse4("parseTypeParameterList", "<A extends B<E>>=");
+ createParser('<A extends B<E>>=');
+ TypeParameterList parameterList = parser.parseTypeParameterList();
+ expectNotNullIfNoErrors(parameterList);
+ listener.assertNoErrors();
expect(parameterList.leftBracket, isNotNull);
expect(parameterList.rightBracket, isNotNull);
expect(parameterList.typeParameters, hasLength(1));
}
void test_parseTypeParameterList_single() {
- TypeParameterList parameterList = parse4("parseTypeParameterList", "<A>");
+ createParser('<<A>');
+ TypeParameterList parameterList = parser.parseTypeParameterList();
+ expectNotNullIfNoErrors(parameterList);
+ listener.assertNoErrors();
expect(parameterList.leftBracket, isNotNull);
expect(parameterList.rightBracket, isNotNull);
expect(parameterList.typeParameters, hasLength(1));
}
void test_parseTypeParameterList_withTrailingEquals() {
- TypeParameterList parameterList = parse4("parseTypeParameterList", "<A>=");
+ createParser('<A>=');
+ TypeParameterList parameterList = parser.parseTypeParameterList();
+ expectNotNullIfNoErrors(parameterList);
+ listener.assertNoErrors();
expect(parameterList.leftBracket, isNotNull);
expect(parameterList.rightBracket, isNotNull);
expect(parameterList.typeParameters, hasLength(1));
}
void test_parseUnaryExpression_decrement_normal() {
- PrefixExpression expression = parse4("parseUnaryExpression", "--x");
+ createParser('--x');
+ PrefixExpression expression = parser.parseUnaryExpression();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
expect(expression.operator, isNotNull);
expect(expression.operator.type, TokenType.MINUS_MINUS);
expect(expression.operand, isNotNull);
}
void test_parseUnaryExpression_decrement_super() {
- PrefixExpression expression = parse4("parseUnaryExpression", "--super");
+ createParser('--super');
+ PrefixExpression expression = parser.parseUnaryExpression();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
expect(expression.operator, isNotNull);
expect(expression.operator.type, TokenType.MINUS);
Expression innerExpression = expression.operand;
@@ -10444,7 +11769,10 @@
}
void test_parseUnaryExpression_decrement_super_propertyAccess() {
- PrefixExpression expression = parse4("parseUnaryExpression", "--super.x");
+ createParser('--super.x');
+ PrefixExpression expression = parser.parseUnaryExpression();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
expect(expression.operator, isNotNull);
expect(expression.operator.type, TokenType.MINUS_MINUS);
expect(expression.operand, isNotNull);
@@ -10454,8 +11782,10 @@
}
void test_parseUnaryExpression_decrement_super_withComment() {
- PrefixExpression expression =
- parse4("parseUnaryExpression", "/* 0 */ --super");
+ createParser('/* 0 */ --super');
+ PrefixExpression expression = parser.parseUnaryExpression();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
expect(expression.operator, isNotNull);
expect(expression.operator.type, TokenType.MINUS);
expect(expression.operator.precedingComments, isNotNull);
@@ -10469,14 +11799,20 @@
}
void test_parseUnaryExpression_increment_normal() {
- PrefixExpression expression = parse4("parseUnaryExpression", "++x");
+ createParser('++x');
+ PrefixExpression expression = parser.parseUnaryExpression();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
expect(expression.operator, isNotNull);
expect(expression.operator.type, TokenType.PLUS_PLUS);
expect(expression.operand, isNotNull);
}
void test_parseUnaryExpression_increment_super_index() {
- PrefixExpression expression = parse4("parseUnaryExpression", "++super[0]");
+ createParser('++super[0]');
+ PrefixExpression expression = parser.parseUnaryExpression();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
expect(expression.operator, isNotNull);
expect(expression.operator.type, TokenType.PLUS_PLUS);
expect(expression.operand, isNotNull);
@@ -10486,7 +11822,10 @@
}
void test_parseUnaryExpression_increment_super_propertyAccess() {
- PrefixExpression expression = parse4("parseUnaryExpression", "++super.x");
+ createParser('++super.x');
+ PrefixExpression expression = parser.parseUnaryExpression();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
expect(expression.operator, isNotNull);
expect(expression.operator.type, TokenType.PLUS_PLUS);
expect(expression.operand, isNotNull);
@@ -10496,97 +11835,124 @@
}
void test_parseUnaryExpression_minus_normal() {
- PrefixExpression expression = parse4("parseUnaryExpression", "-x");
+ createParser('-x');
+ PrefixExpression expression = parser.parseUnaryExpression();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
expect(expression.operator, isNotNull);
expect(expression.operator.type, TokenType.MINUS);
expect(expression.operand, isNotNull);
}
void test_parseUnaryExpression_minus_super() {
- PrefixExpression expression = parse4("parseUnaryExpression", "-super");
+ createParser('-super');
+ PrefixExpression expression = parser.parseUnaryExpression();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
expect(expression.operator, isNotNull);
expect(expression.operator.type, TokenType.MINUS);
expect(expression.operand, isNotNull);
}
void test_parseUnaryExpression_not_normal() {
- PrefixExpression expression = parse4("parseUnaryExpression", "!x");
+ createParser('!x');
+ PrefixExpression expression = parser.parseUnaryExpression();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
expect(expression.operator, isNotNull);
expect(expression.operator.type, TokenType.BANG);
expect(expression.operand, isNotNull);
}
void test_parseUnaryExpression_not_super() {
- PrefixExpression expression = parse4("parseUnaryExpression", "!super");
+ createParser('!super');
+ PrefixExpression expression = parser.parseUnaryExpression();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
expect(expression.operator, isNotNull);
expect(expression.operator.type, TokenType.BANG);
expect(expression.operand, isNotNull);
}
void test_parseUnaryExpression_tilda_normal() {
- PrefixExpression expression = parse4("parseUnaryExpression", "~x");
+ createParser('~x');
+ PrefixExpression expression = parser.parseUnaryExpression();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
expect(expression.operator, isNotNull);
expect(expression.operator.type, TokenType.TILDE);
expect(expression.operand, isNotNull);
}
void test_parseUnaryExpression_tilda_super() {
- PrefixExpression expression = parse4("parseUnaryExpression", "~super");
+ createParser('~super');
+ PrefixExpression expression = parser.parseUnaryExpression();
+ expectNotNullIfNoErrors(expression);
+ listener.assertNoErrors();
expect(expression.operator, isNotNull);
expect(expression.operator.type, TokenType.TILDE);
expect(expression.operand, isNotNull);
}
void test_parseVariableDeclaration_equals() {
- VariableDeclaration declaration =
- parse4("parseVariableDeclaration", "a = b");
+ createParser('a = b');
+ VariableDeclaration declaration = parser.parseVariableDeclaration();
+ expectNotNullIfNoErrors(declaration);
+ listener.assertNoErrors();
expect(declaration.name, isNotNull);
expect(declaration.equals, isNotNull);
expect(declaration.initializer, isNotNull);
}
void test_parseVariableDeclaration_noEquals() {
- VariableDeclaration declaration = parse4("parseVariableDeclaration", "a");
+ createParser('a');
+ VariableDeclaration declaration = parser.parseVariableDeclaration();
+ expectNotNullIfNoErrors(declaration);
+ listener.assertNoErrors();
expect(declaration.name, isNotNull);
expect(declaration.equals, isNull);
expect(declaration.initializer, isNull);
}
void test_parseVariableDeclarationListAfterMetadata_const_noType() {
- VariableDeclarationList declarationList = parse(
- "parseVariableDeclarationListAfterMetadata",
- <Object>[emptyCommentAndMetadata()],
- "const a");
+ createParser('const a');
+ VariableDeclarationList declarationList = parser
+ .parseVariableDeclarationListAfterMetadata(emptyCommentAndMetadata());
+ expectNotNullIfNoErrors(declarationList);
+ listener.assertNoErrors();
expect(declarationList.keyword, isNotNull);
expect(declarationList.type, isNull);
expect(declarationList.variables, hasLength(1));
}
void test_parseVariableDeclarationListAfterMetadata_const_type() {
- VariableDeclarationList declarationList = parse(
- "parseVariableDeclarationListAfterMetadata",
- <Object>[emptyCommentAndMetadata()],
- "const A a");
+ createParser('const A a');
+ VariableDeclarationList declarationList = parser
+ .parseVariableDeclarationListAfterMetadata(emptyCommentAndMetadata());
+ expectNotNullIfNoErrors(declarationList);
+ listener.assertNoErrors();
expect(declarationList.keyword, isNotNull);
expect(declarationList.type, isNotNull);
expect(declarationList.variables, hasLength(1));
}
void test_parseVariableDeclarationListAfterMetadata_final_noType() {
- VariableDeclarationList declarationList = parse(
- "parseVariableDeclarationListAfterMetadata",
- <Object>[emptyCommentAndMetadata()],
- "final a");
+ createParser('final a');
+ VariableDeclarationList declarationList = parser
+ .parseVariableDeclarationListAfterMetadata(emptyCommentAndMetadata());
+ expectNotNullIfNoErrors(declarationList);
+ listener.assertNoErrors();
expect(declarationList.keyword, isNotNull);
expect(declarationList.type, isNull);
expect(declarationList.variables, hasLength(1));
}
void test_parseVariableDeclarationListAfterMetadata_final_type() {
- VariableDeclarationList declarationList = parse(
- "parseVariableDeclarationListAfterMetadata",
- <Object>[emptyCommentAndMetadata()],
- "final A a");
+ createParser('final A a');
+ VariableDeclarationList declarationList = parser
+ .parseVariableDeclarationListAfterMetadata(emptyCommentAndMetadata());
+ expectNotNullIfNoErrors(declarationList);
+ listener.assertNoErrors();
expect(declarationList.keyword, isNotNull);
expect(declarationList.type, isNotNull);
expect(declarationList.variables, hasLength(1));
@@ -10594,49 +11960,54 @@
void test_parseVariableDeclarationListAfterMetadata_final_typeComment() {
enableGenericMethodComments = true;
- VariableDeclarationList decl = parse(
- "parseVariableDeclarationListAfterMetadata",
- <Object>[emptyCommentAndMetadata()],
- "final/*=T*/ x");
- expect(decl.type.name.name, 'T');
- expect(decl.isFinal, true);
+ createParser('final/*=T*/ x');
+ VariableDeclarationList declarationList = parser
+ .parseVariableDeclarationListAfterMetadata(emptyCommentAndMetadata());
+ expectNotNullIfNoErrors(declarationList);
+ listener.assertNoErrors();
+ expect(declarationList.type.name.name, 'T');
+ expect(declarationList.isFinal, true);
}
void test_parseVariableDeclarationListAfterMetadata_type_multiple() {
- VariableDeclarationList declarationList = parse(
- "parseVariableDeclarationListAfterMetadata",
- <Object>[emptyCommentAndMetadata()],
- "A a, b, c");
+ createParser('A a, b, c');
+ VariableDeclarationList declarationList = parser
+ .parseVariableDeclarationListAfterMetadata(emptyCommentAndMetadata());
+ expectNotNullIfNoErrors(declarationList);
+ listener.assertNoErrors();
expect(declarationList.keyword, isNull);
expect(declarationList.type, isNotNull);
expect(declarationList.variables, hasLength(3));
}
void test_parseVariableDeclarationListAfterMetadata_type_single() {
- VariableDeclarationList declarationList = parse(
- "parseVariableDeclarationListAfterMetadata",
- <Object>[emptyCommentAndMetadata()],
- "A a");
+ createParser('A a');
+ VariableDeclarationList declarationList = parser
+ .parseVariableDeclarationListAfterMetadata(emptyCommentAndMetadata());
+ expectNotNullIfNoErrors(declarationList);
+ listener.assertNoErrors();
expect(declarationList.keyword, isNull);
expect(declarationList.type, isNotNull);
expect(declarationList.variables, hasLength(1));
}
void test_parseVariableDeclarationListAfterMetadata_var_multiple() {
- VariableDeclarationList declarationList = parse(
- "parseVariableDeclarationListAfterMetadata",
- <Object>[emptyCommentAndMetadata()],
- "var a, b, c");
+ createParser('var a, b, c');
+ VariableDeclarationList declarationList = parser
+ .parseVariableDeclarationListAfterMetadata(emptyCommentAndMetadata());
+ expectNotNullIfNoErrors(declarationList);
+ listener.assertNoErrors();
expect(declarationList.keyword, isNotNull);
expect(declarationList.type, isNull);
expect(declarationList.variables, hasLength(3));
}
void test_parseVariableDeclarationListAfterMetadata_var_single() {
- VariableDeclarationList declarationList = parse(
- "parseVariableDeclarationListAfterMetadata",
- <Object>[emptyCommentAndMetadata()],
- "var a");
+ createParser('var a');
+ VariableDeclarationList declarationList = parser
+ .parseVariableDeclarationListAfterMetadata(emptyCommentAndMetadata());
+ expectNotNullIfNoErrors(declarationList);
+ listener.assertNoErrors();
expect(declarationList.keyword, isNotNull);
expect(declarationList.type, isNull);
expect(declarationList.variables, hasLength(1));
@@ -10644,20 +12015,23 @@
void test_parseVariableDeclarationListAfterMetadata_var_typeComment() {
enableGenericMethodComments = true;
- VariableDeclarationList decl = parse(
- "parseVariableDeclarationListAfterMetadata",
- <Object>[emptyCommentAndMetadata()],
- "var/*=T*/ x");
- expect(decl.type.name.name, 'T');
- expect(decl.keyword, isNull);
+ createParser('var/*=T*/ x');
+ VariableDeclarationList declarationList = parser
+ .parseVariableDeclarationListAfterMetadata(emptyCommentAndMetadata());
+ expectNotNullIfNoErrors(declarationList);
+ listener.assertNoErrors();
+ expect(declarationList.type.name.name, 'T');
+ expect(declarationList.keyword, isNull);
}
void test_parseVariableDeclarationListAfterType_type() {
TypeName type = new TypeName(new SimpleIdentifier(null), null);
- VariableDeclarationList declarationList = parse(
- "parseVariableDeclarationListAfterType",
- <Object>[emptyCommentAndMetadata(), null, type],
- "a");
+ createParser('a');
+ VariableDeclarationList declarationList =
+ parser.parseVariableDeclarationListAfterType(
+ emptyCommentAndMetadata(), null, type);
+ expectNotNullIfNoErrors(declarationList);
+ listener.assertNoErrors();
expect(declarationList.keyword, isNull);
expect(declarationList.type, type);
expect(declarationList.variables, hasLength(1));
@@ -10665,20 +12039,24 @@
void test_parseVariableDeclarationListAfterType_var() {
Token keyword = TokenFactory.tokenFromKeyword(Keyword.VAR);
- VariableDeclarationList declarationList = parse(
- "parseVariableDeclarationListAfterType",
- <Object>[emptyCommentAndMetadata(), keyword, null],
- "a, b, c");
+ createParser('a, b, c');
+ VariableDeclarationList declarationList =
+ parser.parseVariableDeclarationListAfterType(
+ emptyCommentAndMetadata(), keyword, null);
+ expectNotNullIfNoErrors(declarationList);
+ listener.assertNoErrors();
expect(declarationList.keyword, keyword);
expect(declarationList.type, isNull);
expect(declarationList.variables, hasLength(3));
}
void test_parseVariableDeclarationStatementAfterMetadata_multiple() {
- VariableDeclarationStatement statement = parse(
- "parseVariableDeclarationStatementAfterMetadata",
- <Object>[emptyCommentAndMetadata()],
- "var x, y, z;");
+ createParser('var x, y, z;');
+ VariableDeclarationStatement statement =
+ parser.parseVariableDeclarationStatementAfterMetadata(
+ emptyCommentAndMetadata());
+ expectNotNullIfNoErrors(statement);
+ listener.assertNoErrors();
expect(statement.semicolon, isNotNull);
VariableDeclarationList variableList = statement.variables;
expect(variableList, isNotNull);
@@ -10686,10 +12064,12 @@
}
void test_parseVariableDeclarationStatementAfterMetadata_single() {
- VariableDeclarationStatement statement = parse(
- "parseVariableDeclarationStatementAfterMetadata",
- <Object>[emptyCommentAndMetadata()],
- "var x;");
+ createParser('var x;');
+ VariableDeclarationStatement statement =
+ parser.parseVariableDeclarationStatementAfterMetadata(
+ emptyCommentAndMetadata());
+ expectNotNullIfNoErrors(statement);
+ listener.assertNoErrors();
expect(statement.semicolon, isNotNull);
VariableDeclarationList variableList = statement.variables;
expect(variableList, isNotNull);
@@ -10697,7 +12077,10 @@
}
void test_parseWhileStatement() {
- WhileStatement statement = parse4("parseWhileStatement", "while (x) {}");
+ createParser('while (x) {}');
+ WhileStatement statement = parser.parseWhileStatement();
+ expectNotNullIfNoErrors(statement);
+ listener.assertNoErrors();
expect(statement.whileKeyword, isNotNull);
expect(statement.leftParenthesis, isNotNull);
expect(statement.condition, isNotNull);
@@ -10706,19 +12089,28 @@
}
void test_parseWithClause_multiple() {
- WithClause clause = parse4("parseWithClause", "with A, B, C");
+ createParser('with A, B, C');
+ WithClause clause = parser.parseWithClause();
+ expectNotNullIfNoErrors(clause);
+ listener.assertNoErrors();
expect(clause.withKeyword, isNotNull);
expect(clause.mixinTypes, hasLength(3));
}
void test_parseWithClause_single() {
- WithClause clause = parse4("parseWithClause", "with M");
+ createParser('with M');
+ WithClause clause = parser.parseWithClause();
+ expectNotNullIfNoErrors(clause);
+ listener.assertNoErrors();
expect(clause.withKeyword, isNotNull);
expect(clause.mixinTypes, hasLength(1));
}
void test_parseYieldStatement_each() {
- YieldStatement statement = parse4("parseYieldStatement", "yield* x;");
+ createParser('yield* x;');
+ YieldStatement statement = parser.parseYieldStatement();
+ expectNotNullIfNoErrors(statement);
+ listener.assertNoErrors();
expect(statement.yieldKeyword, isNotNull);
expect(statement.star, isNotNull);
expect(statement.expression, isNotNull);
@@ -10726,7 +12118,10 @@
}
void test_parseYieldStatement_normal() {
- YieldStatement statement = parse4("parseYieldStatement", "yield x;");
+ createParser('yield x;');
+ YieldStatement statement = parser.parseYieldStatement();
+ expectNotNullIfNoErrors(statement);
+ listener.assertNoErrors();
expect(statement.yieldKeyword, isNotNull);
expect(statement.star, isNull);
expect(statement.expression, isNotNull);
@@ -10734,109 +12129,128 @@
}
void test_skipPrefixedIdentifier_invalid() {
- Token following = _skip("skipPrefixedIdentifier", "+");
+ createParser('+');
+ Token following = parser.skipPrefixedIdentifier(parser.currentToken);
expect(following, isNull);
}
void test_skipPrefixedIdentifier_notPrefixed() {
- Token following = _skip("skipPrefixedIdentifier", "a +");
+ createParser('a +');
+ Token following = parser.skipPrefixedIdentifier(parser.currentToken);
expect(following, isNotNull);
expect(following.type, TokenType.PLUS);
}
void test_skipPrefixedIdentifier_prefixed() {
- Token following = _skip("skipPrefixedIdentifier", "a.b +");
+ createParser('a.b +');
+ Token following = parser.skipPrefixedIdentifier(parser.currentToken);
expect(following, isNotNull);
expect(following.type, TokenType.PLUS);
}
void test_skipReturnType_invalid() {
- Token following = _skip("skipReturnType", "+");
+ createParser('+');
+ Token following = parser.skipReturnType(parser.currentToken);
expect(following, isNull);
}
void test_skipReturnType_type() {
- Token following = _skip("skipReturnType", "C +");
+ createParser('C +');
+ Token following = parser.skipReturnType(parser.currentToken);
expect(following, isNotNull);
expect(following.type, TokenType.PLUS);
}
void test_skipReturnType_void() {
- Token following = _skip("skipReturnType", "void +");
+ createParser('void +');
+ Token following = parser.skipReturnType(parser.currentToken);
expect(following, isNotNull);
expect(following.type, TokenType.PLUS);
}
void test_skipSimpleIdentifier_identifier() {
- Token following = _skip("skipSimpleIdentifier", "i +");
+ createParser('i +');
+ Token following = parser.skipSimpleIdentifier(parser.currentToken);
expect(following, isNotNull);
expect(following.type, TokenType.PLUS);
}
void test_skipSimpleIdentifier_invalid() {
- Token following = _skip("skipSimpleIdentifier", "9 +");
+ createParser('9 +');
+ Token following = parser.skipSimpleIdentifier(parser.currentToken);
expect(following, isNull);
}
void test_skipSimpleIdentifier_pseudoKeyword() {
- Token following = _skip("skipSimpleIdentifier", "as +");
+ createParser('as +');
+ Token following = parser.skipSimpleIdentifier(parser.currentToken);
expect(following, isNotNull);
expect(following.type, TokenType.PLUS);
}
void test_skipStringLiteral_adjacent() {
- Token following = _skip("skipStringLiteral", "'a' 'b' +");
+ createParser("'a' 'b' +");
+ Token following = parser.skipStringLiteral(parser.currentToken);
expect(following, isNotNull);
expect(following.type, TokenType.PLUS);
}
void test_skipStringLiteral_interpolated() {
- Token following = _skip("skipStringLiteral", "'a\${b}c' +");
+ createParser("'a\${b}c' +");
+ Token following = parser.skipStringLiteral(parser.currentToken);
expect(following, isNotNull);
expect(following.type, TokenType.PLUS);
}
void test_skipStringLiteral_invalid() {
- Token following = _skip("skipStringLiteral", "a");
+ createParser('a');
+ Token following = parser.skipStringLiteral(parser.currentToken);
expect(following, isNull);
}
void test_skipStringLiteral_single() {
- Token following = _skip("skipStringLiteral", "'a' +");
+ createParser("'a' +");
+ Token following = parser.skipStringLiteral(parser.currentToken);
expect(following, isNotNull);
expect(following.type, TokenType.PLUS);
}
void test_skipTypeArgumentList_invalid() {
- Token following = _skip("skipTypeArgumentList", "+");
+ createParser('+');
+ Token following = parser.skipTypeArgumentList(parser.currentToken);
expect(following, isNull);
}
void test_skipTypeArgumentList_multiple() {
- Token following = _skip("skipTypeArgumentList", "<E, F, G> +");
+ createParser('<E, F, G> +');
+ Token following = parser.skipTypeArgumentList(parser.currentToken);
expect(following, isNotNull);
expect(following.type, TokenType.PLUS);
}
void test_skipTypeArgumentList_single() {
- Token following = _skip("skipTypeArgumentList", "<E> +");
+ createParser('<E> +');
+ Token following = parser.skipTypeArgumentList(parser.currentToken);
expect(following, isNotNull);
expect(following.type, TokenType.PLUS);
}
void test_skipTypeName_invalid() {
- Token following = _skip("skipTypeName", "+");
+ createParser('+');
+ Token following = parser.skipTypeName(parser.currentToken);
expect(following, isNull);
}
void test_skipTypeName_parameterized() {
- Token following = _skip("skipTypeName", "C<E<F<G>>> +");
+ createParser('C<E<F<G>>> +');
+ Token following = parser.skipTypeName(parser.currentToken);
expect(following, isNotNull);
expect(following.type, TokenType.PLUS);
}
void test_skipTypeName_simple() {
- Token following = _skip("skipTypeName", "C +");
+ createParser('C +');
+ Token following = parser.skipTypeName(parser.currentToken);
expect(following, isNotNull);
expect(following.type, TokenType.PLUS);
}
@@ -10851,38 +12265,10 @@
* @throws Exception if the method could not be invoked or throws an exception
*/
String _computeStringValue(String lexeme, bool first, bool last) {
- AnalysisErrorListener listener =
- new AnalysisErrorListener_SimpleParserTest_computeStringValue();
- Parser parser = new Parser(null, listener);
- return invokeParserMethodImpl(
- parser, "computeStringValue", <Object>[lexeme, first, last], null)
- as String;
- }
-
- /**
- * Invoke the method [Parser.createSyntheticIdentifier] with the parser set to the token
- * stream produced by scanning the given source.
- *
- * @param source the source to be scanned to produce the token stream being tested
- * @return the result of invoking the method
- * @throws Exception if the method could not be invoked or throws an exception
- */
- SimpleIdentifier _createSyntheticIdentifier() {
- GatheringErrorListener listener = new GatheringErrorListener();
- return invokeParserMethod2("createSyntheticIdentifier", "", listener);
- }
-
- /**
- * Invoke the method [Parser.createSyntheticIdentifier] with the parser set to the token
- * stream produced by scanning the given source.
- *
- * @param source the source to be scanned to produce the token stream being tested
- * @return the result of invoking the method
- * @throws Exception if the method could not be invoked or throws an exception
- */
- SimpleStringLiteral _createSyntheticStringLiteral() {
- GatheringErrorListener listener = new GatheringErrorListener();
- return invokeParserMethod2("createSyntheticStringLiteral", "", listener);
+ createParser('');
+ String value = parser.computeStringValue(lexeme, first, last);
+ listener.assertNoErrors();
+ return value;
}
void _expectDottedName(DottedName name, List<String> expectedComponents) {
@@ -10905,9 +12291,10 @@
* @throws Exception if the method could not be invoked or throws an exception
*/
bool _isFunctionDeclaration(String source) {
- GatheringErrorListener listener = new GatheringErrorListener();
- return invokeParserMethod2("isFunctionDeclaration", source, listener)
- as bool;
+ createParser(source);
+ bool result = parser.isFunctionDeclaration();
+ expectNotNullIfNoErrors(result);
+ return result;
}
/**
@@ -10919,20 +12306,8 @@
* @throws Exception if the method could not be invoked or throws an exception
*/
bool _isFunctionExpression(String source) {
- GatheringErrorListener listener = new GatheringErrorListener();
- //
- // Scan the source.
- //
- Scanner scanner =
- new Scanner(null, new CharSequenceReader(source), listener);
- Token tokenStream = scanner.tokenize();
- //
- // Parse the source.
- //
- Parser parser = new Parser(null, listener);
- return invokeParserMethodImpl(
- parser, "isFunctionExpression", <Object>[tokenStream], tokenStream)
- as bool;
+ createParser(source);
+ return parser.isFunctionExpression(parser.currentToken);
}
/**
@@ -10944,9 +12319,10 @@
* @throws Exception if the method could not be invoked or throws an exception
*/
bool _isInitializedVariableDeclaration(String source) {
- GatheringErrorListener listener = new GatheringErrorListener();
- return invokeParserMethod2(
- "isInitializedVariableDeclaration", source, listener) as bool;
+ createParser(source);
+ bool result = parser.isInitializedVariableDeclaration();
+ expectNotNullIfNoErrors(result);
+ return result;
}
/**
@@ -10958,8 +12334,10 @@
* @throws Exception if the method could not be invoked or throws an exception
*/
bool _isSwitchMember(String source) {
- GatheringErrorListener listener = new GatheringErrorListener();
- return invokeParserMethod2("isSwitchMember", source, listener) as bool;
+ createParser(source);
+ bool result = parser.isSwitchMember();
+ expectNotNullIfNoErrors(result);
+ return result;
}
/**
@@ -10973,42 +12351,11 @@
*/
CompilationUnit _parseDirectives(String source,
[List<ErrorCode> errorCodes = ErrorCode.EMPTY_LIST]) {
- GatheringErrorListener listener = new GatheringErrorListener();
- Scanner scanner =
- new Scanner(null, new CharSequenceReader(source), listener);
- listener.setLineInfo(new TestSource(), scanner.lineStarts);
- Token token = scanner.tokenize();
- Parser parser = new Parser(null, listener);
- CompilationUnit unit = parser.parseDirectives(token);
+ createParser(source);
+ CompilationUnit unit = parser.parseDirectives2();
expect(unit, isNotNull);
expect(unit.declarations, hasLength(0));
listener.assertErrorsWithCodes(errorCodes);
return unit;
}
-
- /**
- * Invoke a "skip" method in [Parser]. The method is assumed to take a token as it's
- * parameter and is given the first token in the scanned source.
- *
- * @param methodName the name of the method that should be invoked
- * @param source the source to be processed by the method
- * @return the result of invoking the method
- * @throws Exception if the method could not be invoked or throws an exception
- * @throws AssertionFailedError if the result is `null`
- */
- Token _skip(String methodName, String source) {
- GatheringErrorListener listener = new GatheringErrorListener();
- //
- // Scan the source.
- //
- Scanner scanner =
- new Scanner(null, new CharSequenceReader(source), listener);
- Token tokenStream = scanner.tokenize();
- //
- // Parse the source.
- //
- Parser parser = new Parser(null, listener);
- return invokeParserMethodImpl(
- parser, methodName, <Object>[tokenStream], tokenStream) as Token;
- }
}
diff --git a/pkg/analyzer/test/generated/resolver_test.dart b/pkg/analyzer/test/generated/resolver_test.dart
index db8f4cf..6c089fa 100644
--- a/pkg/analyzer/test/generated/resolver_test.dart
+++ b/pkg/analyzer/test/generated/resolver_test.dart
@@ -15,8 +15,8 @@
import 'package:analyzer/src/context/context.dart';
import 'package:analyzer/src/dart/element/element.dart';
import 'package:analyzer/src/dart/element/type.dart';
+import 'package:analyzer/src/error/codes.dart';
import 'package:analyzer/src/generated/engine.dart';
-import 'package:analyzer/src/generated/error.dart';
import 'package:analyzer/src/generated/parser.dart' show ParserErrorCode;
import 'package:analyzer/src/generated/resolver.dart';
import 'package:analyzer/src/generated/source_io.dart';
diff --git a/pkg/analyzer/test/generated/resolver_test_case.dart b/pkg/analyzer/test/generated/resolver_test_case.dart
index 4dfa5c7..1b7f5e2 100644
--- a/pkg/analyzer/test/generated/resolver_test_case.dart
+++ b/pkg/analyzer/test/generated/resolver_test_case.dart
@@ -8,11 +8,12 @@
import 'package:analyzer/dart/ast/visitor.dart';
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/type.dart';
+import 'package:analyzer/error/error.dart';
import 'package:analyzer/file_system/physical_file_system.dart';
import 'package:analyzer/src/dart/element/element.dart';
import 'package:analyzer/src/dart/element/type.dart';
+import 'package:analyzer/src/error/codes.dart';
import 'package:analyzer/src/generated/engine.dart';
-import 'package:analyzer/src/generated/error.dart';
import 'package:analyzer/src/generated/java_engine.dart';
import 'package:analyzer/src/generated/resolver.dart';
import 'package:analyzer/src/generated/source_io.dart';
diff --git a/pkg/analyzer/test/generated/scanner_test.dart b/pkg/analyzer/test/generated/scanner_test.dart
index b1c0547..3937ce8 100644
--- a/pkg/analyzer/test/generated/scanner_test.dart
+++ b/pkg/analyzer/test/generated/scanner_test.dart
@@ -5,10 +5,11 @@
library analyzer.test.generated.scanner_test;
import 'package:analyzer/dart/ast/token.dart';
+import 'package:analyzer/error/error.dart';
+import 'package:analyzer/error/listener.dart';
import 'package:analyzer/src/dart/ast/token.dart';
import 'package:analyzer/src/dart/scanner/reader.dart';
import 'package:analyzer/src/dart/scanner/scanner.dart';
-import 'package:analyzer/src/generated/error.dart';
import 'package:analyzer/src/generated/source.dart';
import 'package:test_reflective_loader/test_reflective_loader.dart';
import 'package:unittest/unittest.dart';
diff --git a/pkg/analyzer/test/generated/simple_resolver_test.dart b/pkg/analyzer/test/generated/simple_resolver_test.dart
index 9431dea..13a0766 100644
--- a/pkg/analyzer/test/generated/simple_resolver_test.dart
+++ b/pkg/analyzer/test/generated/simple_resolver_test.dart
@@ -9,8 +9,8 @@
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/type.dart';
import 'package:analyzer/exception/exception.dart';
+import 'package:analyzer/src/error/codes.dart';
import 'package:analyzer/src/generated/engine.dart';
-import 'package:analyzer/src/generated/error.dart';
import 'package:analyzer/src/generated/source_io.dart';
import 'package:test_reflective_loader/test_reflective_loader.dart';
import 'package:unittest/unittest.dart';
diff --git a/pkg/analyzer/test/generated/static_type_analyzer_test.dart b/pkg/analyzer/test/generated/static_type_analyzer_test.dart
index 2fc3fc5..60854a9 100644
--- a/pkg/analyzer/test/generated/static_type_analyzer_test.dart
+++ b/pkg/analyzer/test/generated/static_type_analyzer_test.dart
@@ -1100,7 +1100,10 @@
Identifier identifier = AstFactory.identifier3('a');
Expression node = AstFactory.listLiteral([identifier]);
DartType resultType = _analyze(node);
- expect(resultType, isNull);
+ _assertType2(
+ _typeProvider.listType
+ .instantiate(<DartType>[_typeProvider.dynamicType]),
+ resultType);
_listener.assertNoErrors();
}
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 14e3c4a..858d10a 100644
--- a/pkg/analyzer/test/generated/static_type_warning_code_test.dart
+++ b/pkg/analyzer/test/generated/static_type_warning_code_test.dart
@@ -4,8 +4,9 @@
library analyzer.test.generated.static_type_warning_code_test;
+import 'package:analyzer/error/error.dart';
+import 'package:analyzer/src/error/codes.dart';
import 'package:analyzer/src/generated/engine.dart';
-import 'package:analyzer/src/generated/error.dart';
import 'package:analyzer/src/generated/java_core.dart' show formatList;
import 'package:analyzer/src/generated/source_io.dart';
import 'package:test_reflective_loader/test_reflective_loader.dart';
diff --git a/pkg/analyzer/test/generated/static_warning_code_test.dart b/pkg/analyzer/test/generated/static_warning_code_test.dart
index 1f5b54d..3acd138 100644
--- a/pkg/analyzer/test/generated/static_warning_code_test.dart
+++ b/pkg/analyzer/test/generated/static_warning_code_test.dart
@@ -4,8 +4,9 @@
library analyzer.test.generated.static_warning_code_test;
+import 'package:analyzer/error/error.dart';
+import 'package:analyzer/src/error/codes.dart';
import 'package:analyzer/src/generated/engine.dart';
-import 'package:analyzer/src/generated/error.dart';
import 'package:analyzer/src/generated/source_io.dart';
import 'package:test_reflective_loader/test_reflective_loader.dart';
import 'package:unittest/unittest.dart';
diff --git a/pkg/analyzer/test/generated/strong_mode_test.dart b/pkg/analyzer/test/generated/strong_mode_test.dart
index 877be1e..a16ee2e 100644
--- a/pkg/analyzer/test/generated/strong_mode_test.dart
+++ b/pkg/analyzer/test/generated/strong_mode_test.dart
@@ -8,8 +8,8 @@
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/type.dart';
import 'package:analyzer/src/dart/element/element.dart';
+import 'package:analyzer/src/error/codes.dart';
import 'package:analyzer/src/generated/engine.dart';
-import 'package:analyzer/src/generated/error.dart';
import 'package:analyzer/src/generated/source_io.dart';
import 'package:test_reflective_loader/test_reflective_loader.dart';
import 'package:unittest/unittest.dart';
@@ -1450,6 +1450,12 @@
checkBody("D");
}
+ void test_genericFunction_upwardsAndDownwards() {
+ // Regression tests for https://github.com/dart-lang/sdk/issues/27151.
+ resolveTestUnit(r'List<num> x = [1, 2];');
+ expectInitializerType('x', 'List<int>');
+ }
+
void test_genericMethod() {
resolveTestUnit(r'''
class C<E> {
diff --git a/pkg/analyzer/test/generated/test_support.dart b/pkg/analyzer/test/generated/test_support.dart
index caf5f36..7b36770 100644
--- a/pkg/analyzer/test/generated/test_support.dart
+++ b/pkg/analyzer/test/generated/test_support.dart
@@ -9,10 +9,11 @@
import 'package:analyzer/dart/ast/ast.dart' show AstNode, SimpleIdentifier;
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/type.dart';
+import 'package:analyzer/error/error.dart';
+import 'package:analyzer/error/listener.dart';
import 'package:analyzer/exception/exception.dart';
import 'package:analyzer/src/dart/ast/utilities.dart';
import 'package:analyzer/src/generated/engine.dart';
-import 'package:analyzer/src/generated/error.dart';
import 'package:analyzer/src/generated/java_engine.dart';
import 'package:analyzer/src/generated/source.dart';
import 'package:plugin/manager.dart';
@@ -415,17 +416,16 @@
}
/**
- * Return `true` if the two errors are equivalent.
- *
- * @param firstError the first error being compared
- * @param secondError the second error being compared
- * @return `true` if the two errors are equivalent
+ * Return `true` if the [actualError] matches the [expectedError].
*/
- bool _equalErrors(AnalysisError firstError, AnalysisError secondError) =>
- identical(firstError.errorCode, secondError.errorCode) &&
- firstError.offset == secondError.offset &&
- firstError.length == secondError.length &&
- _equalSources(firstError.source, secondError.source);
+ bool _equalErrors(AnalysisError expectedError, AnalysisError actualError) {
+ Source expectedSource = expectedError.source;
+ return identical(expectedError.errorCode, actualError.errorCode) &&
+ expectedError.offset == actualError.offset &&
+ expectedError.length == actualError.length &&
+ (expectedSource == null ||
+ _equalSources(expectedSource, actualError.source));
+ }
/**
* Return `true` if the two sources are equivalent.
diff --git a/pkg/analyzer/test/generated/type_system_test.dart b/pkg/analyzer/test/generated/type_system_test.dart
index 909dfdc..af08bb4 100644
--- a/pkg/analyzer/test/generated/type_system_test.dart
+++ b/pkg/analyzer/test/generated/type_system_test.dart
@@ -1124,8 +1124,13 @@
List<DartType> _inferCall(FunctionTypeImpl ft, List<DartType> arguments,
[DartType returnType]) {
- FunctionType inferred = typeSystem.inferGenericFunctionCall(typeProvider,
- ft, ft.parameters.map((p) => p.type).toList(), arguments, returnType);
+ FunctionType inferred = typeSystem.inferGenericFunctionCall(
+ typeProvider,
+ ft,
+ ft.parameters.map((p) => p.type).toList(),
+ arguments,
+ ft.returnType,
+ returnType);
return inferred?.typeArguments;
}
}
diff --git a/pkg/analyzer/test/source/embedder_test.dart b/pkg/analyzer/test/source/embedder_test.dart
index 8773f09..fb3df17 100644
--- a/pkg/analyzer/test/source/embedder_test.dart
+++ b/pkg/analyzer/test/source/embedder_test.dart
@@ -7,6 +7,7 @@
import 'dart:core';
+import 'package:analyzer/file_system/file_system.dart';
import 'package:analyzer/source/embedder.dart';
import 'package:analyzer/src/generated/sdk.dart';
import 'package:analyzer/src/generated/source.dart';
@@ -26,7 +27,7 @@
class DartUriResolverTest extends EmbedderRelatedTest {
void test_embedderYaml() {
EmbedderYamlLocator locator = new EmbedderYamlLocator({
- 'fox': [pathTranslator.getResource(foxLib)]
+ 'fox': <Folder>[pathTranslator.getResource(foxLib)]
});
EmbedderSdk sdk = new EmbedderSdk(locator.embedderYamls);
DartUriResolver resolver = new DartUriResolver(sdk);
@@ -50,7 +51,7 @@
class EmbedderSdkTest extends EmbedderRelatedTest {
void test_creation() {
EmbedderYamlLocator locator = new EmbedderYamlLocator({
- 'fox': [pathTranslator.getResource(foxLib)]
+ 'fox': <Folder>[pathTranslator.getResource(foxLib)]
});
EmbedderSdk sdk = new EmbedderSdk(locator.embedderYamls);
@@ -59,7 +60,7 @@
void test_fromFileUri() {
EmbedderYamlLocator locator = new EmbedderYamlLocator({
- 'fox': [pathTranslator.getResource(foxLib)]
+ 'fox': <Folder>[pathTranslator.getResource(foxLib)]
});
EmbedderSdk sdk = new EmbedderSdk(locator.embedderYamls);
@@ -78,7 +79,7 @@
void test_getSdkLibrary() {
EmbedderYamlLocator locator = new EmbedderYamlLocator({
- 'fox': [pathTranslator.getResource(foxLib)]
+ 'fox': <Folder>[pathTranslator.getResource(foxLib)]
});
EmbedderSdk sdk = new EmbedderSdk(locator.embedderYamls);
@@ -90,7 +91,7 @@
void test_mapDartUri() {
EmbedderYamlLocator locator = new EmbedderYamlLocator({
- 'fox': [pathTranslator.getResource(foxLib)]
+ 'fox': <Folder>[pathTranslator.getResource(foxLib)]
});
EmbedderSdk sdk = new EmbedderSdk(locator.embedderYamls);
@@ -112,7 +113,7 @@
class EmbedderUriResolverTest extends EmbedderRelatedTest {
void test_embedderYaml() {
var locator = new EmbedderYamlLocator({
- 'fox': [pathTranslator.getResource(foxLib)]
+ 'fox': <Folder>[pathTranslator.getResource(foxLib)]
});
var resolver = new EmbedderUriResolver(locator.embedderYamls);
@@ -139,7 +140,7 @@
void test_restoreAbsolute() {
var locator = new EmbedderYamlLocator({
- 'fox': [pathTranslator.getResource(foxLib)]
+ 'fox': <Folder>[pathTranslator.getResource(foxLib)]
});
var resolver = new EmbedderUriResolver(locator.embedderYamls);
diff --git a/pkg/analyzer/test/source/error_processor_test.dart b/pkg/analyzer/test/source/error_processor_test.dart
index ca088967..c170fc9 100644
--- a/pkg/analyzer/test/source/error_processor_test.dart
+++ b/pkg/analyzer/test/source/error_processor_test.dart
@@ -4,11 +4,12 @@
library analyzer.test.source.error_processor;
+import 'package:analyzer/error/error.dart';
import 'package:analyzer/source/analysis_options_provider.dart';
import 'package:analyzer/source/error_processor.dart';
import 'package:analyzer/src/context/context.dart';
+import 'package:analyzer/src/error/codes.dart';
import 'package:analyzer/src/generated/engine.dart';
-import 'package:analyzer/src/generated/error.dart';
import 'package:analyzer/src/task/options.dart';
import 'package:plugin/manager.dart';
import 'package:plugin/plugin.dart';
diff --git a/pkg/analyzer/test/source/package_map_resolver_test.dart b/pkg/analyzer/test/source/package_map_resolver_test.dart
index 7cdcabc..bcdd5be 100644
--- a/pkg/analyzer/test/source/package_map_resolver_test.dart
+++ b/pkg/analyzer/test/source/package_map_resolver_test.dart
@@ -62,7 +62,7 @@
provider.newFile(pkgFileB, 'library lib_b');
PackageMapUriResolver resolver =
new PackageMapUriResolver(provider, <String, List<Folder>>{
- 'pkg': [
+ 'pkg': <Folder>[
provider.getResource('/part1/lib/'),
provider.getResource('/part2/lib/')
]
@@ -99,8 +99,8 @@
provider.newFile(pkgFileB, 'library lib_b;');
PackageMapUriResolver resolver =
new PackageMapUriResolver(provider, <String, List<Folder>>{
- 'pkgA': [provider.getResource('/pkgA/lib/')],
- 'pkgB': [provider.getResource('/pkgB/lib/')]
+ 'pkgA': <Folder>[provider.getResource('/pkgA/lib/')],
+ 'pkgB': <Folder>[provider.getResource('/pkgB/lib/')]
});
{
Uri uri = Uri.parse('package:pkgA/libA.dart');
@@ -158,8 +158,8 @@
provider.newFile(pkgFileB, 'library lib_b;');
PackageMapUriResolver resolver =
new PackageMapUriResolver(provider, <String, List<Folder>>{
- 'pkgA': [provider.getResource('/pkgA/lib/')],
- 'pkgB': [provider.getResource('/pkgB/lib/')]
+ 'pkgA': <Folder>[provider.getResource('/pkgA/lib/')],
+ 'pkgB': <Folder>[provider.getResource('/pkgB/lib/')]
});
{
Source source = _createFileSource('/pkgA/lib/libA.dart');
@@ -187,7 +187,7 @@
provider.newFile(file2, 'library bar');
PackageMapUriResolver resolver =
new PackageMapUriResolver(provider, <String, List<Folder>>{
- 'foo': [
+ 'foo': <Folder>[
provider.getResource('/foo1/lib'),
provider.getResource('/foo2/lib')
]
@@ -211,11 +211,11 @@
provider.newFile(file2, 'library lib');
PackageMapUriResolver resolver =
new PackageMapUriResolver(provider, <String, List<Folder>>{
- 'pkg1': [
+ 'pkg1': <Folder>[
provider.getResource('/foo1'),
provider.getResource('/foo2/bar2')
],
- 'pkg2': [
+ 'pkg2': <Folder>[
provider.getResource('/foo1/bar1'),
provider.getResource('/foo2')
]
diff --git a/pkg/analyzer/test/source/sdk_ext_test.dart b/pkg/analyzer/test/source/sdk_ext_test.dart
index c44ca5d..7c6b19f 100644
--- a/pkg/analyzer/test/source/sdk_ext_test.dart
+++ b/pkg/analyzer/test/source/sdk_ext_test.dart
@@ -4,6 +4,7 @@
library analyzer.test.source.sdk_ext_test;
+import 'package:analyzer/file_system/file_system.dart';
import 'package:analyzer/file_system/memory_file_system.dart';
import 'package:analyzer/source/sdk_ext.dart';
import 'package:test_reflective_loader/test_reflective_loader.dart';
@@ -44,7 +45,7 @@
test_create_noSdkExtPackageMap() {
var resolver = new SdkExtUriResolver({
- 'fox': [resourceProvider.getResource('/empty')]
+ 'fox': <Folder>[resourceProvider.getResource('/empty')]
});
expect(resolver.length, equals(0));
}
@@ -56,7 +57,7 @@
test_create_sdkExtPackageMap() {
var resolver = new SdkExtUriResolver({
- 'fox': [resourceProvider.getResource('/tmp')]
+ 'fox': <Folder>[resourceProvider.getResource('/tmp')]
});
// We have four mappings.
expect(resolver.length, equals(4));
@@ -69,7 +70,7 @@
test_restoreAbsolute() {
var resolver = new SdkExtUriResolver({
- 'fox': [resourceProvider.getResource('/tmp')]
+ 'fox': <Folder>[resourceProvider.getResource('/tmp')]
});
var source = resolver.resolveAbsolute(Uri.parse('dart:fox'));
expect(source, isNotNull);
diff --git a/pkg/analyzer/test/src/abstract_single_unit.dart b/pkg/analyzer/test/src/abstract_single_unit.dart
index 787ac21..428948e 100644
--- a/pkg/analyzer/test/src/abstract_single_unit.dart
+++ b/pkg/analyzer/test/src/abstract_single_unit.dart
@@ -6,8 +6,8 @@
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/element/element.dart';
+import 'package:analyzer/error/error.dart';
import 'package:analyzer/src/dart/ast/utilities.dart';
-import 'package:analyzer/src/generated/error.dart';
import 'package:analyzer/src/generated/java_engine.dart';
import 'package:analyzer/src/generated/source.dart';
import 'package:unittest/unittest.dart';
diff --git a/pkg/analyzer/test/src/context/builder_test.dart b/pkg/analyzer/test/src/context/builder_test.dart
index 5fae924..5f04b4f 100644
--- a/pkg/analyzer/test/src/context/builder_test.dart
+++ b/pkg/analyzer/test/src/context/builder_test.dart
@@ -674,7 +674,7 @@
class EmbedderYamlLocatorTest extends EmbedderRelatedTest {
void test_empty() {
EmbedderYamlLocator locator = new EmbedderYamlLocator({
- 'fox': [pathTranslator.getResource(emptyPath)]
+ 'fox': <Folder>[pathTranslator.getResource(emptyPath)]
});
expect(locator.embedderYamls, hasLength(0));
}
@@ -687,7 +687,7 @@
void test_valid() {
EmbedderYamlLocator locator = new EmbedderYamlLocator({
- 'fox': [pathTranslator.getResource(foxLib)]
+ 'fox': <Folder>[pathTranslator.getResource(foxLib)]
});
expect(locator.embedderYamls, hasLength(1));
}
diff --git a/pkg/analyzer/test/src/context/context_test.dart b/pkg/analyzer/test/src/context/context_test.dart
index 490ba81..7da5f3f 100644
--- a/pkg/analyzer/test/src/context/context_test.dart
+++ b/pkg/analyzer/test/src/context/context_test.dart
@@ -11,6 +11,7 @@
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/type.dart';
import 'package:analyzer/dart/element/visitor.dart';
+import 'package:analyzer/error/error.dart';
import 'package:analyzer/exception/exception.dart';
import 'package:analyzer/file_system/file_system.dart';
import 'package:analyzer/file_system/memory_file_system.dart';
@@ -21,7 +22,6 @@
import 'package:analyzer/src/dart/element/element.dart';
import 'package:analyzer/src/dart/scanner/scanner.dart';
import 'package:analyzer/src/generated/engine.dart';
-import 'package:analyzer/src/generated/error.dart';
import 'package:analyzer/src/generated/resolver.dart';
import 'package:analyzer/src/generated/source.dart';
import 'package:analyzer/src/generated/utilities_collection.dart';
@@ -1942,7 +1942,7 @@
CompilationUnit unit = context.computeResult(scripts[0], PARSED_UNIT);
ImportDirective importNode = unit.directives[0] as ImportDirective;
expect(importNode.uriContent, isNotNull);
- expect(importNode.source, libSource);
+ expect(importNode.uriSource, libSource);
}
void test_performAnalysisTask_addPart() {
diff --git a/pkg/analyzer/test/src/context/mock_sdk.dart b/pkg/analyzer/test/src/context/mock_sdk.dart
index 91cc635..91b4e5e 100644
--- a/pkg/analyzer/test/src/context/mock_sdk.dart
+++ b/pkg/analyzer/test/src/context/mock_sdk.dart
@@ -4,7 +4,6 @@
library analyzer.test.src.context.mock_sdk;
-import 'package:analyzer/dart/element/element.dart' show LibraryElement;
import 'package:analyzer/file_system/file_system.dart' as resource;
import 'package:analyzer/file_system/memory_file_system.dart' as resource;
import 'package:analyzer/src/context/cache.dart';
@@ -13,8 +12,7 @@
import 'package:analyzer/src/generated/sdk.dart';
import 'package:analyzer/src/generated/source.dart';
import 'package:analyzer/src/summary/idl.dart' show PackageBundle;
-import 'package:analyzer/src/summary/summarize_elements.dart'
- show PackageBundleAssembler;
+import 'package:analyzer/src/summary/summary_file_builder.dart';
const String librariesContent = r'''
const Map<String, LibraryInfo> libraries = const {
@@ -248,12 +246,10 @@
void print(Object object) {}
-const proxy = const _Proxy();
class _Proxy { const _Proxy(); }
+const Object proxy = const _Proxy();
-class _Override {
- const _Override();
-}
+class _Override { const _Override(); }
const Object override = const _Override();
''');
@@ -409,14 +405,12 @@
@override
PackageBundle getLinkedBundle() {
if (_bundle == null) {
- PackageBundleAssembler assembler = new PackageBundleAssembler();
- for (SdkLibrary sdkLibrary in sdkLibraries) {
- String uriStr = sdkLibrary.shortName;
- Source source = mapDartUri(uriStr);
- LibraryElement libraryElement = context.computeLibraryElement(source);
- assembler.serializeLibraryElement(libraryElement);
- }
- List<int> bytes = assembler.assemble().toBuffer();
+ List<Source> librarySources = sdkLibraries
+ .map((SdkLibrary library) => mapDartUri(library.shortName))
+ .toList();
+ List<int> bytes = new SummaryBuilder(
+ librarySources, context, context.analysisOptions.strongMode)
+ .build();
_bundle = new PackageBundle.fromBuffer(bytes);
}
return _bundle;
diff --git a/pkg/analyzer/test/src/dart/ast/utilities_test.dart b/pkg/analyzer/test/src/dart/ast/utilities_test.dart
index d629a83..a48fb6e 100644
--- a/pkg/analyzer/test/src/dart/ast/utilities_test.dart
+++ b/pkg/analyzer/test/src/dart/ast/utilities_test.dart
@@ -10,6 +10,7 @@
import 'package:analyzer/dart/element/type.dart';
import 'package:analyzer/src/dart/ast/utilities.dart';
import 'package:analyzer/src/dart/element/element.dart';
+import 'package:analyzer/src/generated/java_core.dart';
import 'package:analyzer/src/generated/java_engine.dart' show Predicate;
import 'package:analyzer/src/generated/java_engine.dart';
import 'package:analyzer/src/generated/testing/ast_factory.dart';
@@ -3340,8 +3341,8 @@
* @throws AFE if the visitor does not produce the expected source for the given node
*/
void _assertSource(String expectedSource, AstNode node) {
- StringBuffer buffer = new StringBuffer();
- node.accept(new ToSourceVisitor(buffer));
- expect(buffer.toString(), expectedSource);
+ PrintStringWriter writer = new PrintStringWriter();
+ node.accept(new ToSourceVisitor(writer));
+ expect(writer.toString(), expectedSource);
}
}
diff --git a/pkg/analyzer/test/src/dart/constant/evaluation_test.dart b/pkg/analyzer/test/src/dart/constant/evaluation_test.dart
index 4c21cec..9de8247 100644
--- a/pkg/analyzer/test/src/dart/constant/evaluation_test.dart
+++ b/pkg/analyzer/test/src/dart/constant/evaluation_test.dart
@@ -8,10 +8,12 @@
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/ast/token.dart';
import 'package:analyzer/dart/element/element.dart';
+import 'package:analyzer/error/error.dart';
+import 'package:analyzer/error/listener.dart';
import 'package:analyzer/src/dart/element/element.dart';
+import 'package:analyzer/src/error/codes.dart';
import 'package:analyzer/src/generated/constant.dart';
import 'package:analyzer/src/generated/engine.dart';
-import 'package:analyzer/src/generated/error.dart';
import 'package:analyzer/src/generated/resolver.dart';
import 'package:analyzer/src/generated/source.dart';
import 'package:analyzer/src/generated/source_io.dart';
diff --git a/pkg/analyzer/test/src/dart/sdk/sdk_test.dart b/pkg/analyzer/test/src/dart/sdk/sdk_test.dart
index e6ab788..7444827 100644
--- a/pkg/analyzer/test/src/dart/sdk/sdk_test.dart
+++ b/pkg/analyzer/test/src/dart/sdk/sdk_test.dart
@@ -33,7 +33,7 @@
class EmbedderSdkTest extends EmbedderRelatedTest {
void test_creation() {
EmbedderYamlLocator locator = new EmbedderYamlLocator({
- 'fox': [pathTranslator.getResource(foxLib)]
+ 'fox': <Folder>[pathTranslator.getResource(foxLib)]
});
EmbedderSdk sdk = new EmbedderSdk(resourceProvider, locator.embedderYamls);
@@ -42,7 +42,7 @@
void test_fromFileUri() {
EmbedderYamlLocator locator = new EmbedderYamlLocator({
- 'fox': [pathTranslator.getResource(foxLib)]
+ 'fox': <Folder>[pathTranslator.getResource(foxLib)]
});
EmbedderSdk sdk = new EmbedderSdk(resourceProvider, locator.embedderYamls);
@@ -63,13 +63,14 @@
pathTranslator.newFileWithBytes(
'$foxPath/sdk.ds', new PackageBundleAssembler().assemble().toBuffer());
EmbedderYamlLocator locator = new EmbedderYamlLocator({
- 'fox': [pathTranslator.getResource(foxLib)]
+ 'fox': <Folder>[pathTranslator.getResource(foxLib)]
});
// No bundle for spec mode.
{
EmbedderSdk sdk =
new EmbedderSdk(resourceProvider, locator.embedderYamls);
sdk.analysisOptions = new AnalysisOptionsImpl()..strongMode = false;
+ sdk.useSummary = true;
expect(sdk.getLinkedBundle(), isNull);
}
// Has bundle for strong mode.
@@ -77,13 +78,22 @@
EmbedderSdk sdk =
new EmbedderSdk(resourceProvider, locator.embedderYamls);
sdk.analysisOptions = new AnalysisOptionsImpl()..strongMode = true;
+ sdk.useSummary = true;
expect(sdk.getLinkedBundle(), isNotNull);
}
+ // Don't use bundle if not enabled.
+ {
+ EmbedderSdk sdk =
+ new EmbedderSdk(resourceProvider, locator.embedderYamls);
+ sdk.analysisOptions = new AnalysisOptionsImpl()..strongMode = true;
+ sdk.useSummary = false;
+ expect(sdk.getLinkedBundle(), isNull);
+ }
}
void test_getLinkedBundle_noBundle() {
EmbedderYamlLocator locator = new EmbedderYamlLocator({
- 'fox': [pathTranslator.getResource(foxLib)]
+ 'fox': <Folder>[pathTranslator.getResource(foxLib)]
});
EmbedderSdk sdk = new EmbedderSdk(resourceProvider, locator.embedderYamls);
expect(sdk.getLinkedBundle(), isNull);
@@ -91,7 +101,7 @@
void test_getSdkLibrary() {
EmbedderYamlLocator locator = new EmbedderYamlLocator({
- 'fox': [pathTranslator.getResource(foxLib)]
+ 'fox': <Folder>[pathTranslator.getResource(foxLib)]
});
EmbedderSdk sdk = new EmbedderSdk(resourceProvider, locator.embedderYamls);
@@ -103,7 +113,7 @@
void test_mapDartUri() {
EmbedderYamlLocator locator = new EmbedderYamlLocator({
- 'fox': [pathTranslator.getResource(foxLib)]
+ 'fox': <Folder>[pathTranslator.getResource(foxLib)]
});
EmbedderSdk sdk = new EmbedderSdk(resourceProvider, locator.embedderYamls);
@@ -346,7 +356,7 @@
test_create_noSdkExtPackageMap() {
var resolver = new SdkExtensionFinder({
- 'fox': [resourceProvider.getResource('/empty')]
+ 'fox': <Folder>[resourceProvider.getResource('/empty')]
});
expect(resolver.urlMappings.length, equals(0));
}
@@ -358,7 +368,7 @@
test_create_sdkExtPackageMap() {
var resolver = new SdkExtensionFinder({
- 'fox': [resourceProvider.getResource('/tmp')]
+ 'fox': <Folder>[resourceProvider.getResource('/tmp')]
});
// We have four mappings.
Map<String, String> urlMappings = resolver.urlMappings;
diff --git a/pkg/analyzer/test/src/summary/incremental_cache_test.dart b/pkg/analyzer/test/src/summary/incremental_cache_test.dart
deleted file mode 100644
index b75162b..0000000
--- a/pkg/analyzer/test/src/summary/incremental_cache_test.dart
+++ /dev/null
@@ -1,297 +0,0 @@
-// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-import 'package:analyzer/dart/element/element.dart';
-import 'package:analyzer/src/generated/error.dart';
-import 'package:analyzer/src/generated/source.dart';
-import 'package:analyzer/src/summary/incremental_cache.dart';
-import 'package:test_reflective_loader/test_reflective_loader.dart';
-import 'package:unittest/unittest.dart';
-
-import '../../generated/test_support.dart';
-import '../abstract_single_unit.dart';
-
-main() {
- groupSep = ' | ';
- defineReflectiveTests(ComparePathsTest);
- defineReflectiveTests(IncrementalCacheTest);
-}
-
-@reflectiveTest
-class ComparePathsTest extends AbstractSingleUnitTest {
- void test_empty() {
- expect(comparePaths('', ''), 0);
- }
-
- void test_equal() {
- expect(comparePaths('abc', 'abc'), 0);
- }
-
- void test_longer_suffixAfter() {
- expect(comparePaths('aab', 'aa'), 1);
- }
-
- void test_longer_suffixBefore() {
- expect(comparePaths('aaa', 'ab'), -1);
- }
-
- void test_longer_suffixSame() {
- expect(comparePaths('aaa', 'aa'), 1);
- }
-
- void test_sameLength_before0() {
- expect(comparePaths('aaa', 'bbb'), -1);
- }
-
- void test_sameLength_before1() {
- expect(comparePaths('aaa', 'bba'), -1);
- }
-
- void test_sameLength_before2() {
- expect(comparePaths('aaa', 'bba'), -1);
- }
-
- void test_shorter_suffixAfter() {
- expect(comparePaths('ab', 'aaa'), 1);
- }
-
- void test_shorter_suffixBefore() {
- expect(comparePaths('aa', 'aab'), -1);
- }
-
- void test_shorter_suffixSame() {
- expect(comparePaths('aa', 'aaa'), -1);
- }
-}
-
-/**
- * TODO(scheglov) write more tests for invalidation.
- */
-@reflectiveTest
-class IncrementalCacheTest extends AbstractSingleUnitTest {
- _TestCacheStorage storage = new _TestCacheStorage();
- IncrementalCache cache;
-
- Source putLibrary(String path, String code) {
- Source source = addSource(path, code);
- LibraryElement libraryElement = context.computeLibraryElement(source);
- cache.putLibrary(libraryElement);
- return source;
- }
-
- void putTestLibrary(String code) {
- resolveTestUnit(code);
- cache.putLibrary(testLibraryElement);
- }
-
- @override
- void setUp() {
- super.setUp();
- cache = new IncrementalCache(storage, context, <int>[]);
- }
-
- void test_getLibraryClosureBundles_emptyCache() {
- resolveTestUnit('main() {}');
- // the cache is empty, no bundles
- List<LibraryBundleWithId> bundles =
- cache.getLibraryClosureBundles(testSource);
- expect(bundles, isNull);
- }
-
- void test_getLibraryClosureBundles_exportLib() {
- Source aSource = putLibrary('/a.dart', '');
- putTestLibrary(r'''
-import 'a.dart';
-main() {}
-''');
- List<LibraryBundleWithId> bundles =
- cache.getLibraryClosureBundles(testSource);
- expect(bundles, isNotNull);
- expect(_getBundleSources(bundles), [testSource, aSource].toSet());
- // remove the 'a.dart' bundle, 'test.dart' loading fails
- cache.clearInternalCaches();
- storage.map.remove(_findBundleForSource(bundles, aSource).id);
- expect(cache.getLibraryClosureBundles(testSource), isNull);
- }
-
- void test_getLibraryClosureBundles_importLib() {
- Source aSource = putLibrary('/a.dart', '');
- putTestLibrary(r'''
-import 'a.dart';
-main() {}
-''');
- List<LibraryBundleWithId> bundles =
- cache.getLibraryClosureBundles(testSource);
- expect(bundles, isNotNull);
- expect(_getBundleSources(bundles), [testSource, aSource].toSet());
- // remove the 'a.dart' bundle, 'test.dart' loading fails
- cache.clearInternalCaches();
- storage.map.remove(_findBundleForSource(bundles, aSource).id);
- expect(cache.getLibraryClosureBundles(testSource), isNull);
- }
-
- void test_getLibraryClosureBundles_importLib2() {
- Source aSource = putLibrary('/a.dart', '');
- Source bSource = putLibrary('/b.dart', "import 'a.dart';");
- putTestLibrary(r'''
-import 'b.dart';
-main() {}
-''');
- List<LibraryBundleWithId> bundles =
- cache.getLibraryClosureBundles(testSource);
- expect(bundles, isNotNull);
- expect(_getBundleSources(bundles), [testSource, aSource, bSource].toSet());
- // remove the 'a.dart' bundle, 'test.dart' loading fails
- cache.clearInternalCaches();
- storage.map.remove(_findBundleForSource(bundles, aSource).id);
- expect(cache.getLibraryClosureBundles(testSource), isNull);
- }
-
- void test_getLibraryClosureBundles_importSdk() {
- putTestLibrary(r'''
-import 'dart:async';
-main() {}
-''');
- List<LibraryBundleWithId> bundles =
- cache.getLibraryClosureBundles(testSource);
- expect(bundles, isNotNull);
- expect(_getBundleSources(bundles), [testSource].toSet());
- }
-
- void test_getLibraryClosureBundles_onlyLibrary() {
- putTestLibrary(r'''
-main() {}
-''');
- // the cache is empty, no bundles
- List<LibraryBundleWithId> bundles =
- cache.getLibraryClosureBundles(testSource);
- expect(bundles, isNotNull);
- }
-
- void test_getLibraryParts_hasParts() {
- Source part1Source = addSource('/part1.dart', r'part of test;');
- Source part2Source = addSource('/part2.dart', r'part of test;');
- putTestLibrary(r'''
-library test;
-part 'part1.dart';
-part 'part2.dart';
-''');
- expect(cache.getLibraryParts(testSource),
- unorderedEquals([part1Source, part2Source]));
- }
-
- void test_getLibraryParts_noParts() {
- putTestLibrary(r'''
-main() {}
-''');
- expect(cache.getLibraryParts(testSource), isEmpty);
- }
-
- void test_getSourceErrorsInLibrary_library() {
- verifyNoTestUnitErrors = false;
- putTestLibrary(r'''
-main() {
- int unusedVar = 42;
-}
-''');
- List<AnalysisError> computedErrors = context.computeErrors(testSource);
- cache.putSourceErrorsInLibrary(testSource, testSource, computedErrors);
- List<AnalysisError> readErrors =
- cache.getSourceErrorsInLibrary(testSource, testSource);
- new GatheringErrorListener()
- ..addAll(readErrors)
- ..assertErrors(computedErrors);
- }
-
- void test_getSourceErrorsInLibrary_part() {
- verifyNoTestUnitErrors = false;
- Source partSource = addSource(
- '/foo.dart',
- r'''
-main() {
- int unusedVar = 42;
-}
-''');
- putTestLibrary(r'''
-library lib;
-part 'foo.dart';
-''');
- List<AnalysisError> computedErrors = context.computeErrors(partSource);
- cache.putSourceErrorsInLibrary(testSource, partSource, computedErrors);
- List<AnalysisError> readErrors =
- cache.getSourceErrorsInLibrary(testSource, partSource);
- new GatheringErrorListener()
- ..addAll(readErrors)
- ..assertErrors(computedErrors);
- }
-
- void test_getSourceKind_library() {
- putTestLibrary(r'''
-main() {}
-''');
- expect(cache.getSourceKind(testSource), SourceKind.LIBRARY);
- }
-
- void test_getSourceKind_library_usedAsPart() {
- verifyNoTestUnitErrors = false;
- Source fooSource = addSource(
- '/foo.dart',
- r'''
-import 'dart:math';
-''');
- putTestLibrary(r'''
-part 'foo.dart';
-main() {}
-''');
- expect(cache.getSourceKind(testSource), SourceKind.LIBRARY);
- // not a part, but also not enough information to write it as a library
- expect(cache.getSourceKind(fooSource), isNull);
- }
-
- void test_getSourceKind_notCached() {
- resolveTestUnit(r'''
-main() {}
-''');
- expect(cache.getSourceKind(testSource), isNull);
- }
-
- void test_getSourceKind_part() {
- Source partSource = addSource('/foo.dart', 'part of lib;');
- putTestLibrary(r'''
-library lib;
-part 'foo.dart';
-''');
- expect(cache.getSourceKind(testSource), SourceKind.LIBRARY);
- expect(cache.getSourceKind(partSource), SourceKind.PART);
- }
-
- LibraryBundleWithId _findBundleForSource(
- List<LibraryBundleWithId> bundles, Source source) {
- return bundles.singleWhere((b) => b.source == source);
- }
-
- Set<Source> _getBundleSources(List<LibraryBundleWithId> bundles) {
- return bundles.map((b) => b.source).toSet();
- }
-}
-
-/**
- * A [Map] based [CacheStorage].
- */
-class _TestCacheStorage implements CacheStorage {
- final Map<String, List<int>> map = <String, List<int>>{};
-
- @override
- void compact() {}
-
- @override
- List<int> get(String key) {
- return map[key];
- }
-
- @override
- void put(String key, List<int> bytes) {
- map[key] = bytes;
- }
-}
diff --git a/pkg/analyzer/test/src/summary/linker_test.dart b/pkg/analyzer/test/src/summary/linker_test.dart
index d410a08..b6fdf2c 100644
--- a/pkg/analyzer/test/src/summary/linker_test.dart
+++ b/pkg/analyzer/test/src/summary/linker_test.dart
@@ -33,8 +33,10 @@
void createLinker(String text, {String path: '/test.dart'}) {
linkerInputs = createLinkerInputs(text, path: path);
- Map<String, LinkedLibraryBuilder> linkedLibraries =
- setupForLink(linkerInputs.linkedLibraries, linkerInputs.getUnit);
+ Map<String, LinkedLibraryBuilder> linkedLibraries = setupForLink(
+ linkerInputs.linkedLibraries,
+ linkerInputs.getUnit,
+ linkerInputs.getDeclaredVariable);
linker = new Linker(linkedLibraries, linkerInputs.getDependency,
linkerInputs.getUnit, true);
}
diff --git a/pkg/analyzer/test/src/summary/prelinker_test.dart b/pkg/analyzer/test/src/summary/prelinker_test.dart
index 925396b..89e0059 100644
--- a/pkg/analyzer/test/src/summary/prelinker_test.dart
+++ b/pkg/analyzer/test/src/summary/prelinker_test.dart
@@ -4,15 +4,13 @@
library analyzer.test.src.summary.prelinker_test;
-import 'package:analyzer/dart/element/element.dart';
-import 'package:analyzer/src/generated/source.dart';
-import 'package:analyzer/src/generated/source_io.dart';
+import 'package:analyzer/src/generated/utilities_dart.dart';
import 'package:analyzer/src/summary/idl.dart';
import 'package:analyzer/src/summary/prelink.dart';
import 'package:test_reflective_loader/test_reflective_loader.dart';
import 'package:unittest/unittest.dart';
-import 'summarize_elements_test.dart';
+import 'summarize_ast_test.dart';
import 'summary_common.dart';
main() {
@@ -26,10 +24,7 @@
* information, and then recreating it using the prelinker.
*/
@reflectiveTest
-class PrelinkerTest extends SummarizeElementsTest {
- final Map<String, UnlinkedPublicNamespace> uriToPublicNamespace =
- <String, UnlinkedPublicNamespace>{};
-
+class PrelinkerTest extends LinkedSummarizeAstTest {
@override
bool get expectAbsoluteUrisInDependencies => false;
@@ -40,59 +35,25 @@
bool get strongMode => false;
@override
- Source addNamedSource(String filePath, String contents) {
- Source source = super.addNamedSource(filePath, contents);
- uriToPublicNamespace[absUri(filePath)] =
- computePublicNamespaceFromText(contents, source);
- return source;
- }
+ void serializeLibraryText(String text, {bool allowErrors: false}) {
+ super.serializeLibraryText(text, allowErrors: allowErrors);
- String resolveToAbsoluteUri(LibraryElement library, String relativeUri) {
- Source resolvedSource =
- context.sourceFactory.resolveUri(library.source, relativeUri);
- if (resolvedSource == null) {
- fail('Failed to resolve relative uri "$relativeUri"');
- }
- return resolvedSource.uri.toString();
- }
-
- @override
- void serializeLibraryElement(LibraryElement library) {
- super.serializeLibraryElement(library);
- uriToPublicNamespace[library.source.uri.toString()] =
- unlinkedUnits[0].publicNamespace;
- Map<String, UnlinkedUnit> uriToUnit = <String, UnlinkedUnit>{};
- expect(unlinkedUnits.length, unitUris.length);
- for (int i = 1; i < unlinkedUnits.length; i++) {
- uriToUnit[unitUris[i]] = unlinkedUnits[i];
- }
UnlinkedUnit getPart(String relativeUri) {
- String absoluteUri = resolveToAbsoluteUri(library, relativeUri);
- UnlinkedUnit unit = uriToUnit[absoluteUri];
- if (unit == null) {
- fail('Prelinker unexpectedly requested unit for "$relativeUri"'
- ' (resolves to "$absoluteUri").');
- }
- return unit;
+ String absoluteUri =
+ resolveRelativeUri(linkerInputs.testDartUri, Uri.parse(relativeUri))
+ .toString();
+ return linkerInputs.getUnit(absoluteUri);
}
UnlinkedPublicNamespace getImport(String relativeUri) {
- String absoluteUri = resolveToAbsoluteUri(library, relativeUri);
- UnlinkedPublicNamespace namespace = SerializedMockSdk
- .instance.uriToUnlinkedUnit[absoluteUri]?.publicNamespace;
- if (namespace == null) {
- namespace = uriToPublicNamespace[absoluteUri];
- }
- if (namespace == null && !allowMissingFiles) {
- fail('Prelinker unexpectedly requested namespace for "$relativeUri"'
- ' (resolves to "$absoluteUri").'
- ' Namespaces available: ${uriToPublicNamespace.keys}');
- }
- return namespace;
+ return getPart(relativeUri)?.publicNamespace;
}
- linked = new LinkedLibrary.fromBuffer(
- prelink(unlinkedUnits[0], getPart, getImport).toBuffer());
+ linked = new LinkedLibrary.fromBuffer(prelink(
+ linkerInputs.unlinkedDefiningUnit,
+ getPart,
+ getImport,
+ (String declaredVariable) => null).toBuffer());
validateLinkedLibrary(linked);
}
}
diff --git a/pkg/analyzer/test/src/summary/resynthesize_ast_test.dart b/pkg/analyzer/test/src/summary/resynthesize_ast_test.dart
index 3f281d3..c6ec856 100644
--- a/pkg/analyzer/test/src/summary/resynthesize_ast_test.dart
+++ b/pkg/analyzer/test/src/summary/resynthesize_ast_test.dart
@@ -26,12 +26,13 @@
import '../context/abstract_context.dart';
import '../task/strong/inferred_type_test.dart';
-import 'resynthesize_test.dart';
+import 'resynthesize_common.dart';
import 'summary_common.dart';
main() {
groupSep = ' | ';
- defineReflectiveTests(ResynthesizeAstTest);
+ defineReflectiveTests(ResynthesizeAstSpecTest);
+ defineReflectiveTests(ResynthesizeAstStrongTest);
defineReflectiveTests(AstInferredTypeTest);
}
@@ -208,12 +209,6 @@
super.test_constructors_inferFromArguments_redirectingFactory();
}
- @override
- @failingTest
- void test_genericMethods_inferJSBuiltin() {
- super.test_genericMethods_inferJSBuiltin();
- }
-
void test_infer_extractIndex_custom() {
var unit = checkFile('''
class A {
@@ -689,27 +684,65 @@
}
@reflectiveTest
-class ResynthesizeAstTest extends ResynthesizeTest
- with _AstResynthesizeTestMixin {
+class ResynthesizeAstSpecTest extends _ResynthesizeAstTest {
@override
- bool get checkPropagatedTypes => false;
+ AnalysisOptionsImpl createOptions() =>
+ super.createOptions()..strongMode = false;
+}
+
+@reflectiveTest
+class ResynthesizeAstStrongTest extends _ResynthesizeAstTest {
+ @override
+ AnalysisOptionsImpl createOptions() =>
+ super.createOptions()..strongMode = true;
@override
- LibraryElementImpl checkLibrary(String text,
- {bool allowErrors: false, bool dumpSummaries: false}) {
- Source source = addTestSource(text);
- LibraryElementImpl resynthesized = _encodeDecodeLibraryElement(source);
- LibraryElementImpl original = context.computeLibraryElement(source);
- checkLibraryElements(original, resynthesized);
- return resynthesized;
+ @failingTest
+ test_const_invokeConstructor_named_unresolved() {
+ super.test_const_invokeConstructor_named_unresolved();
}
@override
- DartSdk createDartSdk() => AbstractContextTest.SHARED_MOCK_SDK;
+ @failingTest
+ test_const_invokeConstructor_named_unresolved3() {
+ super.test_const_invokeConstructor_named_unresolved3();
+ }
@override
- TestSummaryResynthesizer encodeDecodeLibrarySource(Source source) {
- return _encodeLibrary(source);
+ @failingTest
+ test_instantiateToBounds_boundRefersToLaterTypeArgument() {
+ // TODO(paulberry): this is failing due to dartbug.com/27072.
+ super.test_instantiateToBounds_boundRefersToLaterTypeArgument();
+ }
+
+ @override
+ @failingTest
+ test_syntheticFunctionType_genericClosure() {
+ super.test_syntheticFunctionType_genericClosure();
+ }
+
+ @override
+ @failingTest
+ test_syntheticFunctionType_inGenericClass() {
+ super.test_syntheticFunctionType_inGenericClass();
+ }
+
+ @override
+ @failingTest
+ test_syntheticFunctionType_noArguments() {
+ super.test_syntheticFunctionType_noArguments();
+ }
+
+ @override
+ @failingTest
+ test_syntheticFunctionType_withArguments() {
+ super.test_syntheticFunctionType_withArguments();
+ }
+
+ @override
+ @failingTest
+ test_unused_type_parameter() {
+ super.test_unused_type_parameter();
}
}
@@ -762,15 +795,19 @@
return unit;
}
- Set<String> nonSdkLibraryUris = context.sources
+ Set<String> nonSdkLibraryUris = serializedSources
.where((Source source) =>
!source.isInSystemLibrary &&
context.computeKindOf(source) == SourceKind.LIBRARY)
.map((Source source) => source.uri.toString())
.toSet();
- Map<String, LinkedLibrary> linkedSummaries = link(nonSdkLibraryUris,
- getDependency, getUnit, context.analysisOptions.strongMode);
+ Map<String, LinkedLibrary> linkedSummaries = link(
+ nonSdkLibraryUris,
+ getDependency,
+ getUnit,
+ context.declaredVariables.get,
+ context.analysisOptions.strongMode);
return new TestSummaryResynthesizer(
null,
@@ -843,8 +880,8 @@
UnlinkedUnit definingUnit = _getUnlinkedUnit(librarySource);
if (definingUnit != null) {
- LinkedLibraryBuilder linkedLibrary =
- prelink(definingUnit, getPart, getImport);
+ LinkedLibraryBuilder linkedLibrary = prelink(
+ definingUnit, getPart, getImport, context.declaredVariables.get);
linkedLibrary.dependencies.skip(1).forEach((LinkedDependency d) {
_serializeLibrary(resolveRelativeUri(d.uri));
});
@@ -865,3 +902,34 @@
*/
bool get allowMissingFiles;
}
+
+abstract class _ResynthesizeAstTest extends ResynthesizeTest
+ with _AstResynthesizeTestMixin {
+ @override
+ bool get checkPropagatedTypes => false;
+
+ @override
+ LibraryElementImpl checkLibrary(String text,
+ {bool allowErrors: false, bool dumpSummaries: false}) {
+ Source source = addTestSource(text);
+ LibraryElementImpl resynthesized = _encodeDecodeLibraryElement(source);
+ LibraryElementImpl original = context.computeLibraryElement(source);
+ checkLibraryElements(original, resynthesized);
+ return resynthesized;
+ }
+
+ @override
+ void compareLocalElementsOfExecutable(ExecutableElement resynthesized,
+ ExecutableElement original, String desc) {
+ // We don't resynthesize local elements during link.
+ // So, we should not compare them.
+ }
+
+ @override
+ DartSdk createDartSdk() => AbstractContextTest.SHARED_MOCK_SDK;
+
+ @override
+ TestSummaryResynthesizer encodeDecodeLibrarySource(Source source) {
+ return _encodeLibrary(source);
+ }
+}
diff --git a/pkg/analyzer/test/src/summary/resynthesize_test.dart b/pkg/analyzer/test/src/summary/resynthesize_common.dart
similarity index 94%
rename from pkg/analyzer/test/src/summary/resynthesize_test.dart
rename to pkg/analyzer/test/src/summary/resynthesize_common.dart
index 1739dba..06396ec 100644
--- a/pkg/analyzer/test/src/summary/resynthesize_test.dart
+++ b/pkg/analyzer/test/src/summary/resynthesize_common.dart
@@ -4,38 +4,30 @@
library test.src.serialization.elements_test;
-import 'dart:convert';
-
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/constant/value.dart';
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/type.dart';
+import 'package:analyzer/error/error.dart';
import 'package:analyzer/src/dart/ast/ast.dart';
import 'package:analyzer/src/dart/element/element.dart';
import 'package:analyzer/src/dart/element/handle.dart';
import 'package:analyzer/src/dart/element/member.dart';
import 'package:analyzer/src/dart/element/type.dart';
+import 'package:analyzer/src/error/codes.dart';
import 'package:analyzer/src/generated/engine.dart';
-import 'package:analyzer/src/generated/error.dart';
import 'package:analyzer/src/generated/resolver.dart' show Namespace;
import 'package:analyzer/src/generated/sdk.dart';
import 'package:analyzer/src/generated/source.dart';
import 'package:analyzer/src/generated/testing/ast_factory.dart';
import 'package:analyzer/src/summary/idl.dart';
import 'package:analyzer/src/summary/resynthesize.dart';
-import 'package:analyzer/src/summary/summarize_elements.dart';
import 'package:test_reflective_loader/test_reflective_loader.dart';
import 'package:unittest/unittest.dart';
import '../../generated/test_support.dart';
import '../abstract_single_unit.dart';
import '../context/abstract_context.dart';
-import 'summary_common.dart' show canonicalize;
-
-main() {
- groupSep = ' | ';
- defineReflectiveTests(ResynthesizeElementTest);
-}
/**
* Abstract base class for resynthesizing and comparing elements.
@@ -1134,64 +1126,6 @@
AnalysisOptionsImpl createOptions() =>
new AnalysisOptionsImpl()..enableGenericMethods = true;
- /**
- * Serialize the given [library] into a summary. Then create a
- * [TestSummaryResynthesizer] which can deserialize it, along with any
- * references it makes to `dart:core`.
- *
- * Errors will lead to a test failure unless [allowErrors] is `true`.
- */
- TestSummaryResynthesizer encodeLibrary(LibraryElementImpl library,
- {bool allowErrors: false, bool dumpSummaries: false}) {
- if (!allowErrors) {
- assertNoErrors(library.source);
- }
- addLibrary('dart:core');
- addLibrary('dart:async');
- addLibrary('dart:math');
- return encodeLibraryElement(library, dumpSummaries: dumpSummaries);
- }
-
- /**
- * Convert the library element [library] into a summary, and then create a
- * [TestSummaryResynthesizer] which can deserialize it.
- *
- * Caller is responsible for checking the library for errors, and adding any
- * dependent libraries using [addLibrary].
- */
- TestSummaryResynthesizer encodeLibraryElement(LibraryElementImpl library,
- {bool dumpSummaries: false}) {
- Map<String, UnlinkedUnit> unlinkedSummaries = <String, UnlinkedUnit>{};
- LinkedLibrary getLinkedSummaryFor(LibraryElement lib) {
- LibrarySerializationResult serialized = serializeLibrary(
- lib, context.typeProvider, context.analysisOptions.strongMode);
- for (int i = 0; i < serialized.unlinkedUnits.length; i++) {
- unlinkedSummaries[serialized.unitUris[i]] =
- new UnlinkedUnit.fromBuffer(serialized.unlinkedUnits[i].toBuffer());
- }
- return new LinkedLibrary.fromBuffer(serialized.linked.toBuffer());
- }
-
- Map<String, LinkedLibrary> linkedSummaries = <String, LinkedLibrary>{
- library.source.uri.toString(): getLinkedSummaryFor(library)
- };
- for (Source source in otherLibrarySources) {
- LibraryElement original = context.computeLibraryElement(source);
- String uri = source.uri.toString();
- linkedSummaries[uri] = getLinkedSummaryFor(original);
- }
- if (dumpSummaries) {
- unlinkedSummaries.forEach((String path, UnlinkedUnit unit) {
- print('Unlinked $path: ${JSON.encode(canonicalize(unit))}');
- });
- linkedSummaries.forEach((String path, LinkedLibrary lib) {
- print('Linked $path: ${JSON.encode(canonicalize(lib))}');
- });
- }
- return new TestSummaryResynthesizer(
- null, context, unlinkedSummaries, linkedSummaries, allowMissingFiles);
- }
-
ElementImpl getActualElement(Element element, String desc) {
if (element == null) {
return null;
@@ -1343,114 +1277,6 @@
}
@reflectiveTest
-class ResynthesizeElementTest extends ResynthesizeTest {
- @override
- LibraryElementImpl checkLibrary(String text,
- {bool allowErrors: false, bool dumpSummaries: false}) {
- Source source = addTestSource(text);
- LibraryElementImpl original = context.computeLibraryElement(source);
- LibraryElementImpl resynthesized = resynthesizeLibraryElement(
- encodeLibrary(original,
- allowErrors: allowErrors, dumpSummaries: dumpSummaries),
- source.uri.toString(),
- original);
- checkLibraryElements(original, resynthesized);
- return resynthesized;
- }
-
- @override
- SummaryResynthesizer encodeDecodeLibrarySource(Source librarySource) {
- LibraryElement libraryElement =
- context.computeLibraryElement(librarySource);
- return encodeLibrary(libraryElement);
- }
-
- /**
- * Serialize the given [library] into a summary. Then create a
- * [TestSummaryResynthesizer] which can deserialize it, along with any
- * references it makes to `dart:core`.
- *
- * Errors will lead to a test failure unless [allowErrors] is `true`.
- */
- TestSummaryResynthesizer encodeLibrary(LibraryElementImpl library,
- {bool allowErrors: false, bool dumpSummaries: false}) {
- if (!allowErrors) {
- assertNoErrors(library.source);
- }
- addLibrary('dart:core');
- addLibrary('dart:async');
- addLibrary('dart:math');
- return encodeLibraryElement(library, dumpSummaries: dumpSummaries);
- }
-
- /**
- * Convert the library element [library] into a summary, and then create a
- * [TestSummaryResynthesizer] which can deserialize it.
- *
- * Caller is responsible for checking the library for errors, and adding any
- * dependent libraries using [addLibrary].
- */
- TestSummaryResynthesizer encodeLibraryElement(LibraryElementImpl library,
- {bool dumpSummaries: false}) {
- Map<String, UnlinkedUnit> unlinkedSummaries = <String, UnlinkedUnit>{};
- LinkedLibrary getLinkedSummaryFor(LibraryElement lib) {
- LibrarySerializationResult serialized = serializeLibrary(
- lib, context.typeProvider, context.analysisOptions.strongMode);
- for (int i = 0; i < serialized.unlinkedUnits.length; i++) {
- unlinkedSummaries[serialized.unitUris[i]] =
- new UnlinkedUnit.fromBuffer(serialized.unlinkedUnits[i].toBuffer());
- }
- return new LinkedLibrary.fromBuffer(serialized.linked.toBuffer());
- }
-
- Map<String, LinkedLibrary> linkedSummaries = <String, LinkedLibrary>{
- library.source.uri.toString(): getLinkedSummaryFor(library)
- };
- for (Source source in otherLibrarySources) {
- LibraryElement original = context.computeLibraryElement(source);
- String uri = source.uri.toString();
- linkedSummaries[uri] = getLinkedSummaryFor(original);
- }
- if (dumpSummaries) {
- unlinkedSummaries.forEach((String path, UnlinkedUnit unit) {
- print('Unlinked $path: ${JSON.encode(canonicalize(unit))}');
- });
- linkedSummaries.forEach((String path, LinkedLibrary lib) {
- print('Linked $path: ${JSON.encode(canonicalize(lib))}');
- });
- }
- return new TestSummaryResynthesizer(
- null, context, unlinkedSummaries, linkedSummaries, allowMissingFiles);
- }
-
- /**
- * Resynthesize the library element associated with [uri] using
- * [resynthesizer], and verify that it only had to consult one summary in
- * order to do so. [original] is consulted merely to verify that no
- * unnecessary resynthesis work was performed.
- */
- LibraryElementImpl resynthesizeLibraryElement(
- TestSummaryResynthesizer resynthesizer,
- String uri,
- LibraryElement original) {
- LibraryElementImpl resynthesized = resynthesizer.getLibraryElement(uri);
- checkMinimalResynthesisWork(resynthesizer, original);
- return resynthesized;
- }
-
- test_core() {
- addLibrary('dart:async');
- addLibrary('dart:math');
- String uri = 'dart:core';
- LibraryElementImpl original =
- context.computeLibraryElement(context.sourceFactory.forUri(uri));
- LibraryElementImpl resynthesized = resynthesizeLibraryElement(
- encodeLibraryElement(original), uri, original);
- checkLibraryElements(original, resynthesized);
- }
-}
-
-@reflectiveTest
abstract class ResynthesizeTest extends AbstractResynthesizeTest {
LibraryElementImpl checkLibrary(String text,
{bool allowErrors: false, bool dumpSummaries: false});
@@ -3029,6 +2855,51 @@
checkLibrary('export "a.dart";');
}
+ test_export_configurations_useDefault() {
+ context.declaredVariables.define('dart.library.io', 'false');
+ addLibrarySource('/foo.dart', 'class A {}');
+ addLibrarySource('/foo_io.dart', 'class A {}');
+ addLibrarySource('/foo_html.dart', 'class A {}');
+ LibraryElementImpl library = checkLibrary(r'''
+export 'foo.dart'
+ if (dart.library.io) 'foo_io.dart'
+ if (dart.library.html) 'foo_html.dart';
+''');
+ expect(library.exports[0].uri, 'foo.dart');
+ expect(library.exports[0].exportedLibrary.source.shortName, 'foo.dart');
+ }
+
+ test_export_configurations_useFirst() {
+ context.declaredVariables.define('dart.library.io', 'true');
+ context.declaredVariables.define('dart.library.html', 'true');
+ addLibrarySource('/foo.dart', 'class A {}');
+ addLibrarySource('/foo_io.dart', 'class A {}');
+ addLibrarySource('/foo_html.dart', 'class A {}');
+ LibraryElementImpl library = checkLibrary(r'''
+export 'foo.dart'
+ if (dart.library.io) 'foo_io.dart'
+ if (dart.library.html) 'foo_html.dart';
+''');
+ expect(library.exports[0].uri, 'foo_io.dart');
+ expect(library.exports[0].exportedLibrary.source.shortName, 'foo_io.dart');
+ }
+
+ test_export_configurations_useSecond() {
+ context.declaredVariables.define('dart.library.io', 'false');
+ context.declaredVariables.define('dart.library.html', 'true');
+ addLibrarySource('/foo.dart', 'class A {}');
+ addLibrarySource('/foo_io.dart', 'class A {}');
+ addLibrarySource('/foo_html.dart', 'class A {}');
+ LibraryElementImpl library = checkLibrary(r'''
+export 'foo.dart'
+ if (dart.library.io) 'foo_io.dart'
+ if (dart.library.html) 'foo_html.dart';
+''');
+ ExportElement export = library.exports[0];
+ expect(export.uri, 'foo_html.dart');
+ expect(export.exportedLibrary.source.shortName, 'foo_html.dart');
+ }
+
test_export_function() {
addLibrarySource('/a.dart', 'f() {}');
checkLibrary('export "a.dart";');
@@ -3079,6 +2950,47 @@
checkLibrary('export "a.dart";');
}
+ test_exportImport_configurations_useDefault() {
+ context.declaredVariables.define('dart.library.io', 'false');
+ addLibrarySource('/foo.dart', 'class A {}');
+ addLibrarySource('/foo_io.dart', 'class A {}');
+ addLibrarySource('/foo_html.dart', 'class A {}');
+ addLibrarySource(
+ '/bar.dart',
+ r'''
+export 'foo.dart'
+ if (dart.library.io) 'foo_io.dart'
+ if (dart.library.html) 'foo_html.dart';
+''');
+ LibraryElementImpl library = checkLibrary(r'''
+import 'bar.dart';
+class B extends A {}
+''');
+ var typeA = library.definingCompilationUnit.getType('B').supertype;
+ expect(typeA.element.source.shortName, 'foo.dart');
+ }
+
+ test_exportImport_configurations_useFirst() {
+ context.declaredVariables.define('dart.library.io', 'true');
+ context.declaredVariables.define('dart.library.html', 'true');
+ addLibrarySource('/foo.dart', 'class A {}');
+ addLibrarySource('/foo_io.dart', 'class A {}');
+ addLibrarySource('/foo_html.dart', 'class A {}');
+ addLibrarySource(
+ '/bar.dart',
+ r'''
+export 'foo.dart'
+ if (dart.library.io) 'foo_io.dart'
+ if (dart.library.html) 'foo_html.dart';
+''');
+ var library = checkLibrary(r'''
+import 'bar.dart';
+class B extends A {}
+''');
+ var typeA = library.definingCompilationUnit.getType('B').supertype;
+ expect(typeA.element.source.shortName, 'foo_io.dart');
+ }
+
test_exports() {
addLibrarySource('/a.dart', 'library a;');
addLibrarySource('/b.dart', 'library b;');
@@ -3393,6 +3305,39 @@
checkLibrary('void set x(int value) {} int get x => 0;');
}
+ test_import_configurations_useDefault() {
+ context.declaredVariables.define('dart.library.io', 'false');
+ addLibrarySource('/foo.dart', 'class A {}');
+ addLibrarySource('/foo_io.dart', 'class A {}');
+ addLibrarySource('/foo_html.dart', 'class A {}');
+ var library = checkLibrary(r'''
+import 'foo.dart'
+ if (dart.library.io) 'foo_io.dart'
+ if (dart.library.html) 'foo_html.dart';
+
+class B extends A {}
+''');
+ var typeA = library.definingCompilationUnit.getType('B').supertype;
+ expect(typeA.element.source.shortName, 'foo.dart');
+ }
+
+ test_import_configurations_useFirst() {
+ context.declaredVariables.define('dart.library.io', 'true');
+ context.declaredVariables.define('dart.library.html', 'true');
+ addLibrarySource('/foo.dart', 'class A {}');
+ addLibrarySource('/foo_io.dart', 'class A {}');
+ addLibrarySource('/foo_html.dart', 'class A {}');
+ var library = checkLibrary(r'''
+import 'foo.dart'
+ if (dart.library.io) 'foo_io.dart'
+ if (dart.library.html) 'foo_html.dart';
+
+class B extends A {}
+''');
+ var typeA = library.definingCompilationUnit.getType('B').supertype;
+ expect(typeA.element.source.shortName, 'foo_io.dart');
+ }
+
test_import_deferred() {
addLibrarySource('/a.dart', 'f() {}');
checkLibrary('import "a.dart" deferred as p; main() { p.f(); }');
diff --git a/pkg/analyzer/test/src/summary/resynthesize_strong_test.dart b/pkg/analyzer/test/src/summary/resynthesize_strong_test.dart
deleted file mode 100644
index 50ea71b..0000000
--- a/pkg/analyzer/test/src/summary/resynthesize_strong_test.dart
+++ /dev/null
@@ -1,35 +0,0 @@
-// Copyright (c) 2016, 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.
-
-library analyzer.test.src.summary.resynthesize_strong_test;
-
-import 'package:analyzer/src/generated/engine.dart';
-import 'package:analyzer/src/generated/sdk.dart';
-import 'package:test_reflective_loader/test_reflective_loader.dart';
-import 'package:unittest/unittest.dart';
-
-import '../context/abstract_context.dart';
-import 'resynthesize_test.dart';
-
-main() {
- groupSep = ' | ';
- defineReflectiveTests(ResynthesizeStrongTest);
-}
-
-@reflectiveTest
-class ResynthesizeStrongTest extends ResynthesizeElementTest {
- @override
- DartSdk createDartSdk() => AbstractContextTest.SHARED_STRONG_MOCK_SDK;
-
- @override
- AnalysisOptionsImpl createOptions() =>
- super.createOptions()..strongMode = true;
-
- @override
- @failingTest
- test_instantiateToBounds_boundRefersToLaterTypeArgument() {
- // TODO(paulberry): this is failing due to dartbug.com/27072.
- super.test_instantiateToBounds_boundRefersToLaterTypeArgument();
- }
-}
diff --git a/pkg/analyzer/test/src/summary/summarize_ast_test.dart b/pkg/analyzer/test/src/summary/summarize_ast_test.dart
index d34b68e..b0c346f 100644
--- a/pkg/analyzer/test/src/summary/summarize_ast_test.dart
+++ b/pkg/analyzer/test/src/summary/summarize_ast_test.dart
@@ -7,9 +7,9 @@
import 'package:analyzer/analyzer.dart';
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/ast/token.dart';
+import 'package:analyzer/error/listener.dart';
import 'package:analyzer/src/dart/scanner/reader.dart';
import 'package:analyzer/src/dart/scanner/scanner.dart';
-import 'package:analyzer/src/generated/error.dart';
import 'package:analyzer/src/generated/parser.dart';
import 'package:analyzer/src/generated/source.dart';
import 'package:analyzer/src/summary/format.dart';
@@ -137,6 +137,8 @@
@override
List<UnlinkedUnit> unlinkedUnits;
+ LinkerInputs linkerInputs;
+
@override
bool get checkAstDerivedData => true;
@@ -152,9 +154,13 @@
@override
void serializeLibraryText(String text, {bool allowErrors: false}) {
Map<String, UnlinkedUnitBuilder> uriToUnit = this._filesToLink.uriToUnit;
- LinkerInputs linkerInputs = createLinkerInputs(text);
- linked = link(linkerInputs.linkedLibraries, linkerInputs.getDependency,
- linkerInputs.getUnit, strongMode)[linkerInputs.testDartUri.toString()];
+ linkerInputs = createLinkerInputs(text);
+ linked = link(
+ linkerInputs.linkedLibraries,
+ linkerInputs.getDependency,
+ linkerInputs.getUnit,
+ (name) => null,
+ strongMode)[linkerInputs.testDartUri.toString()];
expect(linked, isNotNull);
validateLinkedLibrary(linked);
unlinkedUnits = <UnlinkedUnit>[linkerInputs.unlinkedDefiningUnit];
@@ -203,6 +209,10 @@
Set<String> get linkedLibraries => _uriToUnit.keys.toSet();
+ String getDeclaredVariable(String name) {
+ return null;
+ }
+
LinkedLibrary getDependency(String absoluteUri) {
Map<String, LinkedLibrary> sdkLibraries =
SerializedMockSdk.instance.uriToLinkedLibrary;
@@ -299,6 +309,7 @@
linkerInputs.linkedLibraries,
linkerInputs.getDependency,
linkerInputs.getUnit,
+ linkerInputs.getDeclaredVariable,
true);
linkedLibraries.forEach(assembler.addLinkedLibrary);
linkerInputs._uriToUnit.forEach((String uri, UnlinkedUnit unit) {
diff --git a/pkg/analyzer/test/src/summary/summarize_elements_strong_test.dart b/pkg/analyzer/test/src/summary/summarize_elements_strong_test.dart
deleted file mode 100644
index ffa3cc0..0000000
--- a/pkg/analyzer/test/src/summary/summarize_elements_strong_test.dart
+++ /dev/null
@@ -1,35 +0,0 @@
-// Copyright (c) 2016, 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.
-
-library analyzer.test.src.summary.summarize_elements_strong_test;
-
-import 'package:analyzer/src/generated/engine.dart';
-import 'package:analyzer/src/generated/sdk.dart';
-import 'package:test_reflective_loader/test_reflective_loader.dart';
-import 'package:unittest/unittest.dart';
-
-import '../context/abstract_context.dart';
-import 'summarize_elements_test.dart';
-import 'summary_common.dart';
-
-main() {
- groupSep = ' | ';
- defineReflectiveTests(SummarizeElementsStrongTest);
-}
-
-/**
- * Override of [SummaryTest] which creates summaries from the element model
- * using strong mode.
- */
-@reflectiveTest
-class SummarizeElementsStrongTest extends SummarizeElementsTest {
- @override
- AnalysisOptionsImpl get options => super.options..strongMode = true;
-
- @override
- bool get strongMode => true;
-
- @override
- DartSdk createDartSdk() => AbstractContextTest.SHARED_STRONG_MOCK_SDK;
-}
diff --git a/pkg/analyzer/test/src/summary/summarize_elements_test.dart b/pkg/analyzer/test/src/summary/summarize_elements_test.dart
deleted file mode 100644
index 7eeb91f..0000000
--- a/pkg/analyzer/test/src/summary/summarize_elements_test.dart
+++ /dev/null
@@ -1,167 +0,0 @@
-// Copyright (c) 2016, 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.
-
-library analyzer.test.src.summary.summarize_elements_test;
-
-import 'package:analyzer/dart/element/element.dart';
-import 'package:analyzer/src/generated/engine.dart';
-import 'package:analyzer/src/generated/sdk.dart';
-import 'package:analyzer/src/generated/source.dart';
-import 'package:analyzer/src/generated/source_io.dart';
-import 'package:analyzer/src/summary/format.dart';
-import 'package:analyzer/src/summary/idl.dart';
-import 'package:analyzer/src/summary/public_namespace_computer.dart'
- as public_namespace;
-import 'package:analyzer/src/summary/summarize_elements.dart'
- as summarize_elements;
-import 'package:test_reflective_loader/test_reflective_loader.dart';
-import 'package:unittest/unittest.dart';
-
-import '../abstract_single_unit.dart';
-import '../context/abstract_context.dart';
-import 'summary_common.dart';
-
-main() {
- groupSep = ' | ';
- defineReflectiveTests(SummarizeElementsTest);
-}
-
-/**
- * Override of [SummaryTest] which creates summaries from the element model.
- */
-@reflectiveTest
-class SummarizeElementsTest extends AbstractSingleUnitTest with SummaryTest {
- /**
- * The list of absolute unit URIs corresponding to the compilation units in
- * [unlinkedUnits].
- */
- List<String> unitUris;
-
- /**
- * Map containing all source files in this test, and their corresponding file
- * contents.
- */
- final Map<Source, String> _fileContents = <Source, String>{};
-
- @override
- LinkedLibrary linked;
-
- @override
- List<UnlinkedUnit> unlinkedUnits;
-
- @override
- bool get checkAstDerivedData => false;
-
- @override
- bool get expectAbsoluteUrisInDependencies => true;
-
- /**
- * Determine the analysis options that should be used for this test.
- */
- AnalysisOptionsImpl get options =>
- new AnalysisOptionsImpl()..enableGenericMethods = true;
-
- @override
- bool get skipFullyLinkedData => false;
-
- @override
- bool get skipNonConstInitializers => true;
-
- @override
- bool get strongMode => false;
-
- @override
- Source addNamedSource(String filePath, String contents) {
- Source source = super.addSource(filePath, contents);
- _fileContents[source] = contents;
- return source;
- }
-
- @override
- DartSdk createDartSdk() => AbstractContextTest.SHARED_MOCK_SDK;
-
- /**
- * Serialize the library containing the given class [element], then
- * deserialize it and return the summary of the class.
- */
- UnlinkedClass serializeClassElement(ClassElement element) {
- serializeLibraryElement(element.library);
- return findClass(element.name, failIfAbsent: true);
- }
-
- /**
- * Serialize the given [library] element, then deserialize it and store the
- * resulting summary in [linked] and [unlinkedUnits].
- */
- void serializeLibraryElement(LibraryElement library) {
- summarize_elements.LibrarySerializationResult serializedLib =
- summarize_elements.serializeLibrary(
- library, context.typeProvider, context.analysisOptions.strongMode);
- {
- List<int> buffer = serializedLib.linked.toBuffer();
- linked = new LinkedLibrary.fromBuffer(buffer);
- validateLinkedLibrary(linked);
- }
- unlinkedUnits = serializedLib.unlinkedUnits.map((UnlinkedUnitBuilder b) {
- List<int> buffer = b.toBuffer();
- return new UnlinkedUnit.fromBuffer(buffer);
- }).toList();
- unitUris = serializedLib.unitUris;
- }
-
- @override
- void serializeLibraryText(String text, {bool allowErrors: false}) {
- Source source = addTestSource(text);
- _fileContents[source] = text;
- LibraryElement library = context.computeLibraryElement(source);
- if (!allowErrors) {
- assertNoErrorsInSource(source);
- }
- serializeLibraryElement(library);
- expect(unlinkedUnits[0].imports.length, linked.importDependencies.length);
- expect(unlinkedUnits[0].exports.length, linked.exportDependencies.length);
- expect(linked.units.length, unlinkedUnits.length);
- for (int i = 0; i < linked.units.length; i++) {
- expect(unlinkedUnits[i].references.length,
- lessThanOrEqualTo(linked.units[i].references.length));
- }
- verifyPublicNamespace();
- }
-
- @override
- void setUp() {
- super.setUp();
- prepareAnalysisContext(options);
- }
-
- test_class_no_superclass() {
- UnlinkedClass cls =
- serializeClassElement(context.typeProvider.objectType.element);
- expect(cls.supertype, isNull);
- expect(cls.hasNoSupertype, isTrue);
- }
-
- /**
- * Verify that [public_namespace.computePublicNamespace] produces data that's
- * equivalent to that produced by [summarize_elements.serializeLibrary].
- */
- void verifyPublicNamespace() {
- for (int i = 0; i < unlinkedUnits.length; i++) {
- Source source = context.sourceFactory.forUri(unitUris[i]);
- String text = _fileContents[source];
- if (text == null) {
- if (!allowMissingFiles) {
- fail('Could not find file while verifying public namespace: '
- '${unitUris[i]}');
- }
- } else {
- UnlinkedPublicNamespace namespace =
- computePublicNamespaceFromText(text, source);
- expect(canonicalize(namespace),
- canonicalize(unlinkedUnits[i].publicNamespace),
- reason: 'publicNamespace(${unitUris[i]})');
- }
- }
- }
-}
diff --git a/pkg/analyzer/test/src/summary/summary_common.dart b/pkg/analyzer/test/src/summary/summary_common.dart
index 5d9d9a7..9df7f77 100644
--- a/pkg/analyzer/test/src/summary/summary_common.dart
+++ b/pkg/analyzer/test/src/summary/summary_common.dart
@@ -6,11 +6,9 @@
import 'package:analyzer/analyzer.dart';
import 'package:analyzer/dart/ast/ast.dart';
-import 'package:analyzer/dart/element/element.dart';
+import 'package:analyzer/error/listener.dart';
import 'package:analyzer/src/dart/scanner/reader.dart';
import 'package:analyzer/src/dart/scanner/scanner.dart';
-import 'package:analyzer/src/generated/engine.dart';
-import 'package:analyzer/src/generated/error.dart';
import 'package:analyzer/src/generated/parser.dart';
import 'package:analyzer/src/generated/source.dart';
import 'package:analyzer/src/generated/source_io.dart';
@@ -18,8 +16,6 @@
import 'package:analyzer/src/summary/idl.dart';
import 'package:analyzer/src/summary/public_namespace_computer.dart'
as public_namespace;
-import 'package:analyzer/src/summary/summarize_elements.dart'
- as summarize_elements;
import 'package:path/path.dart' show posix;
import 'package:unittest/unittest.dart';
@@ -108,26 +104,16 @@
static SerializedMockSdk _serializeMockSdk() {
try {
- AnalysisContext analysisContext = new MockSdk().context;
Map<String, UnlinkedUnit> uriToUnlinkedUnit = <String, UnlinkedUnit>{};
Map<String, LinkedLibrary> uriToLinkedLibrary = <String, LinkedLibrary>{};
- List<LibraryElement> libraries = [
- analysisContext.typeProvider.objectType.element.library,
- analysisContext.typeProvider.futureType.element.library,
- analysisContext.computeLibraryElement(
- analysisContext.sourceFactory.resolveUri(null, 'dart:math')),
- ];
- for (LibraryElement library in libraries) {
- summarize_elements.LibrarySerializationResult serializedLibrary =
- summarize_elements.serializeLibrary(
- library, analysisContext.typeProvider, false);
- uriToLinkedLibrary[library.source.uri.toString()] =
- new LinkedLibrary.fromBuffer(serializedLibrary.linked.toBuffer());
- for (int i = 0; i < serializedLibrary.unlinkedUnits.length; i++) {
- uriToUnlinkedUnit[serializedLibrary.unitUris[i]] =
- new UnlinkedUnit.fromBuffer(
- serializedLibrary.unlinkedUnits[i].toBuffer());
- }
+ PackageBundle bundle = new MockSdk().getLinkedBundle();
+ for (int i = 0; i < bundle.unlinkedUnitUris.length; i++) {
+ String uri = bundle.unlinkedUnitUris[i];
+ uriToUnlinkedUnit[uri] = bundle.unlinkedUnits[i];
+ }
+ for (int i = 0; i < bundle.linkedLibraryUris.length; i++) {
+ String uri = bundle.linkedLibraryUris[i];
+ uriToLinkedLibrary[uri] = bundle.linkedLibraries[i];
}
return new SerializedMockSdk._(uriToUnlinkedUnit, uriToLinkedLibrary);
} catch (_) {
@@ -1307,35 +1293,6 @@
expect(cls.interfaces, isEmpty);
}
- test_unresolved_import() {
- allowMissingFiles = true;
- serializeLibraryText("import 'foo.dart';", allowErrors: true);
- expect(unlinkedUnits[0].imports, hasLength(2));
- expect(unlinkedUnits[0].imports[0].uri, 'foo.dart');
- // Note: imports[1] is the implicit import of dart:core.
- expect(unlinkedUnits[0].imports[1].isImplicit, true);
- expect(linked.importDependencies, hasLength(2));
- checkDependency(
- linked.importDependencies[0], absUri('/foo.dart'), 'foo.dart');
- }
-
- test_unresolved_export() {
- allowMissingFiles = true;
- serializeLibraryText("export 'foo.dart';", allowErrors: true);
- expect(unlinkedUnits[0].publicNamespace.exports, hasLength(1));
- expect(unlinkedUnits[0].publicNamespace.exports[0].uri, 'foo.dart');
- expect(linked.exportDependencies, hasLength(1));
- checkDependency(
- linked.exportDependencies[0], absUri('/foo.dart'), 'foo.dart');
- }
-
- test_unresolved_part() {
- allowMissingFiles = true;
- serializeLibraryText("part 'foo.dart';", allowErrors: true);
- expect(unlinkedUnits[0].publicNamespace.parts, hasLength(1));
- expect(unlinkedUnits[0].publicNamespace.parts[0], 'foo.dart');
- }
-
test_class_no_mixins() {
UnlinkedClass cls = serializeClassText('class C {}');
expect(cls.mixins, isEmpty);
@@ -6086,6 +6043,38 @@
ReferenceKind.classOrEnum);
}
+ test_export_configurations() {
+ if (!checkAstDerivedData) {
+ // Element model does not provide access to configurations.
+ return;
+ }
+ addNamedSource('/foo.dart', 'class A {}');
+ addNamedSource('/foo_io.dart', 'class A {}');
+ addNamedSource('/foo_html.dart', 'class A {}');
+ String libraryText = r'''
+export 'foo.dart'
+ if (dart.library.io) 'foo_io.dart'
+ if (dart.flavor == 'html') 'foo_html.dart';
+
+class B extends A {}
+''';
+ serializeLibraryText(libraryText);
+ UnlinkedExportPublic exp = unlinkedUnits[0].publicNamespace.exports[0];
+ expect(exp.configurations, hasLength(2));
+ {
+ UnlinkedConfiguration configuration = exp.configurations[0];
+ expect(configuration.name, 'dart.library.io');
+ expect(configuration.value, 'true');
+ expect(configuration.uri, 'foo_io.dart');
+ }
+ {
+ UnlinkedConfiguration configuration = exp.configurations[1];
+ expect(configuration.name, 'dart.flavor');
+ expect(configuration.value, 'html');
+ expect(configuration.uri, 'foo_html.dart');
+ }
+ }
+
test_export_dependency() {
serializeLibraryText('export "dart:async";');
expect(unlinkedUnits[0].exports, hasLength(1));
@@ -6289,8 +6278,10 @@
String uriString = '"a.dart"';
String libraryText = 'export $uriString;';
serializeLibraryText(libraryText);
- expect(unlinkedUnits[0].publicNamespace.exports, hasLength(1));
- expect(unlinkedUnits[0].publicNamespace.exports[0].uri, 'a.dart');
+ var unlinkedExports = unlinkedUnits[0].publicNamespace.exports;
+ expect(unlinkedExports, hasLength(1));
+ expect(unlinkedExports[0].uri, 'a.dart');
+ expect(unlinkedExports[0].configurations, isEmpty);
}
test_export_variable() {
@@ -7907,6 +7898,36 @@
expect(aDep, lessThan(bDep));
}
+ test_import_configurations() {
+ if (!checkAstDerivedData) {
+ // Element model does not provide access to configurations.
+ return;
+ }
+ addNamedSource('/foo.dart', 'bar() {}');
+ addNamedSource('/foo_io.dart', 'bar() {}');
+ addNamedSource('/foo_html.dart', 'bar() {}');
+ String libraryText = r'''
+import 'foo.dart'
+ if (dart.library.io) 'foo_io.dart'
+ if (dart.flavor == 'html') 'foo_html.dart';
+''';
+ serializeLibraryText(libraryText);
+ UnlinkedImport imp = unlinkedUnits[0].imports[0];
+ expect(imp.configurations, hasLength(2));
+ {
+ UnlinkedConfiguration configuration = imp.configurations[0];
+ expect(configuration.name, 'dart.library.io');
+ expect(configuration.value, 'true');
+ expect(configuration.uri, 'foo_io.dart');
+ }
+ {
+ UnlinkedConfiguration configuration = imp.configurations[1];
+ expect(configuration.name, 'dart.flavor');
+ expect(configuration.value, 'html');
+ expect(configuration.uri, 'foo_html.dart');
+ }
+ }
+
test_import_deferred() {
serializeLibraryText(
'import "dart:async" deferred as a; main() { print(a.Future); }');
@@ -10073,6 +10094,35 @@
_assertCodeRange(unit.codeRange, 0, 14);
}
+ test_unresolved_export() {
+ allowMissingFiles = true;
+ serializeLibraryText("export 'foo.dart';", allowErrors: true);
+ expect(unlinkedUnits[0].publicNamespace.exports, hasLength(1));
+ expect(unlinkedUnits[0].publicNamespace.exports[0].uri, 'foo.dart');
+ expect(linked.exportDependencies, hasLength(1));
+ checkDependency(
+ linked.exportDependencies[0], absUri('/foo.dart'), 'foo.dart');
+ }
+
+ test_unresolved_import() {
+ allowMissingFiles = true;
+ serializeLibraryText("import 'foo.dart';", allowErrors: true);
+ expect(unlinkedUnits[0].imports, hasLength(2));
+ expect(unlinkedUnits[0].imports[0].uri, 'foo.dart');
+ // Note: imports[1] is the implicit import of dart:core.
+ expect(unlinkedUnits[0].imports[1].isImplicit, true);
+ expect(linked.importDependencies, hasLength(2));
+ checkDependency(
+ linked.importDependencies[0], absUri('/foo.dart'), 'foo.dart');
+ }
+
+ test_unresolved_part() {
+ allowMissingFiles = true;
+ serializeLibraryText("part 'foo.dart';", allowErrors: true);
+ expect(unlinkedUnits[0].publicNamespace.parts, hasLength(1));
+ expect(unlinkedUnits[0].publicNamespace.parts[0], 'foo.dart');
+ }
+
test_unresolved_reference_in_multiple_parts() {
addNamedSource('/a.dart', 'part of foo; int x; Unresolved y;');
serializeLibraryText('library foo; part "a.dart"; Unresolved z;',
diff --git a/pkg/analyzer/test/src/summary/test_all.dart b/pkg/analyzer/test/src/summary/test_all.dart
index d669d0e..f4987f4 100644
--- a/pkg/analyzer/test/src/summary/test_all.dart
+++ b/pkg/analyzer/test/src/summary/test_all.dart
@@ -10,7 +10,6 @@
import 'api_signature_test.dart' as api_signature_test;
import 'flat_buffers_test.dart' as flat_buffers_test;
import 'in_summary_source_test.dart' as in_summary_source_test;
-import 'incremental_cache_test.dart' as incremental_cache_test;
import 'index_unit_test.dart' as index_unit_test;
import 'linker_test.dart' as linker_test;
import 'name_filter_test.dart' as name_filter_test;
@@ -18,12 +17,8 @@
import 'prelinker_test.dart' as prelinker_test;
import 'pub_summary_test.dart' as pub_summary_test;
import 'resynthesize_ast_test.dart' as resynthesize_ast_test;
-import 'resynthesize_strong_test.dart' as resynthesize_strong_test;
-import 'resynthesize_test.dart' as resynthesize_test;
import 'summarize_ast_strong_test.dart' as summarize_ast_strong_test;
import 'summarize_ast_test.dart' as summarize_ast_test;
-import 'summarize_elements_strong_test.dart' as summarize_elements_strong_test;
-import 'summarize_elements_test.dart' as summarize_elements_test;
/// Utility for manually running all tests.
main() {
@@ -32,7 +27,6 @@
api_signature_test.main();
flat_buffers_test.main();
in_summary_source_test.main();
- incremental_cache_test.main();
index_unit_test.main();
linker_test.main();
name_filter_test.main();
@@ -40,11 +34,7 @@
prelinker_test.main();
pub_summary_test.main();
resynthesize_ast_test.main();
- resynthesize_strong_test.main();
- resynthesize_test.main();
summarize_ast_strong_test.main();
summarize_ast_test.main();
- summarize_elements_strong_test.main();
- summarize_elements_test.main();
});
}
diff --git a/pkg/analyzer/test/src/task/dart_test.dart b/pkg/analyzer/test/src/task/dart_test.dart
index 390fd8b..f9ebf8c 100644
--- a/pkg/analyzer/test/src/task/dart_test.dart
+++ b/pkg/analyzer/test/src/task/dart_test.dart
@@ -9,12 +9,13 @@
import 'package:analyzer/dart/ast/visitor.dart';
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/type.dart';
+import 'package:analyzer/error/error.dart';
import 'package:analyzer/src/context/cache.dart';
import 'package:analyzer/src/dart/element/element.dart';
+import 'package:analyzer/src/error/codes.dart';
import 'package:analyzer/src/generated/constant.dart';
import 'package:analyzer/src/generated/engine.dart'
show AnalysisOptions, AnalysisOptionsImpl, CacheState;
-import 'package:analyzer/src/generated/error.dart';
import 'package:analyzer/src/generated/resolver.dart';
import 'package:analyzer/src/generated/sdk.dart';
import 'package:analyzer/src/generated/source.dart';
@@ -180,7 +181,8 @@
Annotation annotation = unit.declarations
.firstWhere((m) => m is FunctionDeclaration)
.metadata[0];
- List<ConstantEvaluationTarget> expectedConstants = [
+ List<ConstantEvaluationTarget> expectedConstants =
+ <ConstantEvaluationTarget>[
unitElement.accessors.firstWhere((e) => e.isGetter).variable,
unitElement.types[0].fields[0],
unitElement.functions[0].localVariables[0],
@@ -354,6 +356,52 @@
}
}
+ test_perform_configurations_export() {
+ context.declaredVariables.define('dart.library.io', 'true');
+ context.declaredVariables.define('dart.library.html', 'true');
+ newSource('/foo.dart', '');
+ var foo_io = newSource('/foo_io.dart', '');
+ newSource('/foo_html.dart', '');
+ var testSource = newSource(
+ '/test.dart',
+ r'''
+export 'foo.dart'
+ if (dart.library.io) 'foo_io.dart'
+ if (dart.library.html) 'foo_html.dart';
+''');
+ // Perform the task.
+ computeResult(testSource, LIBRARY_ELEMENT2,
+ matcher: isBuildDirectiveElementsTask);
+ LibraryElement testLibrary = outputs[LIBRARY_ELEMENT2];
+ // Validate the export element.
+ ExportElement export = testLibrary.exports[0];
+ expect(export.exportedLibrary.source, foo_io);
+ expect(export.uri, 'foo_io.dart');
+ }
+
+ test_perform_configurations_import() {
+ context.declaredVariables.define('dart.library.io', 'true');
+ context.declaredVariables.define('dart.library.html', 'true');
+ newSource('/foo.dart', '');
+ var foo_io = newSource('/foo_io.dart', '');
+ newSource('/foo_html.dart', '');
+ var testSource = newSource(
+ '/test.dart',
+ r'''
+import 'foo.dart'
+ if (dart.library.io) 'foo_io.dart'
+ if (dart.library.html) 'foo_html.dart';
+''');
+ // Perform the task.
+ computeResult(testSource, LIBRARY_ELEMENT2,
+ matcher: isBuildDirectiveElementsTask);
+ LibraryElement testLibrary = outputs[LIBRARY_ELEMENT2];
+ // Validate the import element.
+ ImportElement import = testLibrary.imports[0];
+ expect(import.importedLibrary.source, foo_io);
+ expect(import.uri, 'foo_io.dart');
+ }
+
test_perform_dartCoreContext() {
List<Source> sources = newSources({'/libA.dart': ''});
Source source = sources[0];
@@ -3237,6 +3285,118 @@
expect(outputs[UNITS], hasLength(2));
}
+ test_perform_library_configurations_bool1() {
+ context.declaredVariables.define('dart.library.io', 'true');
+ newSource('/foo.dart', '');
+ newSource('/foo_io.dart', '');
+ newSource('/foo_html.dart', '');
+ newSource('/bar.dart', '');
+ newSource('/bar_io.dart', '');
+ newSource('/bar_html.dart', '');
+ _performParseTask(r'''
+import 'foo.dart'
+ if (dart.library.io) 'foo_io.dart'
+ if (dart.library.html) 'foo_html.dart';
+export 'bar.dart'
+ if (dart.library.io) 'bar_io.dart'
+ if (dart.library.html) 'bar_html.dart';
+''');
+ var unit = outputs[PARSED_UNIT] as CompilationUnit;
+
+ var imported = outputs[IMPORTED_LIBRARIES] as List<Source>;
+ _assertContainsOnlyShortName(imported, 'foo_io.dart');
+
+ var import = unit.directives[0] as ImportDirective;
+ expect(import.uriSource.shortName, 'foo.dart');
+ expect(import.selectedSource.shortName, 'foo_io.dart');
+ expect(import.configurations[0].uriSource.shortName, 'foo_io.dart');
+ expect(import.configurations[1].uriSource.shortName, 'foo_html.dart');
+
+ var exported = outputs[EXPORTED_LIBRARIES] as List<Source>;
+ _assertContainsOnlyShortName(exported, 'bar_io.dart');
+
+ var export = unit.directives[1] as ExportDirective;
+ expect(export.uriSource.shortName, 'bar.dart');
+ expect(export.selectedSource.shortName, 'bar_io.dart');
+ expect(export.configurations[0].uriSource.shortName, 'bar_io.dart');
+ expect(export.configurations[1].uriSource.shortName, 'bar_html.dart');
+
+ var refSources = outputs[REFERENCED_SOURCES] as List<Source>;
+ var refNames = refSources.map((source) => source.shortName).toList();
+ expect(refNames, contains('test.dart'));
+ expect(refNames, contains('foo.dart'));
+ expect(refNames, contains('foo_io.dart'));
+ expect(refNames, contains('foo_html.dart'));
+ expect(refNames, contains('bar.dart'));
+ expect(refNames, contains('bar_io.dart'));
+ expect(refNames, contains('bar_html.dart'));
+ }
+
+ test_perform_library_configurations_bool2() {
+ context.declaredVariables.define('dart.library.html', 'true');
+ newSource('/foo.dart', '');
+ newSource('/foo_io.dart', '');
+ newSource('/foo_html.dart', '');
+ _performParseTask(r'''
+import 'foo.dart'
+ if (dart.library.io) 'foo_io.dart'
+ if (dart.library.html) 'foo_html.dart';
+''');
+ var imported = outputs[IMPORTED_LIBRARIES] as List<Source>;
+ _assertContainsOnlyShortName(imported, 'foo_html.dart');
+ }
+
+ test_perform_library_configurations_default() {
+ context.declaredVariables.define('dart.library.io', 'false');
+ newSource('/foo.dart', '');
+ newSource('/foo_io.dart', '');
+ newSource('/foo_html.dart', '');
+ _performParseTask(r'''
+import 'foo.dart'
+ if (dart.library.io) 'foo_io.dart'
+ if (dart.library.html) 'foo_html.dart';
+''');
+ var imported = outputs[IMPORTED_LIBRARIES] as List<Source>;
+ _assertContainsOnlyShortName(imported, 'foo.dart');
+ }
+
+ test_perform_library_configurations_preferFirst() {
+ context.declaredVariables.define('dart.library.io', 'true');
+ context.declaredVariables.define('dart.library.html', 'true');
+ newSource('/foo.dart', '');
+ newSource('/foo_io.dart', '');
+ newSource('/foo_html.dart', '');
+ _performParseTask(r'''
+import 'foo.dart'
+ if (dart.library.io) 'foo_io.dart'
+ if (dart.library.html) 'foo_html.dart';
+''');
+
+ var imported = outputs[IMPORTED_LIBRARIES] as List<Source>;
+ _assertContainsOnlyShortName(imported, 'foo_io.dart');
+
+ var unit = outputs[PARSED_UNIT] as CompilationUnit;
+ var import = unit.directives[0] as ImportDirective;
+ expect(import.uriSource.shortName, 'foo.dart');
+ expect(import.selectedSource.shortName, 'foo_io.dart');
+ expect(import.configurations[0].uriSource.shortName, 'foo_io.dart');
+ expect(import.configurations[1].uriSource.shortName, 'foo_html.dart');
+ }
+
+ test_perform_library_configurations_value() {
+ context.declaredVariables.define('dart.platform', 'Windows');
+ newSource('/foo.dart', '');
+ newSource('/foo_posix.dart', '');
+ newSource('/foo_windows.dart', '');
+ _performParseTask(r'''
+import 'foo.dart'
+ if (dart.platform == 'Posix') 'foo_posix.dart'
+ if (dart.platform == 'Windows') 'foo_windows.dart';
+''');
+ var imported = outputs[IMPORTED_LIBRARIES] as List<Source>;
+ _assertContainsOnlyShortName(imported, 'foo_windows.dart');
+ }
+
test_perform_library_selfReferenceAsPart() {
_performParseTask(r'''
library lib;
@@ -3263,6 +3423,20 @@
expect(outputs[UNITS], hasLength(1));
}
+ /**
+ * Assert that [sources] contains either just a source with the given
+ * [expectedShortName], or it and the `dart:core` source.
+ */
+ void _assertContainsOnlyShortName(
+ List<Source> sources, String expectedShortName) {
+ Iterable<String> shortNames = sources.map((s) => s.shortName);
+ if (shortNames.length == 2) {
+ expect(shortNames, unorderedEquals(['core.dart', expectedShortName]));
+ } else {
+ expect(shortNames, unorderedEquals([expectedShortName]));
+ }
+ }
+
void _performParseTask(String content) {
if (content == null) {
source = resourceProvider.getFile('/test.dart').createSource();
diff --git a/pkg/analyzer/test/src/task/dart_work_manager_test.dart b/pkg/analyzer/test/src/task/dart_work_manager_test.dart
index f1d05e4..84f3f63 100644
--- a/pkg/analyzer/test/src/task/dart_work_manager_test.dart
+++ b/pkg/analyzer/test/src/task/dart_work_manager_test.dart
@@ -5,6 +5,7 @@
library analyzer.test.src.task.dart_work_manager_test;
import 'package:analyzer/dart/ast/ast.dart';
+import 'package:analyzer/error/error.dart' show AnalysisError;
import 'package:analyzer/exception/exception.dart';
import 'package:analyzer/src/context/cache.dart';
import 'package:analyzer/src/dart/scanner/scanner.dart' show ScannerErrorCode;
@@ -14,7 +15,6 @@
CacheState,
ChangeNoticeImpl,
InternalAnalysisContext;
-import 'package:analyzer/src/generated/error.dart' show AnalysisError;
import 'package:analyzer/src/generated/sdk.dart';
import 'package:analyzer/src/generated/source.dart';
import 'package:analyzer/src/generated/testing/ast_factory.dart';
@@ -655,7 +655,7 @@
when(context.prioritySources).thenReturn(<Source>[]);
when(context.shouldErrorsBeAnalyzed(anyObject)).thenReturn(false);
// library1 parts
- manager.resultsComputed(library1, {
+ manager.resultsComputed(library1, <ResultDescriptor, dynamic>{
INCLUDED_PARTS: [part1, part2],
SOURCE_KIND: SourceKind.LIBRARY
});
@@ -665,7 +665,7 @@
expect(manager.libraryPartsMap[library1], [part1, part2]);
expect(manager.libraryPartsMap[library2], isNull);
// library2 parts
- manager.resultsComputed(library2, {
+ manager.resultsComputed(library2, <ResultDescriptor, dynamic>{
INCLUDED_PARTS: [part2, part3],
SOURCE_KIND: SourceKind.LIBRARY
});
@@ -787,8 +787,10 @@
Source part = new TestSource('part.dart');
expect(manager.libraryPartsMap, isEmpty);
// part.dart parsed, no changes is the map of libraries
- manager.resultsComputed(
- part, {SOURCE_KIND: SourceKind.PART, INCLUDED_PARTS: <Source>[]});
+ manager.resultsComputed(part, <ResultDescriptor, dynamic>{
+ SOURCE_KIND: SourceKind.PART,
+ INCLUDED_PARTS: <Source>[]
+ });
expect(manager.libraryPartsMap, isEmpty);
}
diff --git a/pkg/analyzer/test/src/task/html_work_manager_test.dart b/pkg/analyzer/test/src/task/html_work_manager_test.dart
index 2c6e410..55698a0 100644
--- a/pkg/analyzer/test/src/task/html_work_manager_test.dart
+++ b/pkg/analyzer/test/src/task/html_work_manager_test.dart
@@ -4,8 +4,10 @@
library analyzer.test.src.task.html_work_manager_test;
+import 'package:analyzer/error/error.dart' show AnalysisError;
import 'package:analyzer/exception/exception.dart';
import 'package:analyzer/src/context/cache.dart';
+import 'package:analyzer/src/error/codes.dart' show HtmlErrorCode;
import 'package:analyzer/src/generated/engine.dart'
show
AnalysisEngine,
@@ -14,8 +16,6 @@
CacheState,
ChangeNoticeImpl,
InternalAnalysisContext;
-import 'package:analyzer/src/generated/error.dart'
- show AnalysisError, HtmlErrorCode;
import 'package:analyzer/src/generated/source.dart';
import 'package:analyzer/src/task/html.dart';
import 'package:analyzer/src/task/html_work_manager.dart';
diff --git a/pkg/analyzer/test/src/task/inputs_test.dart b/pkg/analyzer/test/src/task/inputs_test.dart
index ed4ecb3..33bcbee 100644
--- a/pkg/analyzer/test/src/task/inputs_test.dart
+++ b/pkg/analyzer/test/src/task/inputs_test.dart
@@ -123,7 +123,7 @@
@reflectiveTest
class ListTaskInputImplTest extends EngineTestCase {
static final AnalysisTarget target = new TestSource();
- static final result1 =
+ static final ResultDescriptor<List<AnalysisTarget>> result1 =
new ResultDescriptorImpl<List<AnalysisTarget>>('result1', null);
static final result2 = new ResultDescriptorImpl<int>('result2', null);
@@ -897,7 +897,7 @@
test_currentResult_afterTwoMoveNext_withConstantInput() {
ConstantTaskInput<int> constantInput = new ConstantTaskInput<int>(11);
- Map<String, TaskInput> inputDescriptors = {
+ Map<String, TaskInput> inputDescriptors = <String, TaskInput>{
'one': input1,
'constant': constantInput,
'two': input2
@@ -947,7 +947,7 @@
test_currentTarget_afterTwoMoveNext_withConstantInput() {
ConstantTaskInput<int> constantInput = new ConstantTaskInput<int>(11);
- Map<String, TaskInput> inputDescriptors = {
+ Map<String, TaskInput> inputDescriptors = <String, TaskInput>{
'one': input1,
'constant': constantInput,
'two': input2
diff --git a/pkg/analyzer/test/src/task/options_test.dart b/pkg/analyzer/test/src/task/options_test.dart
index 4b2e2a9..def44fd 100644
--- a/pkg/analyzer/test/src/task/options_test.dart
+++ b/pkg/analyzer/test/src/task/options_test.dart
@@ -10,6 +10,8 @@
import 'package:analyzer/src/context/context.dart';
import 'package:analyzer/src/generated/engine.dart';
import 'package:analyzer/src/generated/source.dart';
+import 'package:analyzer/src/task/options.dart'
+ show CONFIGURED_ERROR_PROCESSORS;
import 'package:analyzer/src/task/options.dart';
import 'package:analyzer/task/general.dart';
import 'package:analyzer/task/model.dart';
diff --git a/pkg/analyzer/test/src/task/options_work_manager_test.dart b/pkg/analyzer/test/src/task/options_work_manager_test.dart
index 707d630..d52286b 100644
--- a/pkg/analyzer/test/src/task/options_work_manager_test.dart
+++ b/pkg/analyzer/test/src/task/options_work_manager_test.dart
@@ -4,8 +4,10 @@
library analyzer.test.src.task.options_work_manager_test;
+import 'package:analyzer/error/error.dart' show AnalysisError;
import 'package:analyzer/exception/exception.dart';
import 'package:analyzer/src/context/cache.dart';
+import 'package:analyzer/src/error/codes.dart' show AnalysisOptionsErrorCode;
import 'package:analyzer/src/generated/engine.dart'
show
AnalysisEngine,
@@ -14,8 +16,6 @@
CacheState,
ChangeNoticeImpl,
InternalAnalysisContext;
-import 'package:analyzer/src/generated/error.dart'
- show AnalysisError, AnalysisOptionsErrorCode;
import 'package:analyzer/src/generated/source.dart';
import 'package:analyzer/src/task/options.dart';
import 'package:analyzer/src/task/options_work_manager.dart';
diff --git a/pkg/analyzer/test/src/task/strong/checker_test.dart b/pkg/analyzer/test/src/task/strong/checker_test.dart
index 2cdb1bf..ae8ba3a 100644
--- a/pkg/analyzer/test/src/task/strong/checker_test.dart
+++ b/pkg/analyzer/test/src/task/strong/checker_test.dart
@@ -499,6 +499,121 @@
''');
}
+ void test_covariantOverride() {
+ _addMetaLibrary();
+ checkFile(r'''
+import 'meta.dart';
+class C {
+ num f(num x) => x;
+}
+class D extends C {
+ int f(@checked int x) => x;
+}
+class E extends D {
+ int f(Object x) => /*info:DOWN_CAST_IMPLICIT*/x;
+}
+class F extends E {
+ int f(@checked int x) => x;
+}
+class G extends E implements D {}
+
+class D_error extends C {
+ /*error:INVALID_METHOD_OVERRIDE*/int f(int x) => x;
+}
+class E_error extends D {
+ /*error:INVALID_METHOD_OVERRIDE*/int f(@checked double x) => 0;
+}
+class F_error extends E {
+ /*error:INVALID_METHOD_OVERRIDE*/int f(@checked double x) => 0;
+}
+class G_error extends E implements D {
+ /*error:INVALID_METHOD_OVERRIDE*/int f(@checked double x) => 0;
+}
+ ''');
+ }
+
+ void test_covariantOverride_fields() {
+ _addMetaLibrary();
+ checkFile(r'''
+import 'meta.dart';
+class A {
+ get foo => '';
+ set foo(_) {}
+}
+
+class B extends A {
+ @checked num foo;
+}
+class C extends A {
+ @checked @virtual num foo;
+}
+class D extends C {
+ @virtual int foo;
+}
+class E extends D {
+ @virtual /*error:INVALID_METHOD_OVERRIDE*/num foo;
+}
+ ''');
+ }
+
+ void test_covariantOverride_leastUpperBound() {
+ _addMetaLibrary();
+ checkFile(r'''
+import "meta.dart";
+abstract class Top {}
+abstract class Left implements Top {}
+abstract class Right implements Top {}
+abstract class Bottom implements Left, Right {}
+
+abstract class TakesLeft {
+ m(Left x);
+}
+abstract class TakesRight {
+ m(Right x);
+}
+abstract class TakesTop implements TakesLeft, TakesRight {
+ m(Top x); // works today
+}
+abstract class TakesBottom implements TakesLeft, TakesRight {
+ // LUB(Left, Right) == Top, so this is an implicit cast from Top to Bottom.
+ m(@checked Bottom x);
+}
+ ''');
+ }
+
+ void test_covariantOverride_markerIsInherited() {
+ _addMetaLibrary();
+ checkFile(r'''
+import 'meta.dart';
+class C {
+ num f(@checked num x) => x;
+}
+class D extends C {
+ int f(int x) => x;
+}
+class E extends D {
+ int f(Object x) => /*info:DOWN_CAST_IMPLICIT*/x;
+}
+class F extends E {
+ int f(int x) => x;
+}
+class G extends E implements D {}
+
+class D_error extends C {
+ /*error:INVALID_METHOD_OVERRIDE*/int f(String x) => 0;
+}
+class E_error extends D {
+ /*error:INVALID_METHOD_OVERRIDE*/int f(double x) => 0;
+}
+class F_error extends E {
+ /*error:INVALID_METHOD_OVERRIDE*/int f(double x) => 0;
+}
+class G_error extends E implements D {
+ /*error:INVALID_METHOD_OVERRIDE*/int f(double x) => 0;
+}
+ ''');
+ }
+
void test_dynamicInvocation() {
checkFile('''
typedef dynamic A(dynamic x);
@@ -647,6 +762,36 @@
''');
}
+ void test_fieldOverride_virtual() {
+ _addMetaLibrary();
+ checkFile(r'''
+import 'meta.dart';
+class C {
+ @virtual int x;
+}
+class OverrideGetter extends C {
+ int get x => 42;
+}
+class OverrideSetter extends C {
+ set x(int v) {}
+}
+class OverrideBoth extends C {
+ int get x => 42;
+ set x(int v) {}
+}
+class OverrideWithField extends C {
+ int x;
+
+ // expose the hidden storage slot
+ int get superX => super.x;
+ set superX(int v) { super.x = v; }
+}
+class VirtualNotInherited extends OverrideWithField {
+ /*error:INVALID_FIELD_OVERRIDE*/int x;
+}
+ ''');
+ }
+
void test_fieldSetterOverride() {
checkFile('''
class A {}
@@ -3009,6 +3154,37 @@
check(implicitCasts: false);
}
+ void test_overrideNarrowsType_noDuplicateError() {
+ // Regression test for https://github.com/dart-lang/sdk/issues/25232
+ _addMetaLibrary();
+ checkFile(r'''
+import 'meta.dart';
+abstract class A { void test(A arg) { } }
+abstract class B extends A {
+ /*error:INVALID_METHOD_OVERRIDE*/void test(B arg) { }
+}
+abstract class X implements A { }
+class C extends B with X { }
+
+// We treat "implements A" as asking for another check.
+// This feels inconsistent to me.
+class D /*error:INVALID_METHOD_OVERRIDE_FROM_BASE*/extends B implements A { }
+ ''');
+ }
+
+ void test_overrideNarrowsType_legalWithChecked() {
+ // Regression test for https://github.com/dart-lang/sdk/issues/25232
+ _addMetaLibrary();
+ checkFile(r'''
+import 'meta.dart';
+abstract class A { void test(A arg) { } }
+abstract class B extends A { void test(@checked B arg) { } }
+abstract class X implements A { }
+class C extends B with X { }
+class D extends B implements A { }
+ ''');
+ }
+
void test_privateOverride() {
addFile(
'''
@@ -3734,3 +3910,14 @@
''');
}
}
+
+void _addMetaLibrary() {
+ addFile(r'''
+library meta;
+class _Checked { const _Checked(); }
+const Object checked = const _Checked();
+
+class _Virtual { const _Virtual(); }
+const Object virtual = const _Virtual();
+ ''', name: '/meta.dart');
+}
diff --git a/pkg/analyzer/test/src/task/strong/inferred_type_test.dart b/pkg/analyzer/test/src/task/strong/inferred_type_test.dart
index 0490b74..c45e27b 100644
--- a/pkg/analyzer/test/src/task/strong/inferred_type_test.dart
+++ b/pkg/analyzer/test/src/task/strong/inferred_type_test.dart
@@ -888,7 +888,7 @@
checkFile('''
void main() {
List<int> l;
- l = /*info:INFERRED_TYPE_LITERAL*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/"hello"];
+ l = /*info:INFERRED_TYPE_LITERAL,error:COULD_NOT_INFER*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/"hello"];
l = (l = /*info:INFERRED_TYPE_LITERAL*/[1]);
}
''');
@@ -899,8 +899,8 @@
import 'dart:async';
Future test() async {
dynamic d;
- List<int> l0 = await /*info:INFERRED_TYPE_LITERAL*/[/*info:DYNAMIC_CAST*/d];
- List<int> l1 = await /*info:INFERRED_TYPE_ALLOCATION*/new Future.value(/*info:INFERRED_TYPE_LITERAL*/[/*info:DYNAMIC_CAST*/d]);
+ List<int> l0 = await /*info:INFERRED_TYPE_LITERAL,error:COULD_NOT_INFER*/[/*info:DYNAMIC_CAST*/d];
+ List<int> l1 = await /*info:INFERRED_TYPE_ALLOCATION*/new Future.value(/*info:INFERRED_TYPE_LITERAL,error:COULD_NOT_INFER*/[/*info:DYNAMIC_CAST*/d]);
}
''');
}
@@ -949,30 +949,30 @@
void main() {
new F0(/*info:INFERRED_TYPE_LITERAL*/[]);
new F0(/*info:INFERRED_TYPE_LITERAL*/[3]);
- new F0(/*info:INFERRED_TYPE_LITERAL*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/"hello"]);
- new F0(/*info:INFERRED_TYPE_LITERAL*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/"hello",
+ new F0(/*info:INFERRED_TYPE_LITERAL,error:COULD_NOT_INFER*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/"hello"]);
+ new F0(/*info:INFERRED_TYPE_LITERAL,error:COULD_NOT_INFER*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/"hello",
3]);
new F1(a: /*info:INFERRED_TYPE_LITERAL*/[]);
new F1(a: /*info:INFERRED_TYPE_LITERAL*/[3]);
- new F1(a: /*info:INFERRED_TYPE_LITERAL*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/"hello"]);
- new F1(a: /*info:INFERRED_TYPE_LITERAL*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/"hello", 3]);
+ new F1(a: /*info:INFERRED_TYPE_LITERAL,error:COULD_NOT_INFER*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/"hello"]);
+ new F1(a: /*info:INFERRED_TYPE_LITERAL,error:COULD_NOT_INFER*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/"hello", 3]);
new F2(/*info:INFERRED_TYPE_LITERAL*/[]);
new F2(/*info:INFERRED_TYPE_LITERAL*/[3]);
- new F2(/*info:INFERRED_TYPE_LITERAL*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/"hello"]);
- new F2(/*info:INFERRED_TYPE_LITERAL*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/"hello", 3]);
+ new F2(/*info:INFERRED_TYPE_LITERAL,error:COULD_NOT_INFER*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/"hello"]);
+ new F2(/*info:INFERRED_TYPE_LITERAL,error:COULD_NOT_INFER*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/"hello", 3]);
new F3(/*info:INFERRED_TYPE_LITERAL*/[]);
new F3(/*info:INFERRED_TYPE_LITERAL*/[/*info:INFERRED_TYPE_LITERAL*/[3]]);
- new F3(/*info:INFERRED_TYPE_LITERAL*/[/*info:INFERRED_TYPE_LITERAL*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/"hello"]]);
- new F3(/*info:INFERRED_TYPE_LITERAL*/[/*info:INFERRED_TYPE_LITERAL*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/"hello"],
+ new F3(/*info:INFERRED_TYPE_LITERAL*/[/*info:INFERRED_TYPE_LITERAL,error:COULD_NOT_INFER*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/"hello"]]);
+ new F3(/*info:INFERRED_TYPE_LITERAL*/[/*info:INFERRED_TYPE_LITERAL,error:COULD_NOT_INFER*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/"hello"],
/*info:INFERRED_TYPE_LITERAL*/[3]]);
new F4(a: /*info:INFERRED_TYPE_LITERAL*/[]);
new F4(a: /*info:INFERRED_TYPE_LITERAL*/[/*info:INFERRED_TYPE_LITERAL*/[3]]);
- new F4(a: /*info:INFERRED_TYPE_LITERAL*/[/*info:INFERRED_TYPE_LITERAL*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/"hello"]]);
- new F4(a: /*info:INFERRED_TYPE_LITERAL*/[/*info:INFERRED_TYPE_LITERAL*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/"hello"],
+ new F4(a: /*info:INFERRED_TYPE_LITERAL*/[/*info:INFERRED_TYPE_LITERAL,error:COULD_NOT_INFER*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/"hello"]]);
+ new F4(a: /*info:INFERRED_TYPE_LITERAL*/[/*info:INFERRED_TYPE_LITERAL,error:COULD_NOT_INFER*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/"hello"],
/*info:INFERRED_TYPE_LITERAL*/[3]]);
}
''');
@@ -988,28 +988,28 @@
void main() {
f0(/*info:INFERRED_TYPE_LITERAL*/[]);
f0(/*info:INFERRED_TYPE_LITERAL*/[3]);
- f0(/*info:INFERRED_TYPE_LITERAL*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/"hello"]);
- f0(/*info:INFERRED_TYPE_LITERAL*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/"hello", 3]);
+ f0(/*info:INFERRED_TYPE_LITERAL,error:COULD_NOT_INFER*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/"hello"]);
+ f0(/*info:INFERRED_TYPE_LITERAL,error:COULD_NOT_INFER*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/"hello", 3]);
f1(a: /*info:INFERRED_TYPE_LITERAL*/[]);
f1(a: /*info:INFERRED_TYPE_LITERAL*/[3]);
- f1(a: /*info:INFERRED_TYPE_LITERAL*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/"hello"]);
- f1(a: /*info:INFERRED_TYPE_LITERAL*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/"hello", 3]);
+ f1(a: /*info:INFERRED_TYPE_LITERAL,error:COULD_NOT_INFER*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/"hello"]);
+ f1(a: /*info:INFERRED_TYPE_LITERAL,error:COULD_NOT_INFER*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/"hello", 3]);
f2(/*info:INFERRED_TYPE_LITERAL*/[]);
f2(/*info:INFERRED_TYPE_LITERAL*/[3]);
- f2(/*info:INFERRED_TYPE_LITERAL*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/"hello"]);
- f2(/*info:INFERRED_TYPE_LITERAL*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/"hello", 3]);
+ f2(/*info:INFERRED_TYPE_LITERAL,error:COULD_NOT_INFER*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/"hello"]);
+ f2(/*info:INFERRED_TYPE_LITERAL,error:COULD_NOT_INFER*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/"hello", 3]);
f3(/*info:INFERRED_TYPE_LITERAL*/[]);
f3(/*info:INFERRED_TYPE_LITERAL*/[/*info:INFERRED_TYPE_LITERAL*/[3]]);
- f3(/*info:INFERRED_TYPE_LITERAL*/[/*info:INFERRED_TYPE_LITERAL*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/"hello"]]);
- f3(/*info:INFERRED_TYPE_LITERAL*/[/*info:INFERRED_TYPE_LITERAL*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/"hello"], /*info:INFERRED_TYPE_LITERAL*/[3]]);
+ f3(/*info:INFERRED_TYPE_LITERAL*/[/*info:INFERRED_TYPE_LITERAL,error:COULD_NOT_INFER*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/"hello"]]);
+ f3(/*info:INFERRED_TYPE_LITERAL*/[/*info:INFERRED_TYPE_LITERAL,error:COULD_NOT_INFER*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/"hello"], /*info:INFERRED_TYPE_LITERAL*/[3]]);
f4(a: /*info:INFERRED_TYPE_LITERAL*/[]);
f4(a: /*info:INFERRED_TYPE_LITERAL*/[/*info:INFERRED_TYPE_LITERAL*/[3]]);
- f4(a: /*info:INFERRED_TYPE_LITERAL*/[/*info:INFERRED_TYPE_LITERAL*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/"hello"]]);
- f4(a: /*info:INFERRED_TYPE_LITERAL*/[/*info:INFERRED_TYPE_LITERAL*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/"hello"], /*info:INFERRED_TYPE_LITERAL*/[3]]);
+ f4(a: /*info:INFERRED_TYPE_LITERAL*/[/*info:INFERRED_TYPE_LITERAL,error:COULD_NOT_INFER*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/"hello"]]);
+ f4(a: /*info:INFERRED_TYPE_LITERAL*/[/*info:INFERRED_TYPE_LITERAL,error:COULD_NOT_INFER*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/"hello"], /*info:INFERRED_TYPE_LITERAL*/[3]]);
}
''');
}
@@ -1037,8 +1037,8 @@
Function2<int, List<String>> l0 = /*info:INFERRED_TYPE_CLOSURE*/(int x) => null;
Function2<int, List<String>> l1 = (int x) => /*info:INFERRED_TYPE_LITERAL*/["hello"];
Function2<int, List<String>> l2 = /*error:INVALID_ASSIGNMENT*/(String x) => /*info:INFERRED_TYPE_LITERAL*/["hello"];
- Function2<int, List<String>> l3 = (int x) => /*info:INFERRED_TYPE_LITERAL*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/3];
- Function2<int, List<String>> l4 = /*info:INFERRED_TYPE_CLOSURE*/(int x) {return /*info:INFERRED_TYPE_LITERAL*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/3];};
+ Function2<int, List<String>> l3 = (int x) => /*info:INFERRED_TYPE_LITERAL,error:COULD_NOT_INFER*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/3];
+ Function2<int, List<String>> l4 = /*info:INFERRED_TYPE_CLOSURE*/(int x) {return /*info:INFERRED_TYPE_LITERAL,error:COULD_NOT_INFER*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/3];};
}
{
Function2<int, int> l0 = /*info:INFERRED_TYPE_CLOSURE*/(x) => x;
@@ -1093,42 +1093,42 @@
void main() {
new F0<int>(/*info:INFERRED_TYPE_LITERAL*/[]);
new F0<int>(/*info:INFERRED_TYPE_LITERAL*/[3]);
- new F0<int>(/*info:INFERRED_TYPE_LITERAL*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/"hello"]);
- new F0<int>(/*info:INFERRED_TYPE_LITERAL*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/"hello",
+ new F0<int>(/*info:INFERRED_TYPE_LITERAL,error:COULD_NOT_INFER*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/"hello"]);
+ new F0<int>(/*info:INFERRED_TYPE_LITERAL,error:COULD_NOT_INFER*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/"hello",
3]);
new F1<int>(a: /*info:INFERRED_TYPE_LITERAL*/[]);
new F1<int>(a: /*info:INFERRED_TYPE_LITERAL*/[3]);
- new F1<int>(a: /*info:INFERRED_TYPE_LITERAL*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/"hello"]);
- new F1<int>(a: /*info:INFERRED_TYPE_LITERAL*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/"hello", 3]);
+ new F1<int>(a: /*info:INFERRED_TYPE_LITERAL,error:COULD_NOT_INFER*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/"hello"]);
+ new F1<int>(a: /*info:INFERRED_TYPE_LITERAL,error:COULD_NOT_INFER*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/"hello", 3]);
new F2<int>(/*info:INFERRED_TYPE_LITERAL*/[]);
new F2<int>(/*info:INFERRED_TYPE_LITERAL*/[3]);
- new F2<int>(/*info:INFERRED_TYPE_LITERAL*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/"hello"]);
- new F2<int>(/*info:INFERRED_TYPE_LITERAL*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/"hello", 3]);
+ new F2<int>(/*info:INFERRED_TYPE_LITERAL,error:COULD_NOT_INFER*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/"hello"]);
+ new F2<int>(/*info:INFERRED_TYPE_LITERAL,error:COULD_NOT_INFER*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/"hello", 3]);
new F3<int>(/*info:INFERRED_TYPE_LITERAL*/[]);
new F3<int>(/*info:INFERRED_TYPE_LITERAL*/[/*info:INFERRED_TYPE_LITERAL*/[3]]);
- new F3<int>(/*info:INFERRED_TYPE_LITERAL*/[/*info:INFERRED_TYPE_LITERAL*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/"hello"]]);
- new F3<int>(/*info:INFERRED_TYPE_LITERAL*/[/*info:INFERRED_TYPE_LITERAL*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/"hello"],
+ new F3<int>(/*info:INFERRED_TYPE_LITERAL*/[/*info:INFERRED_TYPE_LITERAL,error:COULD_NOT_INFER*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/"hello"]]);
+ new F3<int>(/*info:INFERRED_TYPE_LITERAL*/[/*info:INFERRED_TYPE_LITERAL,error:COULD_NOT_INFER*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/"hello"],
/*info:INFERRED_TYPE_LITERAL*/[3]]);
new F4<int>(a: /*info:INFERRED_TYPE_LITERAL*/[]);
new F4<int>(a: /*info:INFERRED_TYPE_LITERAL*/[/*info:INFERRED_TYPE_LITERAL*/[3]]);
- new F4<int>(a: /*info:INFERRED_TYPE_LITERAL*/[/*info:INFERRED_TYPE_LITERAL*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/"hello"]]);
- new F4<int>(a: /*info:INFERRED_TYPE_LITERAL*/[/*info:INFERRED_TYPE_LITERAL*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/"hello"],
+ new F4<int>(a: /*info:INFERRED_TYPE_LITERAL*/[/*info:INFERRED_TYPE_LITERAL,error:COULD_NOT_INFER*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/"hello"]]);
+ new F4<int>(a: /*info:INFERRED_TYPE_LITERAL*/[/*info:INFERRED_TYPE_LITERAL,error:COULD_NOT_INFER*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/"hello"],
/*info:INFERRED_TYPE_LITERAL*/[3]]);
new F3(/*info:INFERRED_TYPE_LITERAL*/[]);
- new F3(/*info:INFERRED_TYPE_LITERAL*/[/*info:INFERRED_TYPE_LITERAL*/[3]]);
- new F3(/*info:INFERRED_TYPE_LITERAL*/[/*info:INFERRED_TYPE_LITERAL*/["hello"]]);
- new F3(/*info:INFERRED_TYPE_LITERAL*/[/*info:INFERRED_TYPE_LITERAL*/["hello"],
+ /*info:INFERRED_TYPE_ALLOCATION*/new F3(/*info:INFERRED_TYPE_LITERAL*/[/*info:INFERRED_TYPE_LITERAL*/[3]]);
+ /*info:INFERRED_TYPE_ALLOCATION*/new F3(/*info:INFERRED_TYPE_LITERAL*/[/*info:INFERRED_TYPE_LITERAL*/["hello"]]);
+ /*info:INFERRED_TYPE_ALLOCATION*/new F3(/*info:INFERRED_TYPE_LITERAL*/[/*info:INFERRED_TYPE_LITERAL*/["hello"],
/*info:INFERRED_TYPE_LITERAL*/[3]]);
new F4(a: /*info:INFERRED_TYPE_LITERAL*/[]);
- new F4(a: /*info:INFERRED_TYPE_LITERAL*/[/*info:INFERRED_TYPE_LITERAL*/[3]]);
- new F4(a: /*info:INFERRED_TYPE_LITERAL*/[/*info:INFERRED_TYPE_LITERAL*/["hello"]]);
- new F4(a: /*info:INFERRED_TYPE_LITERAL*/[/*info:INFERRED_TYPE_LITERAL*/["hello"],
+ /*info:INFERRED_TYPE_ALLOCATION*/new F4(a: /*info:INFERRED_TYPE_LITERAL*/[/*info:INFERRED_TYPE_LITERAL*/[3]]);
+ /*info:INFERRED_TYPE_ALLOCATION*/new F4(a: /*info:INFERRED_TYPE_LITERAL*/[/*info:INFERRED_TYPE_LITERAL*/["hello"]]);
+ /*info:INFERRED_TYPE_ALLOCATION*/new F4(a: /*info:INFERRED_TYPE_LITERAL*/[/*info:INFERRED_TYPE_LITERAL*/["hello"],
/*info:INFERRED_TYPE_LITERAL*/[3]]);
}
''');
@@ -1161,8 +1161,8 @@
v = /*info:INFERRED_TYPE_CLOSURE*//*<T>*/(int x) => null;
v = /*<T>*/(int x) => /*info:INFERRED_TYPE_LITERAL*/["hello"];
v = /*error:INVALID_ASSIGNMENT*//*<T>*/(String x) => /*info:INFERRED_TYPE_LITERAL*/["hello"];
- v = /*<T>*/(int x) => /*info:INFERRED_TYPE_LITERAL*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/3];
- v = /*info:INFERRED_TYPE_CLOSURE*//*<T>*/(int x) {return /*info:INFERRED_TYPE_LITERAL*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/3];};
+ v = /*<T>*/(int x) => /*info:INFERRED_TYPE_LITERAL,error:COULD_NOT_INFER*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/3];
+ v = /*info:INFERRED_TYPE_CLOSURE*//*<T>*/(int x) {return /*info:INFERRED_TYPE_LITERAL,error:COULD_NOT_INFER*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/3];};
}
{
int int2int/*<S>*/(int x) => null;
@@ -1283,8 +1283,8 @@
a: /*info:INFERRED_TYPE_LITERAL*/[3],
b: /*info:INFERRED_TYPE_LITERAL*/["hello"]);
A<int, String> a1 = /*info:INFERRED_TYPE_ALLOCATION*/new F(3, "hello",
- a: /*info:INFERRED_TYPE_LITERAL*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/"hello"],
- b: /*info:INFERRED_TYPE_LITERAL*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/3]);
+ a: /*info:INFERRED_TYPE_LITERAL,error:COULD_NOT_INFER*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/"hello"],
+ b: /*info:INFERRED_TYPE_LITERAL,error:COULD_NOT_INFER*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/3]);
A<int, String> a2 = /*info:INFERRED_TYPE_ALLOCATION*/new F.named(3, "hello", 3, "hello");
A<int, String> a3 = /*info:INFERRED_TYPE_ALLOCATION*/new F.named(3, "hello");
A<int, String> a4 = /*info:INFERRED_TYPE_ALLOCATION*/new /*error:COULD_NOT_INFER,error:COULD_NOT_INFER*/F.named(3, "hello",
@@ -1299,15 +1299,15 @@
void test_downwardsInferenceOnListLiterals_inferDownwards() {
checkFile('''
void foo([List<String> list1 = /*info:INFERRED_TYPE_LITERAL*/const [],
- List<String> list2 = /*info:INFERRED_TYPE_LITERAL*/const [/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE,error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/42]]) {
+ List<String> list2 = /*info:INFERRED_TYPE_LITERAL,error:COULD_NOT_INFER*/const [/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE,error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/42]]) {
}
void main() {
{
List<int> l0 = /*info:INFERRED_TYPE_LITERAL*/[];
List<int> l1 = /*info:INFERRED_TYPE_LITERAL*/[3];
- List<int> l2 = /*info:INFERRED_TYPE_LITERAL*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/"hello"];
- List<int> l3 = /*info:INFERRED_TYPE_LITERAL*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/"hello", 3];
+ List<int> l2 = /*info:INFERRED_TYPE_LITERAL,error:COULD_NOT_INFER*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/"hello"];
+ List<int> l3 = /*info:INFERRED_TYPE_LITERAL,error:COULD_NOT_INFER*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/"hello", 3];
}
{
List<dynamic> l0 = [];
@@ -1324,14 +1324,14 @@
{
Iterable<int> i0 = /*info:INFERRED_TYPE_LITERAL*/[];
Iterable<int> i1 = /*info:INFERRED_TYPE_LITERAL*/[3];
- Iterable<int> i2 = /*info:INFERRED_TYPE_LITERAL*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/"hello"];
- Iterable<int> i3 = /*info:INFERRED_TYPE_LITERAL*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/"hello", 3];
+ Iterable<int> i2 = /*info:INFERRED_TYPE_LITERAL,error:COULD_NOT_INFER*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/"hello"];
+ Iterable<int> i3 = /*info:INFERRED_TYPE_LITERAL,error:COULD_NOT_INFER*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/"hello", 3];
}
{
const List<int> c0 = /*info:INFERRED_TYPE_LITERAL*/const [];
const List<int> c1 = /*info:INFERRED_TYPE_LITERAL*/const [3];
- const List<int> c2 = /*info:INFERRED_TYPE_LITERAL*/const [/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE,error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/"hello"];
- const List<int> c3 = /*info:INFERRED_TYPE_LITERAL*/const [/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE,error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/"hello", 3];
+ const List<int> c2 = /*info:INFERRED_TYPE_LITERAL,error:COULD_NOT_INFER*/const [/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE,error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/"hello"];
+ const List<int> c3 = /*info:INFERRED_TYPE_LITERAL,error:COULD_NOT_INFER*/const [/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE,error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/"hello", 3];
}
}
''');
@@ -1399,7 +1399,7 @@
void test_downwardsInferenceOnMapLiterals() {
checkFile('''
void foo([Map<int, String> m1 = /*info:INFERRED_TYPE_LITERAL*/const {1: "hello"},
- Map<int, String> m2 = /*info:INFERRED_TYPE_LITERAL*/const {
+ Map<int, String> m2 = /*info:INFERRED_TYPE_LITERAL,error:COULD_NOT_INFER*/const {
// One error is from type checking and the other is from const evaluation.
/*error:MAP_KEY_TYPE_NOT_ASSIGNABLE,error:MAP_KEY_TYPE_NOT_ASSIGNABLE*/"hello":
"world"
@@ -1409,13 +1409,13 @@
{
Map<int, String> l0 = /*info:INFERRED_TYPE_LITERAL*/{};
Map<int, String> l1 = /*info:INFERRED_TYPE_LITERAL*/{3: "hello"};
- Map<int, String> l2 = /*info:INFERRED_TYPE_LITERAL*/{
+ Map<int, String> l2 = /*info:INFERRED_TYPE_LITERAL,error:COULD_NOT_INFER*/{
/*error:MAP_KEY_TYPE_NOT_ASSIGNABLE*/"hello": "hello"
};
- Map<int, String> l3 = /*info:INFERRED_TYPE_LITERAL*/{
+ Map<int, String> l3 = /*info:INFERRED_TYPE_LITERAL,error:COULD_NOT_INFER*/{
3: /*error:MAP_VALUE_TYPE_NOT_ASSIGNABLE*/3
};
- Map<int, String> l4 = /*info:INFERRED_TYPE_LITERAL*/{
+ Map<int, String> l4 = /*info:INFERRED_TYPE_LITERAL,error:COULD_NOT_INFER,error:COULD_NOT_INFER*/{
3: "hello",
/*error:MAP_KEY_TYPE_NOT_ASSIGNABLE*/"hello":
/*error:MAP_VALUE_TYPE_NOT_ASSIGNABLE*/3
@@ -1432,10 +1432,10 @@
Map<dynamic, String> l0 = /*info:INFERRED_TYPE_LITERAL*/{};
Map<dynamic, String> l1 = /*info:INFERRED_TYPE_LITERAL*/{3: "hello"};
Map<dynamic, String> l2 = /*info:INFERRED_TYPE_LITERAL*/{"hello": "hello"};
- Map<dynamic, String> l3 = /*info:INFERRED_TYPE_LITERAL*/{
+ Map<dynamic, String> l3 = /*info:INFERRED_TYPE_LITERAL,error:COULD_NOT_INFER*/{
3: /*error:MAP_VALUE_TYPE_NOT_ASSIGNABLE*/3
};
- Map<dynamic, String> l4 = /*info:INFERRED_TYPE_LITERAL*/{
+ Map<dynamic, String> l4 = /*info:INFERRED_TYPE_LITERAL,error:COULD_NOT_INFER*/{
3: "hello",
"hello": /*error:MAP_VALUE_TYPE_NOT_ASSIGNABLE*/3
};
@@ -1443,11 +1443,11 @@
{
Map<int, dynamic> l0 = /*info:INFERRED_TYPE_LITERAL*/{};
Map<int, dynamic> l1 = /*info:INFERRED_TYPE_LITERAL*/{3: "hello"};
- Map<int, dynamic> l2 = /*info:INFERRED_TYPE_LITERAL*/{
+ Map<int, dynamic> l2 = /*info:INFERRED_TYPE_LITERAL,error:COULD_NOT_INFER*/{
/*error:MAP_KEY_TYPE_NOT_ASSIGNABLE*/"hello": "hello"
};
Map<int, dynamic> l3 = /*info:INFERRED_TYPE_LITERAL*/{3: 3};
- Map<int, dynamic> l4 = /*info:INFERRED_TYPE_LITERAL*/{
+ Map<int, dynamic> l4 = /*info:INFERRED_TYPE_LITERAL,error:COULD_NOT_INFER*/{
3:"hello",
/*error:MAP_KEY_TYPE_NOT_ASSIGNABLE*/"hello": 3
};
@@ -1460,14 +1460,14 @@
{
const Map<int, String> l0 = /*info:INFERRED_TYPE_LITERAL*/const {};
const Map<int, String> l1 = /*info:INFERRED_TYPE_LITERAL*/const {3: "hello"};
- const Map<int, String> l2 = /*info:INFERRED_TYPE_LITERAL*/const {
+ const Map<int, String> l2 = /*info:INFERRED_TYPE_LITERAL,error:COULD_NOT_INFER*/const {
/*error:MAP_KEY_TYPE_NOT_ASSIGNABLE,error:MAP_KEY_TYPE_NOT_ASSIGNABLE*/"hello":
"hello"
};
- const Map<int, String> l3 = /*info:INFERRED_TYPE_LITERAL*/const {
+ const Map<int, String> l3 = /*info:INFERRED_TYPE_LITERAL,error:COULD_NOT_INFER*/const {
3: /*error:MAP_VALUE_TYPE_NOT_ASSIGNABLE,error:MAP_VALUE_TYPE_NOT_ASSIGNABLE*/3
};
- const Map<int, String> l4 = /*info:INFERRED_TYPE_LITERAL*/const {
+ const Map<int, String> l4 = /*info:INFERRED_TYPE_LITERAL,error:COULD_NOT_INFER,error:COULD_NOT_INFER*/const {
3:"hello",
/*error:MAP_KEY_TYPE_NOT_ASSIGNABLE,error:MAP_KEY_TYPE_NOT_ASSIGNABLE*/"hello":
/*error:MAP_VALUE_TYPE_NOT_ASSIGNABLE,error:MAP_VALUE_TYPE_NOT_ASSIGNABLE*/3
@@ -1746,6 +1746,41 @@
''');
}
+ void test_futureUnion_upwardsGenericMethods() {
+ // Regression test for https://github.com/dart-lang/sdk/issues/27151
+ checkFile(r'''
+import 'dart:async';
+
+main() async {
+ var b = new Future<B>.value(new B());
+ var c = new Future<C>.value(new C());
+ var lll = /*info:INFERRED_TYPE_LITERAL*/[b, c];
+ var result = await Future.wait(lll);
+ var result2 = await Future.wait(/*info:INFERRED_TYPE_LITERAL*/[b, c]);
+ List<A> list = result;
+ list = result2;
+}
+
+class A {}
+class B extends A {}
+class C extends A {}
+ ''');
+ }
+
+ void test_genericFunctions_returnTypedef() {
+ checkFile(r'''
+typedef void ToValue<T>(T value);
+
+main() {
+ ToValue/*<T>*/ f/*<T>*/(dynamic /*=T*/ x) => null;
+ var x = f/*<int>*/(42);
+ var y = f(42);
+ ToValue<int> takesInt = x;
+ takesInt = y;
+}
+ ''');
+ }
+
void test_genericMethods_basicDownwardInference() {
checkFile(r'''
/*=T*/ f/*<S, T>*/(/*=S*/ s) => null;
@@ -1833,7 +1868,7 @@
/*=T*/ f/*<T>*/(List/*<T>*/ s) => null;
main() {
String x = f(/*info:INFERRED_TYPE_LITERAL*/['hi']);
- String y = f(/*info:INFERRED_TYPE_LITERAL*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/42]);
+ String y = f(/*info:INFERRED_TYPE_LITERAL,error:COULD_NOT_INFER*/[/*error:LIST_ELEMENT_TYPE_NOT_ASSIGNABLE*/42]);
}
''');
}
@@ -2734,17 +2769,17 @@
main() {
// List inside map
var map = <String, List<Folder>>{
- 'pkgA': /*info:INFERRED_TYPE_LITERAL*/[/*info:DOWN_CAST_IMPLICIT*/getResource('/pkgA/lib/')],
- 'pkgB': /*info:INFERRED_TYPE_LITERAL*/[/*info:DOWN_CAST_IMPLICIT*/getResource('/pkgB/lib/')]
+ 'pkgA': /*info:INFERRED_TYPE_LITERAL,error:COULD_NOT_INFER*/[/*info:DOWN_CAST_IMPLICIT*/getResource('/pkgA/lib/')],
+ 'pkgB': /*info:INFERRED_TYPE_LITERAL,error:COULD_NOT_INFER*/[/*info:DOWN_CAST_IMPLICIT*/getResource('/pkgB/lib/')]
};
// Also try map inside list
var list = <Map<String, Folder>>[
- /*info:INFERRED_TYPE_LITERAL*/{ 'pkgA': /*info:DOWN_CAST_IMPLICIT*/getResource('/pkgA/lib/') },
- /*info:INFERRED_TYPE_LITERAL*/{ 'pkgB': /*info:DOWN_CAST_IMPLICIT*/getResource('/pkgB/lib/') },
+ /*info:INFERRED_TYPE_LITERAL,error:COULD_NOT_INFER*/{ 'pkgA': /*info:DOWN_CAST_IMPLICIT*/getResource('/pkgA/lib/') },
+ /*info:INFERRED_TYPE_LITERAL,error:COULD_NOT_INFER*/{ 'pkgB': /*info:DOWN_CAST_IMPLICIT*/getResource('/pkgB/lib/') },
];
// Instance creation too
var foo = new Foo<List<Folder>>(
- /*info:INFERRED_TYPE_LITERAL*/[/*info:DOWN_CAST_IMPLICIT*/getResource('/pkgA/lib/')]
+ /*info:INFERRED_TYPE_LITERAL,error:COULD_NOT_INFER*/[/*info:DOWN_CAST_IMPLICIT*/getResource('/pkgA/lib/')]
);
}
''');
@@ -2786,6 +2821,32 @@
expect(fns[9].type.toString(), '() → Stream<int>');
}
+ void test_inferParameterType_setter_fromField() {
+ var mainUnit = checkFile('''
+class C extends D {
+ /*error:INVALID_FIELD_OVERRIDE*/set foo(x) {}
+}
+class D {
+ int foo;
+}
+''');
+ var f = mainUnit.getType('C').accessors[0];
+ expect(f.type.toString(), '(int) → void');
+ }
+
+ void test_inferParameterType_setter_fromSetter() {
+ var mainUnit = checkFile('''
+class C extends D {
+ set foo(x) {}
+}
+class D {
+ set foo(int x) {}
+}
+''');
+ var f = mainUnit.getType('C').accessors[0];
+ expect(f.type.toString(), '(int) → void');
+ }
+
void test_inferred_nonstatic_field_depends_on_static_field_complex() {
var mainUnit = checkFile('''
class C {
diff --git a/pkg/analyzer/test/src/task/strong/strong_test_helper.dart b/pkg/analyzer/test/src/task/strong/strong_test_helper.dart
index 5b9f89a..dd03301 100644
--- a/pkg/analyzer/test/src/task/strong/strong_test_helper.dart
+++ b/pkg/analyzer/test/src/task/strong/strong_test_helper.dart
@@ -9,12 +9,14 @@
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/ast/token.dart';
import 'package:analyzer/dart/element/element.dart';
+import 'package:analyzer/error/error.dart';
+import 'package:analyzer/error/listener.dart';
import 'package:analyzer/file_system/file_system.dart';
import 'package:analyzer/file_system/memory_file_system.dart';
import 'package:analyzer/source/error_processor.dart';
import 'package:analyzer/src/dart/ast/token.dart';
+import 'package:analyzer/src/error/codes.dart';
import 'package:analyzer/src/generated/engine.dart';
-import 'package:analyzer/src/generated/error.dart';
import 'package:analyzer/src/generated/source.dart';
import 'package:source_span/source_span.dart';
import 'package:unittest/unittest.dart';
@@ -270,6 +272,7 @@
lib.importedLibraries.forEach(find);
lib.exportedLibraries.forEach(find);
}
+
find(start);
return results;
}
diff --git a/pkg/analyzer/test/stress/for_git_repository.dart b/pkg/analyzer/test/stress/for_git_repository.dart
index 2ee3929..858d7f3 100644
--- a/pkg/analyzer/test/stress/for_git_repository.dart
+++ b/pkg/analyzer/test/stress/for_git_repository.dart
@@ -10,6 +10,7 @@
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/type.dart';
+import 'package:analyzer/error/error.dart';
import 'package:analyzer/file_system/file_system.dart' as fs;
import 'package:analyzer/file_system/physical_file_system.dart';
import 'package:analyzer/src/context/builder.dart';
@@ -19,7 +20,6 @@
import 'package:analyzer/src/dart/element/member.dart';
import 'package:analyzer/src/dart/sdk/sdk.dart';
import 'package:analyzer/src/generated/engine.dart';
-import 'package:analyzer/src/generated/error.dart';
import 'package:analyzer/src/generated/sdk.dart';
import 'package:analyzer/src/generated/source.dart';
import 'package:analyzer/src/generated/utilities_collection.dart';
diff --git a/pkg/analyzer/tool/summary/build_sdk_summaries.dart b/pkg/analyzer/tool/summary/build_sdk_summaries.dart
index 8a6645d..fe9302a 100644
--- a/pkg/analyzer/tool/summary/build_sdk_summaries.dart
+++ b/pkg/analyzer/tool/summary/build_sdk_summaries.dart
@@ -2,83 +2,46 @@
import 'package:analyzer/file_system/physical_file_system.dart';
import 'package:analyzer/src/dart/sdk/sdk.dart';
-import 'package:analyzer/src/summary/flat_buffers.dart' as fb;
import 'package:analyzer/src/summary/summary_file_builder.dart';
main(List<String> args) {
- if (args.length < 1) {
+ String command;
+ String outFilePath;
+ String sdkPath;
+ if (args.length == 2) {
+ command = args[0];
+ outFilePath = args[1];
+ } else if (args.length == 3) {
+ command = args[0];
+ outFilePath = args[1];
+ sdkPath = args[2];
+ } else {
_printUsage();
exitCode = 1;
return;
}
- String command = args[0];
- if ((command == 'multiple-outputs' || command == 'strong-outputs') &&
- args.length >= 2 &&
- args.length <= 3) {
- bool includeSpec = command != 'strong-outputs';
- //
- // Prepare the output path.
- //
- String outputDirectoryPath = args[1];
- if (!FileSystemEntity.isDirectorySync(outputDirectoryPath)) {
- print("'$outputDirectoryPath' is not a directory.");
- _printUsage();
- exitCode = 1;
- return;
- }
- //
- // Prepare results.
- //
- String sdkPath = args.length > 2 ? args[2] : null;
- SummaryOutput output = _buildMultipleOutputs(sdkPath, includeSpec);
- if (output == null) {
- exitCode = 1;
- return;
- }
- //
- // Write results.
- //
- if (includeSpec) {
- output.spec.writeMultiple(outputDirectoryPath, 'spec');
- }
- output.strong.writeMultiple(outputDirectoryPath, 'strong');
- } else if (command == 'single-output' &&
- args.length >= 2 &&
- args.length <= 3) {
- String outputPath = args[1];
- String sdkPath = args.length > 2 ? args[2] : null;
- //
- // Prepare results.
- //
- SummaryOutput output = _buildMultipleOutputs(sdkPath, true);
- if (output == null) {
- exitCode = 1;
- return;
- }
- //
- // Write results.
- //
- output.write(outputPath);
- } else if (command == 'extract-spec-sum' && args.length == 3) {
- String inputPath = args[1];
- String outputPath = args[2];
- _extractSingleOutput(inputPath, FIELD_SPEC_SUM, outputPath);
- } else if (command == 'extract-spec-index' && args.length == 3) {
- String inputPath = args[1];
- String outputPath = args[2];
- _extractSingleOutput(inputPath, FIELD_SPEC_INDEX, outputPath);
- } else if (command == 'extract-strong-sum' && args.length == 3) {
- String inputPath = args[1];
- String outputPath = args[2];
- _extractSingleOutput(inputPath, FIELD_STRONG_SUM, outputPath);
- } else if (command == 'extract-strong-index' && args.length == 3) {
- String inputPath = args[1];
- String outputPath = args[2];
- _extractSingleOutput(inputPath, FIELD_STRONG_INDEX, outputPath);
+ //
+ // Validate the SDK path.
+ //
+ sdkPath ??= FolderBasedDartSdk
+ .defaultSdkDirectory(PhysicalResourceProvider.INSTANCE)
+ .path;
+ if (!FileSystemEntity.isDirectorySync('$sdkPath/lib')) {
+ print("'$sdkPath/lib' does not exist.");
+ _printUsage();
+ return;
+ }
+
+ //
+ // Handle commands.
+ //
+ if (command == 'build-spec') {
+ _buildSummary(sdkPath, outFilePath, false);
+ } else if (command == 'build-strong') {
+ _buildSummary(sdkPath, outFilePath, true);
} else {
_printUsage();
- exitCode = 1;
return;
}
}
@@ -88,72 +51,23 @@
*/
const BINARY_NAME = "build_sdk_summaries";
-SummaryOutput _buildMultipleOutputs(String sdkPath, bool includeSpec) {
- //
- // Validate the SDK path.
- //
- if (sdkPath != null) {
- if (!FileSystemEntity.isDirectorySync('$sdkPath/lib')) {
- print("'$sdkPath/lib' does not exist.");
- _printUsage();
- return null;
- }
- } else {
- sdkPath = FolderBasedDartSdk
- .defaultSdkDirectory(PhysicalResourceProvider.INSTANCE)
- .path;
- }
-
- //
- // Build spec and strong outputs.
- //
- BuilderOutput spec = includeSpec ? _buildOutput(sdkPath, false) : null;
- BuilderOutput strong = _buildOutput(sdkPath, true);
- return new SummaryOutput(spec, strong);
-}
-
-BuilderOutput _buildOutput(String sdkPath, bool strongMode) {
- String modeName = strongMode ? 'strong' : 'spec';
- print('Generating $modeName mode summary and index.');
+void _buildSummary(String sdkPath, String outPath, bool strong) {
+ String modeName = strong ? 'strong' : 'spec';
+ print('Generating $modeName mode summary.');
Stopwatch sw = new Stopwatch()..start();
- SummaryBuildConfig config = new SummaryBuildConfig(strongMode: strongMode);
- BuilderOutput output = new SummaryBuilder.forSdk(sdkPath, config).build();
+ List<int> bytes = new SummaryBuilder.forSdk(sdkPath, strong).build();
+ new File(outPath).writeAsBytesSync(bytes, mode: FileMode.WRITE_ONLY);
print('\tDone in ${sw.elapsedMilliseconds} ms.');
- return output;
-}
-
-/**
- * Open the flat buffer in [inputPath] and extract the byte array in the [field]
- * into the [outputPath] file.
- */
-void _extractSingleOutput(String inputPath, int field, String outputPath) {
- List<int> bytes = new File(inputPath).readAsBytesSync();
- fb.BufferContext root = new fb.BufferContext.fromBytes(bytes);
- int tableOffset = root.derefObject(0);
- List<int> fieldBytes =
- const fb.Uint8ListReader().vTableGet(root, tableOffset, field);
- new File(outputPath).writeAsBytesSync(fieldBytes, mode: FileMode.WRITE_ONLY);
}
/**
* Print information about how to use the SDK summaries builder.
*/
void _printUsage() {
-// print('Usage: $BINARY_NAME command output_directory_path [sdk_path]');
print('Usage: $BINARY_NAME command arguments');
print('Where command can be one of the following:');
- print(' multiple-outputs output_directory_path [sdk_path]');
- print(' Generate separate summary and index files.');
- print(' strong-outputs output_directory_path [sdk_path]');
- print(' Generate separate summary and index files (strong mode only).');
- print(' single-output output_file_path [sdk_path]');
- print(' Generate a single file with summary and index.');
- print(' extract-spec-sum input_file output_file');
- print(' Extract the spec-mode summary file.');
- print(' extract-strong-sum input_file output_file');
- print(' Extract the strong-mode summary file.');
- print(' extract-spec-index input_file output_file');
- print(' Extract the spec-mode index file.');
- print(' extract-strong-index input_file output_file');
- print(' Extract the strong-mode index file.');
+ print(' build-spec output_file [sdk_path]');
+ print(' Generate spec mode summary file.');
+ print(' build-strong output_file [sdk_path]');
+ print(' Generate strong mode summary file.');
}
diff --git a/pkg/analyzer/tool/summary/generate.dart b/pkg/analyzer/tool/summary/generate.dart
index b9616867..d3fd863 100644
--- a/pkg/analyzer/tool/summary/generate.dart
+++ b/pkg/analyzer/tool/summary/generate.dart
@@ -24,6 +24,7 @@
import 'package:analyzer/analyzer.dart';
import 'package:analyzer/dart/ast/token.dart';
+import 'package:analyzer/error/listener.dart';
import 'package:analyzer/file_system/file_system.dart';
import 'package:analyzer/file_system/physical_file_system.dart';
import 'package:analyzer/src/codegen/tools.dart';
@@ -568,19 +569,19 @@
out();
outDoc(field.documentation);
constructorParams.add('$typeStr $fieldName');
- out('void set $fieldName($typeStr _value) {');
+ out('void set $fieldName($typeStr value) {');
indent(() {
String stateFieldName = '_' + fieldName;
// Validate that int(s) are non-negative.
if (fieldType.typeName == 'int') {
if (!fieldType.isList) {
- out('assert(_value == null || _value >= 0);');
+ out('assert(value == null || value >= 0);');
} else {
- out('assert(_value == null || _value.every((e) => e >= 0));');
+ out('assert(value == null || value.every((e) => e >= 0));');
}
}
// Set the value.
- out('$stateFieldName = _value;');
+ out('this.$stateFieldName = value;');
});
out('}');
}
diff --git a/pkg/analyzer/tool/task_dependency_graph/generate.dart b/pkg/analyzer/tool/task_dependency_graph/generate.dart
index db2cd09..068790f 100644
--- a/pkg/analyzer/tool/task_dependency_graph/generate.dart
+++ b/pkg/analyzer/tool/task_dependency_graph/generate.dart
@@ -154,14 +154,15 @@
DartSdk sdk = new FolderBasedDartSdk(resourceProvider,
FolderBasedDartSdk.defaultSdkDirectory(resourceProvider));
context = AnalysisEngine.instance.createAnalysisContext();
- String packageRootPath;
- if (Platform.packageRoot != null) {
- packageRootPath = Uri.parse(Platform.packageRoot).toFilePath();
- } else {
- packageRootPath = path.join(rootDir, 'packages');
- }
ContextBuilder builder = new ContextBuilder(resourceProvider, null, null);
- builder.defaultPackagesDirectoryPath = packageRootPath;
+ if (Platform.packageRoot != null) {
+ builder.defaultPackagesDirectoryPath = Uri.parse(Platform.packageRoot).toFilePath();
+ } else if (Platform.packageConfig != null) {
+ builder.defaultPackageFilePath = Platform.packageConfig;
+ } else {
+ // Let the context builder use the default algorithm for package
+ // resolution.
+ }
List<UriResolver> uriResolvers = [
new DartUriResolver(sdk),
new PackageMapUriResolver(resourceProvider,
diff --git a/pkg/analyzer_cli/lib/src/analyzer_impl.dart b/pkg/analyzer_cli/lib/src/analyzer_impl.dart
index 75acfa9..9f75bf9 100644
--- a/pkg/analyzer_cli/lib/src/analyzer_impl.dart
+++ b/pkg/analyzer_cli/lib/src/analyzer_impl.dart
@@ -18,7 +18,6 @@
import 'package:analyzer/src/generated/utilities_general.dart';
import 'package:analyzer_cli/src/driver.dart';
import 'package:analyzer_cli/src/error_formatter.dart';
-import 'package:analyzer_cli/src/incremental_analyzer.dart';
import 'package:analyzer_cli/src/options.dart';
import 'package:path/path.dart' as pathos;
@@ -39,8 +38,6 @@
final AnalysisContext context;
- final IncrementalAnalysisSession incrementalSession;
-
/// Accumulated analysis statistics.
final AnalysisStats stats;
@@ -63,8 +60,8 @@
/// specified the "--package-warnings" option.
String _selfPackageName;
- AnalyzerImpl(this.context, this.incrementalSession, this.librarySource,
- this.options, this.stats, this.startTime);
+ AnalyzerImpl(this.context, this.librarySource, this.options, this.stats,
+ this.startTime);
/// Returns the maximal [ErrorSeverity] of the recorded errors.
ErrorSeverity get maxErrorSeverity {
@@ -138,7 +135,6 @@
var units = new Set<CompilationUnitElement>();
var libraries = new Set<LibraryElement>();
addLibrarySources(library, libraries, units);
- incrementalSession?.setAnalyzedSources(sources);
}
/// Setup local fields such as the analysis context for analysis.
diff --git a/pkg/analyzer_cli/lib/src/build_mode.dart b/pkg/analyzer_cli/lib/src/build_mode.dart
index 7632e69..8992a10 100644
--- a/pkg/analyzer_cli/lib/src/build_mode.dart
+++ b/pkg/analyzer_cli/lib/src/build_mode.dart
@@ -8,7 +8,6 @@
import 'dart:io' as io;
import 'package:analyzer/dart/ast/ast.dart' show CompilationUnit;
-import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/file_system/file_system.dart';
import 'package:analyzer/src/dart/sdk/sdk.dart';
import 'package:analyzer/src/generated/engine.dart';
@@ -137,7 +136,6 @@
PackageBundleAssembler assembler;
final Set<Source> processedSources = new Set<Source>();
final Map<Uri, UnlinkedUnit> uriToUnit = <Uri, UnlinkedUnit>{};
- PackageBundle sdkBundle;
BuildMode(this.resourceProvider, this.options, this.stats);
@@ -194,30 +192,7 @@
excludeHashes: options.buildSummaryExcludeInformative &&
options.buildSummaryOutputSemantic == null);
if (_shouldOutputSummary) {
- if (options.buildSummaryOnlyAst && !options.buildSummaryFallback) {
- _serializeAstBasedSummary(explicitSources);
- } else {
- for (Source source in explicitSources) {
- if (context.computeKindOf(source) == SourceKind.LIBRARY) {
- if (options.buildSummaryFallback) {
- assembler.addFallbackLibrary(source);
- } else {
- LibraryElement libraryElement =
- context.computeLibraryElement(source);
- assembler.serializeLibraryElement(libraryElement);
- }
- }
- if (options.buildSummaryFallback) {
- assembler.addFallbackUnit(source);
- }
- }
- }
- if (!options.buildSummaryOnlyAst) {
- // In non-AST mode, the SDK bundle wasn't added to the summaryDataStore
- // because it is automatically loaded during analysis. However we still
- // want the SDK bundle to be noted as a dependency, so add it now.
- summaryDataStore.addBundle(null, sdkBundle);
- }
+ _serializeAstBasedSummary(explicitSources);
// Write the whole package bundle.
assembler.recordDependencies(summaryDataStore);
PackageBundleBuilder bundle = assembler.assemble();
@@ -267,6 +242,7 @@
recordDependencyInfo: _shouldOutputSummary);
DartSdk sdk;
+ PackageBundle sdkBundle;
if (options.dartSdkSummaryPath != null) {
SummaryBasedDartSdk summarySdk = new SummaryBasedDartSdk(
options.dartSdkSummaryPath, options.strongMode);
@@ -277,15 +253,13 @@
resourceProvider.getFolder(options.dartSdkPath), options.strongMode);
dartSdk.analysisOptions =
Driver.createAnalysisOptionsForCommandLineOptions(options);
- dartSdk.useSummary = !options.buildSummaryOnlyAst;
+ dartSdk.useSummary = false;
sdk = dartSdk;
sdkBundle = dartSdk.getSummarySdkBundle(options.strongMode);
}
- // In AST mode include SDK bundle to avoid parsing SDK sources.
- if (options.buildSummaryOnlyAst) {
- summaryDataStore.addBundle(null, sdkBundle);
- }
+ // Include SDK bundle to avoid parsing SDK sources.
+ summaryDataStore.addBundle(null, sdkBundle);
// Create the context.
context = AnalysisEngine.instance.createAnalysisContext();
@@ -302,13 +276,6 @@
contextOptions.analyzeFunctionBodies = false;
}
});
-
- if (!options.buildSummaryOnlyAst) {
- // Configure using summaries.
- context.typeProvider = sdk.context.typeProvider;
- context.resultProvider =
- new InputPackagesResultProvider(context, summaryDataStore);
- }
}
/**
@@ -395,8 +362,12 @@
});
}
- Map<String, LinkedLibraryBuilder> linkResult =
- link(sourceUris, _getDependency, _getUnit, options.strongMode);
+ Map<String, LinkedLibraryBuilder> linkResult = link(
+ sourceUris,
+ _getDependency,
+ _getUnit,
+ context.declaredVariables.get,
+ options.strongMode);
linkResult.forEach(assembler.addLinkedLibrary);
}
}
diff --git a/pkg/analyzer_cli/lib/src/driver.dart b/pkg/analyzer_cli/lib/src/driver.dart
index b16b787..185290b 100644
--- a/pkg/analyzer_cli/lib/src/driver.dart
+++ b/pkg/analyzer_cli/lib/src/driver.dart
@@ -32,12 +32,12 @@
show PerformanceTag;
import 'package:analyzer/src/services/lint.dart';
import 'package:analyzer/src/source/source_resource.dart';
+import 'package:analyzer/src/summary/package_bundle_reader.dart';
import 'package:analyzer/src/summary/summary_sdk.dart' show SummaryBasedDartSdk;
import 'package:analyzer/src/task/options.dart';
import 'package:analyzer_cli/src/analyzer_impl.dart';
import 'package:analyzer_cli/src/build_mode.dart';
import 'package:analyzer_cli/src/error_formatter.dart';
-import 'package:analyzer_cli/src/incremental_analyzer.dart';
import 'package:analyzer_cli/src/options.dart';
import 'package:analyzer_cli/src/perf_report.dart';
import 'package:analyzer_cli/starter.dart';
@@ -78,7 +78,7 @@
/// The context that was most recently created by a call to [_analyzeAll], or
/// `null` if [_analyzeAll] hasn't been called yet.
- AnalysisContext _context;
+ InternalAnalysisContext _context;
/// The total number of source files loaded by an AnalysisContext.
int _analyzedFileCount = 0;
@@ -87,8 +87,6 @@
/// creation.
CommandLineOptions _previousOptions;
- IncrementalAnalysisSession incrementalSession;
-
@override
ResolverProvider packageResolverProvider;
@@ -223,8 +221,6 @@
libUris.add(source.uri);
}
- incrementalSession?.finish();
-
// Check that each part has a corresponding source in the input list.
for (Source part in parts) {
bool found = false;
@@ -311,7 +307,8 @@
if (options.enableSuperMixins != _previousOptions.enableSuperMixins) {
return false;
}
- if (options.incrementalCachePath != _previousOptions.incrementalCachePath) {
+ if (!_equalLists(
+ options.buildSummaryInputs, _previousOptions.buildSummaryInputs)) {
return false;
}
return true;
@@ -347,8 +344,11 @@
/// Decide on the appropriate method for resolving URIs based on the given
/// [options] and [customUrlMappings] settings, and return a
/// [SourceFactory] that has been configured accordingly.
- SourceFactory _chooseUriResolutionPolicy(CommandLineOptions options,
- Map<file_system.Folder, YamlMap> embedderMap, _PackageInfo packageInfo) {
+ SourceFactory _chooseUriResolutionPolicy(
+ CommandLineOptions options,
+ Map<file_system.Folder, YamlMap> embedderMap,
+ _PackageInfo packageInfo,
+ SummaryDataStore summaryDataStore) {
// Create a custom package resolver if one has been specified.
if (packageResolverProvider != null) {
file_system.Folder folder = resourceProvider.getResource('.');
@@ -359,6 +359,7 @@
// TODO(brianwilkerson) This doesn't handle sdk extensions.
List<UriResolver> resolvers = <UriResolver>[
sdkResolver,
+ new InSummaryUriResolver(resourceProvider, summaryDataStore),
resolver,
new file_system.ResourceUriResolver(resourceProvider)
];
@@ -417,6 +418,9 @@
resolvers.add(new SdkExtUriResolver(packageInfo.packageMap));
}
+ // Then package URIs from summaries.
+ resolvers.add(new InSummaryUriResolver(resourceProvider, summaryDataStore));
+
// Then package URIs.
if (packageUriResolver != null) {
resolvers.add(packageUriResolver);
@@ -505,17 +509,26 @@
// No summaries in the presence of embedders or extenders.
bool useSummaries = embedderMap.isEmpty && !hasSdkExt;
+ if (!useSummaries && options.buildSummaryInputs.isNotEmpty) {
+ throw new _DriverError(
+ 'Summaries are not yet supported when using Flutter.');
+ }
+
+ // Read any input summaries.
+ SummaryDataStore summaryDataStore = new SummaryDataStore(
+ useSummaries ? options.buildSummaryInputs : <String>[]);
+
// Once options and embedders are processed, setup the SDK.
_setupSdk(options, useSummaries);
// Choose a package resolution policy and a diet parsing policy based on
// the command-line options.
- SourceFactory sourceFactory =
- _chooseUriResolutionPolicy(options, embedderMap, packageInfo);
+ SourceFactory sourceFactory = _chooseUriResolutionPolicy(
+ options, embedderMap, packageInfo, summaryDataStore);
_context.sourceFactory = sourceFactory;
-
- incrementalSession = configureIncrementalAnalysis(options, context);
+ _context.resultProvider =
+ new InputPackagesResultProvider(_context, summaryDataStore);
}
/// Return discovered packagespec, or `null` if none is found.
@@ -612,8 +625,8 @@
/// Analyze a single source.
ErrorSeverity _runAnalyzer(Source source, CommandLineOptions options) {
int startTime = currentTimeMillis();
- AnalyzerImpl analyzer = new AnalyzerImpl(
- _context, incrementalSession, source, options, stats, startTime);
+ AnalyzerImpl analyzer =
+ new AnalyzerImpl(_context, source, options, stats, startTime);
var errorSeverity = analyzer.analyzeSync();
if (errorSeverity == ErrorSeverity.ERROR) {
io.exitCode = errorSeverity.ordinal;
@@ -693,6 +706,19 @@
_processAnalysisOptions(resourceProvider, context, options);
}
+ /// Perform a deep comparison of two string lists.
+ static bool _equalLists(List<String> l1, List<String> l2) {
+ if (l1.length != l2.length) {
+ return false;
+ }
+ for (int i = 0; i < l1.length; i++) {
+ if (l1[i] != l2[i]) {
+ return false;
+ }
+ }
+ return true;
+ }
+
/// Perform a deep comparison of two string maps.
static bool _equalMaps(Map<String, String> m1, Map<String, String> m2) {
if (m1.length != m2.length) {
diff --git a/pkg/analyzer_cli/lib/src/incremental_analyzer.dart b/pkg/analyzer_cli/lib/src/incremental_analyzer.dart
deleted file mode 100644
index d7e9084..0000000
--- a/pkg/analyzer_cli/lib/src/incremental_analyzer.dart
+++ /dev/null
@@ -1,226 +0,0 @@
-// Copyright (c) 2016, 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.
-
-library analyzer_cli.src.incremental_analyzer;
-
-import 'dart:io' as io;
-
-import 'package:analyzer/dart/element/element.dart';
-import 'package:analyzer/file_system/physical_file_system.dart';
-import 'package:analyzer/src/context/cache.dart';
-import 'package:analyzer/src/context/context.dart';
-import 'package:analyzer/src/dart/sdk/sdk.dart';
-import 'package:analyzer/src/generated/engine.dart';
-import 'package:analyzer/src/generated/error.dart';
-import 'package:analyzer/src/generated/sdk.dart';
-import 'package:analyzer/src/generated/source.dart';
-import 'package:analyzer/src/summary/incremental_cache.dart';
-import 'package:analyzer/src/summary/package_bundle_reader.dart';
-import 'package:analyzer/src/task/dart.dart';
-import 'package:analyzer/task/dart.dart';
-import 'package:analyzer/task/general.dart';
-import 'package:analyzer/task/model.dart';
-import 'package:analyzer_cli/src/options.dart';
-
-/**
- * If the given [options] enables incremental analysis and [context] and Dart
- * SDK implementations support incremental analysis, configure it for the
- * given [context] and return the handle to work with it.
- */
-IncrementalAnalysisSession configureIncrementalAnalysis(
- CommandLineOptions options, AnalysisContext context) {
- String cachePath = options.incrementalCachePath;
- DartSdk sdk = context.sourceFactory.dartSdk;
- // If supported implementations, configure for incremental analysis.
- if (cachePath != null &&
- context is InternalAnalysisContext &&
- sdk is FolderBasedDartSdk) {
- context.typeProvider = sdk.context.typeProvider;
- // Set the result provide from the cache.
- CacheStorage storage = new FolderCacheStorage(
- PhysicalResourceProvider.INSTANCE.getFolder(cachePath),
- '${io.pid}.temp');
- List<int> configSalt = <int>[
- context.analysisOptions.encodeCrossContextOptions()
- ];
- IncrementalCache cache = new IncrementalCache(storage, context, configSalt);
- context.resultProvider = new _CacheBasedResultProvider(context, cache);
- // Listen for new libraries to put into the cache.
- _IncrementalAnalysisSession session =
- new _IncrementalAnalysisSession(options, storage, context, cache);
- context
- .onResultChanged(LIBRARY_ELEMENT1)
- .listen((ResultChangedEvent event) {
- if (event.wasComputed) {
- session.newLibrarySources.add(event.target.source);
- }
- });
- return session;
- }
- // Incremental analysis cannot be used.
- return null;
-}
-
-/**
- * Interface that is exposed to the clients of incremental analysis.
- */
-abstract class IncrementalAnalysisSession {
- /**
- * Finish tasks required after incremental analysis - save results into the
- * cache, evict old results, etc.
- */
- void finish();
-
- /**
- * Sets the set of [Source]s analyzed in the context, both explicit and
- * implicit, for which errors might be requested. This set is used to compute
- * containing libraries for every source in the context.
- */
- void setAnalyzedSources(Iterable<Source> sources);
-}
-
-/**
- * The [ResultProvider] that provides results from [IncrementalCache].
- */
-class _CacheBasedResultProvider extends ResynthesizerResultProvider {
- final IncrementalCache cache;
-
- final Set<Source> sourcesWithSummaries = new Set<Source>();
- final Set<Source> sourcesWithoutSummaries = new Set<Source>();
- final Set<String> addedLibraryBundleIds = new Set<String>();
-
- _CacheBasedResultProvider(InternalAnalysisContext context, this.cache)
- : super(context, new SummaryDataStore(<String>[])) {
- AnalysisContext sdkContext = context.sourceFactory.dartSdk.context;
- createResynthesizer(sdkContext, sdkContext.typeProvider);
- }
-
- @override
- bool compute(CacheEntry entry, ResultDescriptor result) {
- AnalysisTarget target = entry.target;
- // Source based results.
- if (target is Source) {
- if (result == SOURCE_KIND) {
- SourceKind kind = cache.getSourceKind(target);
- if (kind != null) {
- entry.setValue(result, kind, TargetedResult.EMPTY_LIST);
- return true;
- } else {
- return false;
- }
- }
- if (result == INCLUDED_PARTS) {
- List<Source> parts = cache.getLibraryParts(target);
- if (parts != null) {
- entry.setValue(result, parts, TargetedResult.EMPTY_LIST);
- return true;
- } else {
- return false;
- }
- }
- if (result == DART_ERRORS) {
- List<Source> librarySources = context.getLibrariesContaining(target);
- List<List<AnalysisError>> errorList = <List<AnalysisError>>[];
- for (Source librarySource in librarySources) {
- List<AnalysisError> errors =
- cache.getSourceErrorsInLibrary(librarySource, target);
- if (errors == null) {
- return false;
- }
- errorList.add(errors);
- }
- List<AnalysisError> mergedErrors = AnalysisError.mergeLists(errorList);
- // Filter the errors.
- IgnoreInfo ignoreInfo = context.getResult(target, IGNORE_INFO);
- LineInfo lineInfo = context.getResult(target, LINE_INFO);
- List<AnalysisError> filteredErrors =
- DartErrorsTask.filterIgnored(mergedErrors, ignoreInfo, lineInfo);
- // Set the result.
- entry.setValue(result, filteredErrors, TargetedResult.EMPTY_LIST);
- return true;
- }
- }
- return super.compute(entry, result);
- }
-
- @override
- bool hasResultsForSource(Source source) {
- // Check cache states.
- if (sourcesWithSummaries.contains(source)) {
- return true;
- }
- if (sourcesWithoutSummaries.contains(source)) {
- return false;
- }
- // Try to load bundles.
- List<LibraryBundleWithId> bundles = cache.getLibraryClosureBundles(source);
- if (bundles == null) {
- sourcesWithoutSummaries.add(source);
- return false;
- }
- // Fill the resynthesizer.
- sourcesWithSummaries.add(source);
- for (LibraryBundleWithId bundleWithId in bundles) {
- if (addedLibraryBundleIds.add(bundleWithId.id)) {
- addBundle(null, bundleWithId.bundle);
- }
- }
- return true;
- }
-}
-
-class _IncrementalAnalysisSession implements IncrementalAnalysisSession {
- final CommandLineOptions commandLineOptions;
- final CacheStorage cacheStorage;
- final AnalysisContext context;
- final IncrementalCache cache;
-
- final Set<Source> newLibrarySources = new Set<Source>();
-
- _IncrementalAnalysisSession(
- this.commandLineOptions, this.cacheStorage, this.context, this.cache);
-
- @override
- void finish() {
- // Finish computing new libraries and put them into the cache.
- for (Source librarySource in newLibrarySources) {
- if (!commandLineOptions.machineFormat) {
- print('Compute library element for $librarySource');
- }
- _putLibrary(librarySource);
- }
- // Compact the cache.
- cacheStorage.compact();
- }
-
- @override
- void setAnalyzedSources(Iterable<Source> sources) {
- for (Source source in sources) {
- SourceKind kind = context.computeKindOf(source);
- if (kind == SourceKind.LIBRARY) {
- context.computeResult(source, LINE_INFO);
- context.computeResult(source, IGNORE_INFO);
- context.computeResult(source, INCLUDED_PARTS);
- }
- }
- }
-
- void _putLibrary(Source librarySource) {
- LibraryElement libraryElement =
- context.computeResult(librarySource, LIBRARY_ELEMENT);
- try {
- cache.putLibrary(libraryElement);
- } catch (e) {
- return;
- }
- // Write errors for the library units.
- for (CompilationUnitElement unit in libraryElement.units) {
- Source unitSource = unit.source;
- List<AnalysisError> errors = context.computeResult(
- new LibrarySpecificUnit(librarySource, unitSource),
- LIBRARY_UNIT_ERRORS);
- cache.putSourceErrorsInLibrary(librarySource, unitSource, errors);
- }
- }
-}
diff --git a/pkg/analyzer_cli/lib/src/options.dart b/pkg/analyzer_cli/lib/src/options.dart
index 6a4c426..c64eddc 100644
--- a/pkg/analyzer_cli/lib/src/options.dart
+++ b/pkg/analyzer_cli/lib/src/options.dart
@@ -48,10 +48,6 @@
/// Whether to skip analysis when creating summaries in build mode.
final bool buildSummaryOnly;
- /// Whether to create summaries using only ASTs, i.e. don't perform
- /// resolution.
- final bool buildSummaryOnlyAst;
-
/// Whether to use diet parsing, i.e. skip function bodies. We don't need to
/// analyze function bodies to use summaries during future compilation steps.
final bool buildSummaryOnlyDiet;
@@ -66,9 +62,6 @@
/// build mode.
final String buildSummaryOutputSemantic;
- /// Whether to output a summary in "fallback mode".
- final bool buildSummaryFallback;
-
/// Whether to suppress a nonzero exit code in build mode.
final bool buildSuppressExitCode;
@@ -120,9 +113,6 @@
/// Whether to use machine format for error display
final bool machineFormat;
- /// The path to the root folder of the incremental cache.
- final String incrementalCachePath;
-
/// The path to the package root
final String packageRootPath;
@@ -169,10 +159,8 @@
: buildAnalysisOutput = args['build-analysis-output'],
buildMode = args['build-mode'],
buildModePersistentWorker = args['persistent_worker'],
- buildSummaryFallback = args['build-summary-fallback'],
buildSummaryInputs = args['build-summary-input'] as List<String>,
buildSummaryOnly = args['build-summary-only'],
- buildSummaryOnlyAst = args['build-summary-only-ast'],
buildSummaryOnlyDiet = args['build-summary-only-diet'],
buildSummaryExcludeInformative =
args['build-summary-exclude-informative'],
@@ -195,7 +183,6 @@
lints = args['lints'],
log = args['log'],
machineFormat = args['machine'] || args['format'] == 'machine',
- incrementalCachePath = args['incremental-cache-path'],
packageConfigPath = args['packages'],
packageRootPath = args['package-root'],
perfReport = args['x-perf-report'],
@@ -373,13 +360,6 @@
allowMultiple: true,
splitCommas: false)
//
- // Incremental analysis.
- //
- ..addOption('incremental-cache-path',
- help: 'The path to the folder with information to support '
- 'incremental analysis, e.g. summary files, errors, etc.',
- hide: true)
- //
// Build mode.
//
..addFlag('persistent_worker',
@@ -416,7 +396,7 @@
negatable: false,
hide: true)
..addFlag('build-summary-only-ast',
- help: 'Generate summaries using ASTs.',
+ help: 'deprecated -- Generate summaries using ASTs.',
defaultsTo: false,
negatable: false,
hide: true)
@@ -431,11 +411,6 @@
defaultsTo: false,
negatable: false,
hide: true)
- ..addFlag('build-summary-fallback',
- help: 'If outputting a summary, output it in fallback mode.',
- defaultsTo: false,
- negatable: false,
- hide: true)
..addFlag('build-suppress-exit-code',
help: 'Exit with code 0 even if errors are found.',
defaultsTo: false,
diff --git a/pkg/analyzer_cli/test/options_test.dart b/pkg/analyzer_cli/test/options_test.dart
index 50ee98c..b74edc1 100644
--- a/pkg/analyzer_cli/test/options_test.dart
+++ b/pkg/analyzer_cli/test/options_test.dart
@@ -21,7 +21,6 @@
expect(options, isNotNull);
expect(options.buildMode, isFalse);
expect(options.buildAnalysisOutput, isNull);
- expect(options.buildSummaryFallback, isFalse);
expect(options.buildSummaryInputs, isEmpty);
expect(options.buildSummaryOnly, isFalse);
expect(options.buildSummaryOutput, isNull);
@@ -264,17 +263,6 @@
expect(options.sourceFiles, isEmpty);
}
- test_buildSummaryFallback() {
- _parse([
- '--build-mode',
- '--build-summary-output=//path/to/output.sum',
- '--build-summary-fallback',
- 'package:p/foo.dart|/path/to/p/lib/foo.dart'
- ]);
- expect(options.buildMode, isTrue);
- expect(options.buildSummaryFallback, isTrue);
- }
-
test_buildSummaryInputs_commaSeparated() {
_parse([
'--build-mode',
@@ -286,6 +274,16 @@
options.buildSummaryInputs, ['/path/to/aaa.sum', '/path/to/bbb.sum']);
}
+ test_buildSummaryInputs_commaSeparated_normalMode() {
+ _parse([
+ '--build-summary-input=/path/to/aaa.sum,/path/to/bbb.sum',
+ '/path/to/p/lib/foo.dart'
+ ]);
+ expect(options.buildMode, isFalse);
+ expect(
+ options.buildSummaryInputs, ['/path/to/aaa.sum', '/path/to/bbb.sum']);
+ }
+
test_buildSummaryInputs_separateFlags() {
_parse([
'--build-mode',
@@ -298,6 +296,17 @@
options.buildSummaryInputs, ['/path/to/aaa.sum', '/path/to/bbb.sum']);
}
+ test_buildSummaryInputs_separateFlags_normalMode() {
+ _parse([
+ '--build-summary-input=/path/to/aaa.sum',
+ '--build-summary-input=/path/to/bbb.sum',
+ 'package:p/foo.dart|/path/to/p/lib/foo.dart'
+ ]);
+ expect(options.buildMode, isFalse);
+ expect(
+ options.buildSummaryInputs, ['/path/to/aaa.sum', '/path/to/bbb.sum']);
+ }
+
test_buildSummaryOnly() {
_parse([
'--build-mode',
diff --git a/pkg/analyzer_cli/tool/perf.dart b/pkg/analyzer_cli/tool/perf.dart
new file mode 100644
index 0000000..3c97e23
--- /dev/null
+++ b/pkg/analyzer_cli/tool/perf.dart
@@ -0,0 +1,172 @@
+// Copyright (c) 2016, 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.
+
+/// An entrypoint used to run portions of analyzer and measure its performance.
+library analyzer_cli.tool.perf;
+
+import 'dart:io' show exit;
+
+import 'package:analyzer/dart/ast/ast.dart';
+import 'package:analyzer/dart/ast/token.dart';
+import 'package:analyzer/error/listener.dart';
+import 'package:analyzer/file_system/file_system.dart' show ResourceUriResolver;
+import 'package:analyzer/file_system/physical_file_system.dart'
+ show PhysicalResourceProvider;
+import 'package:analyzer/source/package_map_resolver.dart';
+import 'package:analyzer/src/context/builder.dart';
+import 'package:analyzer/src/dart/scanner/reader.dart';
+import 'package:analyzer/src/dart/scanner/scanner.dart';
+import 'package:analyzer/src/dart/sdk/sdk.dart' show FolderBasedDartSdk;
+import 'package:analyzer/src/generated/parser.dart';
+import 'package:analyzer/src/generated/source.dart';
+import 'package:analyzer/src/generated/source_io.dart';
+import 'package:package_config/discovery.dart';
+
+/// Cummulative total number of chars scanned.
+int scanTotalChars = 0;
+
+/// Cummulative time spent scanning.
+Stopwatch scanTimer = new Stopwatch();
+
+/// Factory to load and resolve app, packages, and sdk sources.
+SourceFactory sources;
+
+main(args) {
+ // TODO(sigmund): provide sdk folder as well.
+ if (args.length < 3) {
+ print('usage: perf.dart <bench-id> <package-root> <entry.dart>');
+ exit(1);
+ }
+ var totalTimer = new Stopwatch()..start();
+
+ var bench = args[0];
+ var packageRoot = Uri.base.resolve(args[1]);
+ var entryUri = Uri.base.resolve(args[2]);
+
+ setup(packageRoot);
+ if (bench == 'scan') {
+ scanReachableFiles(entryUri);
+ } else if (bench == 'parse') {
+ Set<Source> files = scanReachableFiles(entryUri);
+ parseFiles(files);
+ } else {
+ print('unsupported bench-id: $bench. Please specify "scan" or "parse"');
+ // TODO(sigmund): implement the remaining benchmarks.
+ exit(1);
+ }
+
+ totalTimer.stop();
+ report("total", totalTimer.elapsedMicroseconds);
+}
+
+/// Sets up analyzer to be able to load and resolve app, packages, and sdk
+/// sources.
+void setup(Uri packageRoot) {
+ var provider = PhysicalResourceProvider.INSTANCE;
+ var packageMap = new ContextBuilder(provider, null, null)
+ .convertPackagesToMap(getPackagesDirectory(packageRoot));
+ sources = new SourceFactory([
+ new ResourceUriResolver(provider),
+ new PackageMapUriResolver(provider, packageMap),
+ new DartUriResolver(
+ new FolderBasedDartSdk(provider, provider.getFolder("sdk"))),
+ ]);
+}
+
+/// Load and scans all files we need to process: files reachable from the
+/// entrypoint and all core libraries automatically included by the VM.
+Set<Source> scanReachableFiles(Uri entryUri) {
+ var files = new Set<Source>();
+ var loadTimer = new Stopwatch()..start();
+ collectSources(sources.forUri2(entryUri), files);
+ collectSources(sources.forUri("dart:async"), files);
+ collectSources(sources.forUri("dart:collection"), files);
+ collectSources(sources.forUri("dart:convert"), files);
+ collectSources(sources.forUri("dart:core"), files);
+ collectSources(sources.forUri("dart:developer"), files);
+ collectSources(sources.forUri("dart:_internal"), files);
+ collectSources(sources.forUri("dart:isolate"), files);
+ collectSources(sources.forUri("dart:math"), files);
+ collectSources(sources.forUri("dart:mirrors"), files);
+ collectSources(sources.forUri("dart:typed_data"), files);
+ loadTimer.stop();
+
+ print('input size: ${scanTotalChars} chars');
+ var loadTime = loadTimer.elapsedMicroseconds - scanTimer.elapsedMicroseconds;
+ report("load", loadTime);
+ report("scan", scanTimer.elapsedMicroseconds);
+ return files;
+}
+
+/// Parses every file in [files] and reports the time spent doing so.
+void parseFiles(Set<Source> files) {
+ // The code below will record again how many chars are scanned and how long it
+ // takes to scan them, even though we already did so in [scanReachableFiles].
+ // Recording and reporting this twice is unnecessary, but we do so for now to
+ // validate that the results are consistent.
+ scanTimer = new Stopwatch();
+ var old = scanTotalChars;
+ scanTotalChars = 0;
+ var parseTimer = new Stopwatch()..start();
+ for (var source in files) {
+ parseFull(source);
+ }
+ parseTimer.stop();
+
+ // Report size and scanning time again. See discussion above.
+ if (old != scanTotalChars) print('input size changed? ${old} chars');
+ report("scan", scanTimer.elapsedMicroseconds);
+
+ var pTime = parseTimer.elapsedMicroseconds - scanTimer.elapsedMicroseconds;
+ report("parse", pTime);
+}
+
+/// Add to [files] all sources reachable from [start].
+void collectSources(Source start, Set<Source> files) {
+ if (!files.add(start)) return;
+ var unit = parseDirectives(start);
+ for (var directive in unit.directives) {
+ if (directive is UriBasedDirective) {
+ var next = sources.resolveUri(start, directive.uri.stringValue);
+ collectSources(next, files);
+ }
+ }
+}
+
+/// Uses the diet-parser to parse only directives in [source].
+CompilationUnit parseDirectives(Source source) {
+ var token = tokenize(source);
+ var parser = new Parser(source, AnalysisErrorListener.NULL_LISTENER);
+ return parser.parseDirectives(token);
+}
+
+/// Parse the full body of [source] and return it's compilation unit.
+CompilationUnit parseFull(Source source) {
+ var token = tokenize(source);
+ var parser = new Parser(source, AnalysisErrorListener.NULL_LISTENER);
+ return parser.parseCompilationUnit(token);
+}
+
+/// Scan [source] and return the first token produced by the scanner.
+Token tokenize(Source source) {
+ scanTimer.start();
+ var contents = source.contents.data;
+ scanTotalChars += contents.length;
+ // TODO(sigmund): is there a way to scan from a random-access-file without
+ // first converting to String?
+ var scanner = new Scanner(source, new CharSequenceReader(contents),
+ AnalysisErrorListener.NULL_LISTENER);
+ var token = scanner.tokenize();
+ scanTimer.stop();
+ return token;
+}
+
+/// Report that metric [name] took [time] micro-seconds to process
+/// [scanTotalChars] characters.
+void report(String name, int time) {
+ var sb = new StringBuffer();
+ sb.write('$name: $time us, ${time ~/ 1000} ms');
+ sb.write(', ${scanTotalChars * 1000 ~/ time} chars/ms');
+ print('$sb');
+}
diff --git a/pkg/analyzer_cli/tool/perf_test.dart b/pkg/analyzer_cli/tool/perf_test.dart
new file mode 100644
index 0000000..3302a51
--- /dev/null
+++ b/pkg/analyzer_cli/tool/perf_test.dart
@@ -0,0 +1,11 @@
+// Copyright (c) 2016, 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.
+
+/// The only purpose of this file is to enable analyzer tests on `perf.dart`,
+/// the code here just has a dummy import to the rest of the code.
+library analyzer_cli.tool.perf_test;
+
+import 'perf.dart' as m;
+
+main() => print('done ${m.scanTotalChars}');
diff --git a/pkg/compiler/lib/src/elements/common.dart b/pkg/compiler/lib/src/elements/common.dart
index 2e99eff..3e430d2 100644
--- a/pkg/compiler/lib/src/elements/common.dart
+++ b/pkg/compiler/lib/src/elements/common.dart
@@ -494,6 +494,8 @@
}
abstract class FunctionSignatureCommon implements FunctionSignature {
+ DartType get returnType => type.returnType;
+
void forEachRequiredParameter(void function(Element parameter)) {
requiredParameters.forEach(function);
}
diff --git a/pkg/compiler/lib/src/elements/elements.dart b/pkg/compiler/lib/src/elements/elements.dart
index 1df89f8..814e1fb 100644
--- a/pkg/compiler/lib/src/elements/elements.dart
+++ b/pkg/compiler/lib/src/elements/elements.dart
@@ -1175,6 +1175,7 @@
abstract class FunctionSignature {
FunctionType get type;
+ DartType get returnType;
List<DartType> get typeVariables;
List<FormalElement> get requiredParameters;
List<FormalElement> get optionalParameters;
diff --git a/pkg/compiler/lib/src/js_backend/backend.dart b/pkg/compiler/lib/src/js_backend/backend.dart
index 41e7227..f688ff7 100644
--- a/pkg/compiler/lib/src/js_backend/backend.dart
+++ b/pkg/compiler/lib/src/js_backend/backend.dart
@@ -2820,8 +2820,10 @@
case Feature.FALL_THROUGH_ERROR:
registerBackendImpact(transformed, impacts.fallThroughError);
break;
- case Feature.INC_DEC_OPERATION:
- registerBackendImpact(transformed, impacts.incDecOperation);
+ case Feature.FIELD_WITHOUT_INITIALIZER:
+ transformed.registerTypeUse(
+ new TypeUse.instantiation(backend.coreTypes.nullType));
+ registerBackendImpact(transformed, impacts.nullLiteral);
break;
case Feature.LAZY_FIELD:
registerBackendImpact(transformed, impacts.lazyField);
diff --git a/pkg/compiler/lib/src/js_backend/backend_impact.dart b/pkg/compiler/lib/src/js_backend/backend_impact.dart
index 9a9a0d1..7fb1e9c 100644
--- a/pkg/compiler/lib/src/js_backend/backend_impact.dart
+++ b/pkg/compiler/lib/src/js_backend/backend_impact.dart
@@ -306,16 +306,6 @@
return _constSymbol;
}
- BackendImpact _incDecOperation;
-
- BackendImpact get incDecOperation {
- if (_incDecOperation == null) {
- _incDecOperation =
- _needsInt('Needed for the `+ 1` or `- 1` operation of ++/--.');
- }
- return _incDecOperation;
- }
-
/// Helper for registering that `int` is needed.
BackendImpact _needsInt(String reason) {
// TODO(johnniwinther): Register [reason] for use in dump-info.
diff --git a/pkg/compiler/lib/src/js_backend/constant_emitter.dart b/pkg/compiler/lib/src/js_backend/constant_emitter.dart
index e30ef91..31bcccb 100644
--- a/pkg/compiler/lib/src/js_backend/constant_emitter.dart
+++ b/pkg/compiler/lib/src/js_backend/constant_emitter.dart
@@ -315,7 +315,7 @@
fields.add(_reifiedTypeArguments(constant.type));
}
jsAst.New instantiation = new jsAst.New(constructor, fields);
- return maybeAddTypeArguments(constant.type, instantiation);
+ return instantiation;
}
String stripComments(String rawJavaScript) {
diff --git a/pkg/compiler/lib/src/js_backend/kernel_task.dart b/pkg/compiler/lib/src/js_backend/kernel_task.dart
index 7f53580..0c59fa4 100644
--- a/pkg/compiler/lib/src/js_backend/kernel_task.dart
+++ b/pkg/compiler/lib/src/js_backend/kernel_task.dart
@@ -22,7 +22,6 @@
///
/// May enqueue more elements to the resolution queue.
void buildKernelIr() {
- kernel.functionToIr(_compiler.mainFunction);
- kernel.processWorkQueue();
+ kernel.libraryDependencies(_compiler.options.entryPoint);
}
}
diff --git a/pkg/compiler/lib/src/kernel/kernel.dart b/pkg/compiler/lib/src/kernel/kernel.dart
index d5f1151..fa53c0e 100644
--- a/pkg/compiler/lib/src/kernel/kernel.dart
+++ b/pkg/compiler/lib/src/kernel/kernel.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.md file.
+import 'dart:async';
import 'dart:collection' show Queue;
import 'package:kernel/ast.dart' as ir;
@@ -18,8 +19,10 @@
ClassElement,
ConstructorElement,
Element,
+ ExportElement,
FieldElement,
FunctionElement,
+ ImportElement,
LibraryElement,
MixinApplicationElement,
TypeVariableElement;
@@ -117,6 +120,10 @@
return new ir.Name(name, irLibrary);
}
+ Future<ir.Library> loadLibrary(Uri uri) async {
+ return libraryToIr(await compiler.libraryLoader.loadLibrary(uri));
+ }
+
ir.Library libraryToIr(LibraryElement library) {
library = library.declaration;
return libraries.putIfAbsent(library, () {
@@ -489,6 +496,10 @@
throw message;
}
+ forEachLibraryElement(f(LibraryElement library)) {
+ return compiler.libraryLoader.libraries.forEach(f);
+ }
+
ConstructorTarget computeEffectiveTarget(
ConstructorElement constructor, DartType type) {
constructor = constructor.implementation;
@@ -505,6 +516,59 @@
return new ConstructorTarget(constructor, type);
}
+ /// Compute all the dependencies on the library with [uri] (including the
+ /// library itself). This is useful for creating a Kernel IR `Program`.
+ List<ir.Library> libraryDependencies(Uri uri) {
+ List<ir.Library> result = <ir.Library>[];
+ Queue<LibraryElement> notProcessed = new Queue<LibraryElement>();
+ Set<LibraryElement> seen = new Set<LibraryElement>();
+ LibraryElement library = compiler.libraryLoader.lookupLibrary(uri);
+ void processLater(LibraryElement library) {
+ if (library != null) {
+ notProcessed.addLast(library);
+ }
+ }
+
+ processLater(library);
+ seen.add(library);
+ LibraryElement core =
+ compiler.libraryLoader.lookupLibrary(Uri.parse("dart:core"));
+ if (seen.add(core)) {
+ // `dart:core` is implicitly imported by most libraries, and for some
+ // reason not included in `library.imports` below.
+ processLater(core);
+ }
+ while (notProcessed.isNotEmpty) {
+ LibraryElement library = notProcessed.removeFirst();
+ ir.Library irLibrary = libraryToIr(library);
+ for (ImportElement import in library.imports) {
+ if (seen.add(import.importedLibrary)) {
+ processLater(import.importedLibrary);
+ }
+ }
+ for (ExportElement export in library.exports) {
+ if (seen.add(export.exportedLibrary)) {
+ processLater(export.exportedLibrary);
+ }
+ }
+ for (ImportElement import in library.implementation.imports) {
+ if (seen.add(import.importedLibrary)) {
+ processLater(import.importedLibrary);
+ }
+ }
+ for (ExportElement export in library.implementation.exports) {
+ if (seen.add(export.exportedLibrary)) {
+ processLater(export.exportedLibrary);
+ }
+ }
+ if (irLibrary != null) {
+ result.add(irLibrary);
+ }
+ }
+ processWorkQueue();
+ return result;
+ }
+
/// Returns true if [element] is synthesized to recover or represent a
/// semantic error, for example, missing, duplicated, or ambiguous elements.
/// However, returns false for elements that have an unrecoverable syntax
diff --git a/pkg/compiler/lib/src/kernel/kernel_debug.dart b/pkg/compiler/lib/src/kernel/kernel_debug.dart
new file mode 100644
index 0000000..7258161
--- /dev/null
+++ b/pkg/compiler/lib/src/kernel/kernel_debug.dart
@@ -0,0 +1,45 @@
+// Copyright (c) 2016, 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.
+
+/// Helper for debug Kernel nodes.
+
+library kernel.debug;
+
+import 'package:kernel/kernel.dart';
+import 'package:kernel/visitor.dart';
+
+import '../util/util.dart' show Indentation, Tagging;
+
+class DebugPrinter extends Visitor with Indentation, Tagging<Node> {
+ StringBuffer sb = new StringBuffer();
+
+ void visitNodeWithChildren(Node node, String type, [Map params]) {
+ openNode(node, type, params);
+ node.visitChildren(this);
+ closeNode();
+ }
+
+ @override
+ void defaultNode(Node node) {
+ visitNodeWithChildren(node, '${node.runtimeType}');
+ }
+
+ @override
+ void visitName(Name node) {
+ openAndCloseNode(node, '${node.runtimeType}',
+ {'name': node.name, 'library': node.library?.name});
+ }
+
+ @override
+ void visitIntLiteral(IntLiteral node) {
+ openAndCloseNode(node, '${node.runtimeType}', {'value': '${node.value}'});
+ }
+
+ /// Pretty-prints given node tree into string.
+ static String prettyPrint(Node node) {
+ var p = new DebugPrinter();
+ node.accept(p);
+ return p.sb.toString();
+ }
+}
diff --git a/pkg/compiler/lib/src/kernel/kernel_visitor.dart b/pkg/compiler/lib/src/kernel/kernel_visitor.dart
index c2d458c..26f3b3a 100644
--- a/pkg/compiler/lib/src/kernel/kernel_visitor.dart
+++ b/pkg/compiler/lib/src/kernel/kernel_visitor.dart
@@ -861,10 +861,12 @@
for (Expression element in node.elements.nodes) {
elements.add(visitForValue(element));
}
- return new ir.ListLiteral(elements,
- typeArgument: computeTypeFromTypes(node.typeArguments),
- // TODO(ahe): Should constness be validated?
- isConst: node.isConst);
+ return associateNode(
+ new ir.ListLiteral(elements,
+ typeArgument: computeTypeFromTypes(node.typeArguments),
+ // TODO(ahe): Should constness be validated?
+ isConst: node.isConst),
+ node);
}
@override
@@ -877,11 +879,13 @@
}
List<ir.DartType> typeArguments =
computeTypesFromTypes(node.typeArguments, expected: 2);
- return new ir.MapLiteral(entries,
- keyType: typeArguments.first,
- valueType: typeArguments.last,
- // TODO(ahe): Should Constness be validated?
- isConst: node.isConst);
+ return associateNode(
+ new ir.MapLiteral(entries,
+ keyType: typeArguments.first,
+ valueType: typeArguments.last,
+ // TODO(ahe): Should Constness be validated?
+ isConst: node.isConst),
+ node);
}
@override
@@ -1245,14 +1249,17 @@
@override
ir.PropertyGet visitDynamicPropertyGet(
Send node, Node receiver, Name name, _) {
- return new ir.PropertyGet(visitForValue(receiver), nameToIrName(name));
+ return associateNode(
+ new ir.PropertyGet(visitForValue(receiver), nameToIrName(name)), node);
}
@override
ir.MethodInvocation visitDynamicPropertyInvoke(
Send node, Node receiver, NodeList arguments, Selector selector, _) {
- return buildInvokeSelector(
- visitForValue(receiver), selector, buildArguments(arguments));
+ return associateNode(
+ buildInvokeSelector(
+ visitForValue(receiver), selector, buildArguments(arguments)),
+ node);
}
@override
@@ -1260,9 +1267,15 @@
Send node, Node receiver, Name name, CompoundRhs rhs, _) {
ir.Expression receiverNode =
receiver == null ? new ir.ThisExpression() : visitForValue(receiver);
- return buildCompound(
+ ir.Expression compound = buildCompound(
PropertyAccessor.make(receiverNode, nameToIrName(name), null, null),
rhs);
+ if (compound is ir.VariableSet) {
+ associateNode(compound.value, node);
+ } else {
+ associateNode(compound, node);
+ }
+ return compound;
}
@override
@@ -1314,13 +1327,14 @@
@override
ir.MethodInvocation visitEquals(Send node, Node left, Node right, _) {
- return buildBinaryOperator(left, '==', right);
+ return associateNode(buildBinaryOperator(left, '==', right), node);
}
@override
ir.MethodInvocation visitExpressionInvoke(Send node, Node expression,
NodeList arguments, CallStructure callStructure, _) {
- return buildCall(visitForValue(expression), callStructure, arguments);
+ return associateNode(
+ buildCall(visitForValue(expression), callStructure, arguments), node);
}
@override
@@ -1556,7 +1570,8 @@
@override
ir.Expression visitIndex(Send node, Node receiver, Node index, _) {
- return buildIndexAccessor(receiver, index).buildSimpleRead();
+ return associateNode(
+ buildIndexAccessor(receiver, index).buildSimpleRead(), node);
}
ir.Expression buildIndexPostfix(Accessor accessor, IncDecOperator operator) {
@@ -1584,8 +1599,10 @@
@override
ir.Expression visitIndexSet(
SendSet node, Node receiver, Node index, Node rhs, _) {
- return buildIndexAccessor(receiver, index)
- .buildAssignment(visitForValue(rhs), voidContext: isVoidContext);
+ return associateNode(
+ buildIndexAccessor(receiver, index)
+ .buildAssignment(visitForValue(rhs), voidContext: isVoidContext),
+ node);
}
ir.Initializer buildInitializingFormal(InitializingFormalElement parameter) {
@@ -1711,7 +1728,14 @@
ir.Expression handleLocalCompounds(
SendSet node, LocalElement local, CompoundRhs rhs, _,
{bool isSetterValid}) {
- return buildCompound(new VariableAccessor(getLocal(local)), rhs);
+ ir.Expression compound =
+ buildCompound(new VariableAccessor(getLocal(local)), rhs);
+ if (compound is ir.VariableSet) {
+ associateNode(compound.value, node);
+ } else {
+ associateNode(compound, node);
+ }
+ return compound;
}
@override
@@ -1761,7 +1785,9 @@
@override
ir.Not visitNotEquals(Send node, Node left, Node right, _) {
- return new ir.Not(buildBinaryOperator(left, '==', right));
+ return associateNode(
+ new ir.Not(associateNode(buildBinaryOperator(left, '==', right), node)),
+ node);
}
@override
@@ -1797,7 +1823,8 @@
@override
ir.MethodInvocation handleLocalInvoke(Send node, LocalElement element,
NodeList arguments, CallStructure callStructure, _) {
- return buildCall(buildLocalGet(element), callStructure, arguments);
+ return associateNode(
+ buildCall(buildLocalGet(element), callStructure, arguments), node);
}
@override
@@ -1899,7 +1926,8 @@
@override
ir.MethodInvocation handleStaticFieldInvoke(Send node, FieldElement field,
NodeList arguments, CallStructure callStructure, _) {
- return buildCall(buildStaticGet(field), callStructure, arguments);
+ return associateNode(
+ buildCall(buildStaticGet(field), callStructure, arguments), node);
}
@override
@@ -2391,7 +2419,7 @@
NodeList arguments,
CallStructure callStructure,
_) {
- return buildSuperMethodInvoke(method, arguments);
+ return associateNode(buildSuperMethodInvoke(method, arguments), node);
}
@override
@@ -2465,14 +2493,17 @@
@override
ir.Expression visitThisPropertyGet(Send node, Name name, _) {
- return buildThisPropertyAccessor(name).buildSimpleRead();
+ return associateNode(
+ buildThisPropertyAccessor(name).buildSimpleRead(), node);
}
@override
ir.MethodInvocation visitThisPropertyInvoke(
Send node, NodeList arguments, Selector selector, _) {
- return buildInvokeSelector(
- new ir.ThisExpression(), selector, buildArguments(arguments));
+ return associateNode(
+ buildInvokeSelector(
+ new ir.ThisExpression(), selector, buildArguments(arguments)),
+ node);
}
@override
@@ -2590,10 +2621,12 @@
@override
ir.MethodInvocation visitUnary(
Send node, UnaryOperator operator, Node expression, _) {
- return new ir.MethodInvocation(
- visitForValue(expression),
- kernel.irName(operator.selectorName, currentElement),
- new ir.Arguments.empty());
+ return associateNode(
+ new ir.MethodInvocation(
+ visitForValue(expression),
+ kernel.irName(operator.selectorName, currentElement),
+ new ir.Arguments.empty()),
+ node);
}
@override
diff --git a/pkg/compiler/lib/src/resolution/constructors.dart b/pkg/compiler/lib/src/resolution/constructors.dart
index 214ebf4..1ccf768 100644
--- a/pkg/compiler/lib/src/resolution/constructors.dart
+++ b/pkg/compiler/lib/src/resolution/constructors.dart
@@ -619,7 +619,9 @@
// This is not really resolving a type-annotation, but the name of the
// constructor. Therefore we allow deferred types.
DartType type = resolver.resolveTypeAnnotation(node,
- malformedIsError: inConstContext, deferredIsMalformed: false);
+ malformedIsError: inConstContext,
+ deferredIsMalformed: false,
+ registerCheckedModeCheck: false);
Send send = node.typeName.asSend();
PrefixElement prefix;
if (send != null) {
diff --git a/pkg/compiler/lib/src/resolution/members.dart b/pkg/compiler/lib/src/resolution/members.dart
index 14c1aab..39bd77d 100644
--- a/pkg/compiler/lib/src/resolution/members.dart
+++ b/pkg/compiler/lib/src/resolution/members.dart
@@ -456,8 +456,14 @@
resolver.constantCompiler.compileConstant(parameter);
});
});
+ if (!functionSignature.returnType.isDynamic) {
+ registry.registerTypeUse(
+ new TypeUse.checkedModeCheck(functionSignature.returnType));
+ }
functionSignature.forEachParameter((ParameterElement element) {
- registry.registerTypeUse(new TypeUse.checkedModeCheck(element.type));
+ if (!element.type.isDynamic) {
+ registry.registerTypeUse(new TypeUse.checkedModeCheck(element.type));
+ }
});
}
@@ -3403,7 +3409,7 @@
? new PrefixStructure(semantics, operator)
: new PostfixStructure(semantics, operator);
registry.registerSendStructure(node, sendStructure);
- registry.registerFeature(Feature.INC_DEC_OPERATION);
+ registry.registerConstantLiteral(new IntConstantExpression(1));
} else {
Node rhs = node.arguments.head;
visitExpression(rhs);
@@ -4057,11 +4063,13 @@
}
DartType resolveTypeAnnotation(TypeAnnotation node,
- {bool malformedIsError: false, bool deferredIsMalformed: true}) {
+ {bool malformedIsError: false,
+ bool deferredIsMalformed: true,
+ bool registerCheckedModeCheck: true}) {
DartType type = typeResolver.resolveTypeAnnotation(this, node,
malformedIsError: malformedIsError,
deferredIsMalformed: deferredIsMalformed);
- if (!type.isDynamic) {
+ if (registerCheckedModeCheck && !type.isDynamic) {
registry.registerTypeUse(new TypeUse.checkedModeCheck(type));
}
return type;
diff --git a/pkg/compiler/lib/src/resolution/resolution.dart b/pkg/compiler/lib/src/resolution/resolution.dart
index 743ede2..37c0933 100644
--- a/pkg/compiler/lib/src/resolution/resolution.dart
+++ b/pkg/compiler/lib/src/resolution/resolution.dart
@@ -400,8 +400,7 @@
reporter.reportErrorMessage(
element, MessageKind.FINAL_WITHOUT_INITIALIZER);
} else {
- // TODO(johnniwinther): Register a feature instead.
- registry.registerTypeUse(new TypeUse.instantiation(coreTypes.nullType));
+ registry.registerFeature(Feature.FIELD_WITHOUT_INITIALIZER);
}
if (Elements.isStaticOrTopLevelField(element)) {
diff --git a/pkg/compiler/lib/src/resolution/type_resolver.dart b/pkg/compiler/lib/src/resolution/type_resolver.dart
index c1fb6cc..274911d 100644
--- a/pkg/compiler/lib/src/resolution/type_resolver.dart
+++ b/pkg/compiler/lib/src/resolution/type_resolver.dart
@@ -176,7 +176,8 @@
} else {
type = new InterfaceType(
cls.declaration, arguments.toList(growable: false));
- addTypeVariableBoundsCheck = true;
+ addTypeVariableBoundsCheck =
+ arguments.any((DartType type) => !type.isDynamic);
}
}
} else if (element.isTypedef) {
@@ -195,7 +196,8 @@
type = typdef.rawType;
} else {
type = new TypedefType(typdef, arguments.toList(growable: false));
- addTypeVariableBoundsCheck = true;
+ addTypeVariableBoundsCheck =
+ arguments.any((DartType type) => !type.isDynamic);
}
}
} else if (element.isTypeVariable) {
diff --git a/pkg/compiler/lib/src/ssa/builder_kernel.dart b/pkg/compiler/lib/src/ssa/builder_kernel.dart
index 88cfe18..93eae3d 100644
--- a/pkg/compiler/lib/src/ssa/builder_kernel.dart
+++ b/pkg/compiler/lib/src/ssa/builder_kernel.dart
@@ -8,14 +8,14 @@
import '../common/codegen.dart' show CodegenRegistry, CodegenWorkItem;
import '../common/tasks.dart' show CompilerTask;
import '../compiler.dart';
+import '../dart_types.dart';
import '../elements/elements.dart';
import '../io/source_information.dart';
import '../js_backend/backend.dart' show JavaScriptBackend;
import '../kernel/kernel.dart';
-import '../kernel/kernel_visitor.dart';
-import '../resolution/tree_elements.dart';
import '../tree/dartstring.dart';
import '../types/masks.dart';
+import '../universe/selector.dart';
import 'graph_builder.dart';
import 'kernel_ast_adapter.dart';
@@ -37,23 +37,16 @@
return measure(() {
AstElement element = work.element.implementation;
Kernel kernel = backend.kernelTask.kernel;
- ir.Procedure function = kernel.functions[element];
- KernelSsaBuilder builder = new KernelSsaBuilder(
- function,
- element,
- work.resolvedAst,
- backend.compiler,
- work.registry,
- sourceInformationFactory,
- kernel);
+ KernelSsaBuilder builder = new KernelSsaBuilder(element, work.resolvedAst,
+ backend.compiler, work.registry, sourceInformationFactory, kernel);
return builder.build();
});
}
}
class KernelSsaBuilder extends ir.Visitor with GraphBuilder {
- final ir.Procedure function;
- final FunctionElement functionElement;
+ ir.Node target;
+ final AstElement targetElement;
final ResolvedAst resolvedAst;
final Compiler compiler;
final CodegenRegistry registry;
@@ -64,47 +57,74 @@
KernelAstAdapter astAdapter;
KernelSsaBuilder(
- this.function,
- this.functionElement,
+ this.targetElement,
this.resolvedAst,
this.compiler,
this.registry,
SourceInformationStrategy sourceInformationFactory,
Kernel kernel) {
- graph.element = functionElement;
+ graph.element = targetElement;
// TODO(het): Should sourceInformationBuilder be in GraphBuilder?
this.sourceInformationBuilder =
sourceInformationFactory.createBuilderForContext(resolvedAst);
graph.sourceInformation =
sourceInformationBuilder.buildVariableDeclaration();
- this.localsHandler =
- new LocalsHandler(this, functionElement, null, compiler);
- this.astAdapter = new KernelAstAdapter(
- compiler.backend,
- resolvedAst,
- kernel.nodeToAst,
- kernel.nodeToElement,
- kernel.functions,
- kernel.classes,
- kernel.libraries);
+ this.localsHandler = new LocalsHandler(this, targetElement, null, compiler);
+ this.astAdapter = new KernelAstAdapter(kernel, compiler.backend,
+ resolvedAst, kernel.nodeToAst, kernel.nodeToElement);
+ Element originTarget = targetElement;
+ if (originTarget.isPatch) {
+ originTarget = originTarget.origin;
+ }
+ if (originTarget is FunctionElement) {
+ target = kernel.functions[originTarget];
+ } else if (originTarget is FieldElement) {
+ target = kernel.fields[originTarget];
+ }
}
HGraph build() {
// TODO(het): no reason to do this here...
HInstruction.idCounter = 0;
- if (function.kind == ir.ProcedureKind.Method ||
- function.kind == ir.ProcedureKind.Operator) {
- buildMethod(function, functionElement);
- } else {
- compiler.reporter.internalError(
- functionElement,
- "Unable to convert this kind of Kernel "
- "procedure to SSA: ${function.kind}");
+ if (target is ir.Procedure) {
+ buildProcedure(target);
+ } else if (target is ir.Field) {
+ buildField(target);
+ } else if (target is ir.Constructor) {
+ // TODO(het): Actually handle this correctly
+ HBasicBlock block = graph.addNewBlock();
+ open(graph.entry);
+ close(new HGoto()).addSuccessor(block);
+ open(block);
+ closeAndGotoExit(new HGoto());
+ graph.finalize();
}
assert(graph.isValid());
return graph;
}
+ void buildProcedure(ir.Procedure procedure) {
+ if (procedure.kind == ir.ProcedureKind.Method ||
+ procedure.kind == ir.ProcedureKind.Operator ||
+ procedure.kind == ir.ProcedureKind.Getter ||
+ procedure.kind == ir.ProcedureKind.Factory) {
+ buildMethod(procedure);
+ } else {
+ compiler.reporter.internalError(
+ targetElement,
+ "Unable to convert this kind of Kernel "
+ "procedure to SSA: ${procedure.kind}");
+ }
+ }
+
+ void buildField(ir.Field field) {
+ openFunction();
+ field.initializer.accept(this);
+ HInstruction value = pop();
+ closeAndGotoExit(new HReturn(value, null));
+ closeFunction();
+ }
+
@override
HInstruction popBoolified() {
HInstruction value = pop();
@@ -123,17 +143,16 @@
}
/// Builds a SSA graph for [method].
- void buildMethod(ir.Procedure method, FunctionElement functionElement) {
- openFunction(functionElement);
+ void buildMethod(ir.Procedure method) {
+ openFunction();
method.function.body.accept(this);
closeFunction();
}
- // TODO(het): get function element from astAdapter?
- void openFunction(FunctionElement functionElement) {
+ void openFunction() {
HBasicBlock block = graph.addNewBlock();
open(graph.entry);
- localsHandler.startFunction(functionElement, resolvedAst.node);
+ localsHandler.startFunction(targetElement, resolvedAst.node);
close(new HGoto()).addSuccessor(block);
open(block);
@@ -145,6 +164,12 @@
}
@override
+ void defaultExpression(ir.Expression expression) {
+ // TODO(het): This is only to get tests working
+ stack.add(graph.addConstantNull(compiler));
+ }
+
+ @override
void visitBlock(ir.Block block) {
assert(!isAborted());
for (ir.Statement statement in block.statements) {
@@ -166,7 +191,7 @@
}
@override
- visitExpressionStatement(ir.ExpressionStatement exprStatement) {
+ void visitExpressionStatement(ir.ExpressionStatement exprStatement) {
exprStatement.expression.accept(this);
pop();
}
@@ -189,52 +214,212 @@
@override
void visitIfStatement(ir.IfStatement ifStatement) {
- SsaBranchBuilder branchBuilder = new SsaBranchBuilder(this, compiler);
- branchBuilder.handleIf(
+ SsaBranchBuilder brancher = new SsaBranchBuilder(this, compiler);
+ brancher.handleIf(
() => ifStatement.condition.accept(this),
() => ifStatement.then.accept(this),
() => ifStatement.otherwise?.accept(this));
}
@override
+ void visitConditionalExpression(ir.ConditionalExpression conditional) {
+ SsaBranchBuilder brancher = new SsaBranchBuilder(this, compiler);
+ brancher.handleConditional(
+ () => conditional.condition.accept(this),
+ () => conditional.then.accept(this),
+ () => conditional.otherwise.accept(this));
+ }
+
+ @override
+ void visitLogicalExpression(ir.LogicalExpression logicalExpression) {
+ SsaBranchBuilder brancher = new SsaBranchBuilder(this, compiler);
+ brancher.handleLogicalBinary(() => logicalExpression.left.accept(this),
+ () => logicalExpression.right.accept(this),
+ isAnd: logicalExpression.operator == '&&');
+ }
+
+ @override
void visitIntLiteral(ir.IntLiteral intLiteral) {
stack.add(graph.addConstantInt(intLiteral.value, compiler));
}
@override
- visitDoubleLiteral(ir.DoubleLiteral doubleLiteral) {
+ void visitDoubleLiteral(ir.DoubleLiteral doubleLiteral) {
stack.add(graph.addConstantDouble(doubleLiteral.value, compiler));
}
@override
- visitBoolLiteral(ir.BoolLiteral boolLiteral) {
+ void visitBoolLiteral(ir.BoolLiteral boolLiteral) {
stack.add(graph.addConstantBool(boolLiteral.value, compiler));
}
@override
- visitStringLiteral(ir.StringLiteral stringLiteral) {
+ void visitStringLiteral(ir.StringLiteral stringLiteral) {
stack.add(graph.addConstantString(
new DartString.literal(stringLiteral.value), compiler));
}
@override
- visitSymbolLiteral(ir.SymbolLiteral symbolLiteral) {
+ void visitSymbolLiteral(ir.SymbolLiteral symbolLiteral) {
stack.add(graph.addConstant(
astAdapter.getConstantForSymbol(symbolLiteral), compiler));
registry?.registerConstSymbol(symbolLiteral.value);
}
@override
- visitNullLiteral(ir.NullLiteral nullLiteral) {
+ void visitNullLiteral(ir.NullLiteral nullLiteral) {
stack.add(graph.addConstantNull(compiler));
}
@override
- visitVariableGet(ir.VariableGet variableGet) {
+ void visitListLiteral(ir.ListLiteral listLiteral) {
+ HInstruction listInstruction;
+ if (listLiteral.isConst) {
+ listInstruction =
+ graph.addConstant(astAdapter.getConstantFor(listLiteral), compiler);
+ } else {
+ List<HInstruction> elements = <HInstruction>[];
+ for (ir.Expression element in listLiteral.expressions) {
+ element.accept(this);
+ elements.add(pop());
+ }
+ listInstruction = new HLiteralList(elements, backend.extendableArrayType);
+ add(listInstruction);
+ // TODO(het): set runtime type info
+ }
+
+ // TODO(het): Set the instruction type to the list type given by inference
+ stack.add(listInstruction);
+ }
+
+ @override
+ void visitMapLiteral(ir.MapLiteral mapLiteral) {
+ if (mapLiteral.isConst) {
+ stack.add(
+ graph.addConstant(astAdapter.getConstantFor(mapLiteral), compiler));
+ return;
+ }
+
+ // The map literal constructors take the key-value pairs as a List
+ List<HInstruction> constructorArgs = <HInstruction>[];
+ for (ir.MapEntry mapEntry in mapLiteral.entries) {
+ mapEntry.accept(this);
+ constructorArgs.add(pop());
+ constructorArgs.add(pop());
+ }
+
+ // The constructor is a procedure because it's a factory.
+ ir.Procedure constructor;
+ List<HInstruction> inputs = <HInstruction>[];
+ if (constructorArgs.isEmpty) {
+ constructor = astAdapter.mapLiteralConstructorEmpty;
+ } else {
+ constructor = astAdapter.mapLiteralConstructor;
+ HLiteralList argList =
+ new HLiteralList(constructorArgs, backend.extendableArrayType);
+ add(argList);
+ inputs.add(argList);
+ }
+
+ // TODO(het): Add type information
+ _pushStaticInvocation(constructor, inputs, backend.dynamicType);
+ }
+
+ @override
+ void visitMapEntry(ir.MapEntry mapEntry) {
+ // Visit value before the key because each will push an expression to the
+ // stack, so when we pop them off, the key is popped first, then the value.
+ mapEntry.value.accept(this);
+ mapEntry.key.accept(this);
+ }
+
+ @override
+ void visitStaticGet(ir.StaticGet staticGet) {
+ var staticTarget = staticGet.target;
+ Element element = astAdapter.getElement(staticTarget).declaration;
+ if (staticTarget is ir.Procedure &&
+ staticTarget.kind == ir.ProcedureKind.Getter) {
+ // Invoke the getter
+ _pushStaticInvocation(
+ target, const <HInstruction>[], astAdapter.returnTypeOf(target));
+ } else {
+ push(new HStatic(element, astAdapter.inferredTypeOf(staticTarget)));
+ }
+ }
+
+ @override
+ void visitStaticSet(ir.StaticSet staticSet) {
+ VariableElement field = astAdapter.getElement(staticSet.target);
+ staticSet.value.accept(this);
+ HInstruction value = pop();
+ add(new HStaticStore(field, value));
+ stack.add(value);
+ }
+
+ @override
+ void visitPropertyGet(ir.PropertyGet propertyGet) {
+ propertyGet.receiver.accept(this);
+ HInstruction receiver = pop();
+
+ List<HInstruction> inputs = <HInstruction>[];
+ bool isIntercepted = astAdapter.isIntercepted(propertyGet);
+ if (isIntercepted) {
+ HInterceptor interceptor = _interceptorFor(receiver);
+ inputs.add(interceptor);
+ }
+ inputs.add(receiver);
+
+ TypeMask type = astAdapter.selectorGetterTypeOf(propertyGet);
+
+ push(new HInvokeDynamicGetter(astAdapter.getGetterSelector(propertyGet),
+ astAdapter.typeOfGet(propertyGet), null, inputs, type));
+ }
+
+ @override
+ void visitVariableGet(ir.VariableGet variableGet) {
LocalElement local = astAdapter.getElement(variableGet.variable);
stack.add(localsHandler.readLocal(local));
}
+ @override
+ void visitVariableSet(ir.VariableSet variableSet) {
+ variableSet.value.accept(this);
+ HInstruction value = pop();
+ _visitLocalSetter(variableSet.variable, value);
+ }
+
+ @override
+ void visitVariableDeclaration(ir.VariableDeclaration declaration) {
+ LocalElement local = astAdapter.getElement(declaration);
+ if (declaration.initializer == null) {
+ HInstruction initialValue = graph.addConstantNull(compiler);
+ localsHandler.updateLocal(local, initialValue);
+ } else {
+ // TODO(het): handle case where the variable is top-level or static
+ declaration.initializer.accept(this);
+ HInstruction initialValue = pop();
+
+ _visitLocalSetter(declaration, initialValue);
+
+ // Ignore value
+ pop();
+ }
+ }
+
+ void _visitLocalSetter(ir.VariableDeclaration variable, HInstruction value) {
+ // TODO(het): handle case where the variable is top-level or static
+ LocalElement local = astAdapter.getElement(variable);
+
+ // Give the value a name if it doesn't have one already.
+ if (value.sourceElement == null) {
+ value.sourceElement = local;
+ }
+
+ stack.add(value);
+ // TODO(het): check or trust type
+ localsHandler.updateLocal(local, value);
+ }
+
// TODO(het): Also extract type arguments
/// Extracts the list of instructions for the expressions in the arguments.
List<HInstruction> _visitArguments(ir.Arguments arguments) {
@@ -253,16 +438,20 @@
}
@override
- visitStaticInvocation(ir.StaticInvocation invocation) {
+ void visitStaticInvocation(ir.StaticInvocation invocation) {
ir.Procedure target = invocation.target;
- bool targetCanThrow = astAdapter.getCanThrow(target);
TypeMask typeMask = astAdapter.returnTypeOf(target);
- var arguments = _visitArguments(invocation.arguments);
+ List<HInstruction> arguments = _visitArguments(invocation.arguments);
+ _pushStaticInvocation(target, arguments, typeMask);
+ }
+
+ void _pushStaticInvocation(
+ ir.Node target, List<HInstruction> arguments, TypeMask typeMask) {
HInstruction instruction = new HInvokeStatic(
astAdapter.getElement(target).declaration, arguments, typeMask,
- targetCanThrow: targetCanThrow);
+ targetCanThrow: astAdapter.getCanThrow(target));
instruction.sideEffects = astAdapter.getSideEffects(target);
push(instruction);
@@ -270,7 +459,7 @@
// TODO(het): Decide when to inline
@override
- visitMethodInvocation(ir.MethodInvocation invocation) {
+ void visitMethodInvocation(ir.MethodInvocation invocation) {
invocation.receiver.accept(this);
HInstruction receiver = pop();
@@ -281,9 +470,7 @@
bool isIntercepted = astAdapter.isIntercepted(invocation);
if (isIntercepted) {
- HInterceptor interceptor =
- new HInterceptor(receiver, backend.nonNullType);
- add(interceptor);
+ HInterceptor interceptor = _interceptorFor(receiver);
inputs.add(interceptor);
}
inputs.addAll(arguments);
@@ -294,13 +481,92 @@
astAdapter.typeOfInvocation(invocation), inputs, type, isIntercepted));
}
+ HInterceptor _interceptorFor(HInstruction intercepted) {
+ HInterceptor interceptor =
+ new HInterceptor(intercepted, backend.nonNullType);
+ add(interceptor);
+ return interceptor;
+ }
+
+ static ir.Class _containingClass(ir.TreeNode node) {
+ while (node != null) {
+ if (node is ir.Class) return node;
+ node = node.parent;
+ }
+ return null;
+ }
+
@override
- visitThisExpression(ir.ThisExpression thisExpression) {
+ void visitSuperMethodInvocation(ir.SuperMethodInvocation invocation) {
+ List<HInstruction> arguments = _visitArguments(invocation.arguments);
+ HInstruction receiver = localsHandler.readThis();
+ Selector selector = astAdapter.getSelector(invocation);
+ ir.Class surroundingClass = _containingClass(invocation);
+
+ List<HInstruction> inputs = <HInstruction>[];
+ if (astAdapter.isIntercepted(invocation)) {
+ inputs.add(_interceptorFor(receiver));
+ }
+ inputs.add(receiver);
+ inputs.addAll(arguments);
+
+ HInstruction instruction = new HInvokeSuper(
+ astAdapter.getElement(invocation.interfaceTarget),
+ astAdapter.getElement(surroundingClass),
+ selector,
+ inputs,
+ astAdapter.returnTypeOf(invocation.interfaceTarget),
+ null,
+ isSetter: selector.isSetter || selector.isIndexSet);
+ instruction.sideEffects =
+ compiler.world.getSideEffectsOfSelector(selector, null);
+ push(instruction);
+ }
+
+ @override
+ void visitConstructorInvocation(ir.ConstructorInvocation invocation) {
+ ir.Constructor target = invocation.target;
+ List<HInstruction> arguments = _visitArguments(invocation.arguments);
+ TypeMask typeMask = new TypeMask.nonNullExact(
+ astAdapter.getElement(target.enclosingClass), compiler.world);
+ _pushStaticInvocation(target, arguments, typeMask);
+ }
+
+ @override
+ void visitIsExpression(ir.IsExpression isExpression) {
+ isExpression.operand.accept(this);
+ HInstruction expression = pop();
+
+ DartType type = astAdapter.getDartType(isExpression.type);
+
+ if (backend.hasDirectCheckFor(type)) {
+ push(new HIs.direct(type, expression, backend.boolType));
+ return;
+ }
+
+ // The interceptor is not always needed. It is removed by optimization
+ // when the receiver type or tested type permit.
+ HInterceptor interceptor = _interceptorFor(expression);
+ push(new HIs.raw(type, expression, interceptor, backend.boolType));
+ }
+
+ @override
+ void visitThrow(ir.Throw throwNode) {
+ throwNode.expression.accept(this);
+ HInstruction expression = pop();
+ if (isReachable) {
+ push(new HThrowExpression(expression, null));
+ isReachable = false;
+ }
+ }
+
+ @override
+ void visitThisExpression(ir.ThisExpression thisExpression) {
stack.add(localsHandler.readThis());
}
@override
- visitNot(ir.Not not) {
+ void visitNot(ir.Not not) {
not.operand.accept(this);
push(new HNot(popBoolified(), backend.boolType));
}
diff --git a/pkg/compiler/lib/src/ssa/codegen_helpers.dart b/pkg/compiler/lib/src/ssa/codegen_helpers.dart
index eda5485..43515f8 100644
--- a/pkg/compiler/lib/src/ssa/codegen_helpers.dart
+++ b/pkg/compiler/lib/src/ssa/codegen_helpers.dart
@@ -681,7 +681,8 @@
// A [HIs] instruction uses its input multiple times, so we
// avoid generating it at use site.
if (user is HIs) return false;
- return true;
+ // Avoid code motion into a loop.
+ return user.hasSameLoopHeaderAs(input);
}
void visitBasicBlock(HBasicBlock block) {
diff --git a/pkg/compiler/lib/src/ssa/kernel_ast_adapter.dart b/pkg/compiler/lib/src/ssa/kernel_ast_adapter.dart
index 8682d35..4f31bb2 100644
--- a/pkg/compiler/lib/src/ssa/kernel_ast_adapter.dart
+++ b/pkg/compiler/lib/src/ssa/kernel_ast_adapter.dart
@@ -5,46 +5,46 @@
import 'package:kernel/ast.dart' as ir;
import '../common.dart';
+import '../common/names.dart';
import '../compiler.dart';
import '../constants/values.dart';
import '../dart_types.dart';
import '../elements/elements.dart';
import '../js_backend/js_backend.dart';
+import '../kernel/kernel.dart';
import '../resolution/tree_elements.dart';
import '../tree/tree.dart' as ast;
import '../types/masks.dart';
import '../universe/call_structure.dart';
import '../universe/selector.dart';
import '../universe/side_effects.dart';
-
import 'types.dart';
/// A helper class that abstracts all accesses of the AST from Kernel nodes.
///
/// The goal is to remove all need for the AST from the Kernel SSA builder.
class KernelAstAdapter {
+ final Kernel kernel;
final JavaScriptBackend _backend;
final ResolvedAst _resolvedAst;
final Map<ir.Node, ast.Node> _nodeToAst;
final Map<ir.Node, Element> _nodeToElement;
DartTypeConverter _typeConverter;
- KernelAstAdapter(
- this._backend,
- this._resolvedAst,
- this._nodeToAst,
- this._nodeToElement,
- Map<FunctionElement, ir.Member> functions,
- Map<ClassElement, ir.Class> classes,
- Map<LibraryElement, ir.Library> libraries) {
- for (FunctionElement functionElement in functions.keys) {
- _nodeToElement[functions[functionElement]] = functionElement;
+ KernelAstAdapter(this.kernel, this._backend, this._resolvedAst,
+ this._nodeToAst, this._nodeToElement) {
+ // TODO(het): Maybe just use all of the kernel maps directly?
+ for (FieldElement fieldElement in kernel.fields.keys) {
+ _nodeToElement[kernel.fields[fieldElement]] = fieldElement;
}
- for (ClassElement classElement in classes.keys) {
- _nodeToElement[classes[classElement]] = classElement;
+ for (FunctionElement functionElement in kernel.functions.keys) {
+ _nodeToElement[kernel.functions[functionElement]] = functionElement;
}
- for (LibraryElement libraryElement in libraries.keys) {
- _nodeToElement[libraries[libraryElement]] = libraryElement;
+ for (ClassElement classElement in kernel.classes.keys) {
+ _nodeToElement[kernel.classes[classElement]] = classElement;
+ }
+ for (LibraryElement libraryElement in kernel.libraries.keys) {
+ _nodeToElement[kernel.libraries[libraryElement]] = libraryElement;
}
_typeConverter = new DartTypeConverter(this);
}
@@ -73,12 +73,11 @@
return result;
}
- bool getCanThrow(ir.Procedure procedure) {
- FunctionElement function = getElement(procedure);
- return !_compiler.world.getCannotThrow(function);
+ bool getCanThrow(ir.Node procedure) {
+ return !_compiler.world.getCannotThrow(getElement(procedure));
}
- TypeMask returnTypeOf(ir.Procedure node) {
+ TypeMask returnTypeOf(ir.Member node) {
return TypeMaskFactory.inferredReturnTypeForElement(
getElement(node), _compiler);
}
@@ -93,18 +92,34 @@
return new CallStructure(argumentCount, namedArguments);
}
- // TODO(het): Create the selector directly from the invocation
- Selector getSelector(ir.MethodInvocation invocation) {
- SelectorKind kind = Elements.isOperatorName(invocation.name.name)
- ? SelectorKind.OPERATOR
- : SelectorKind.CALL;
+ Name getName(ir.Name name) {
+ return new Name(
+ name.name, name.isPrivate ? getElement(name.library) : null);
+ }
- ir.Name irName = invocation.name;
+ // TODO(het): Create the selector directly from the invocation
+ Selector getSelector(ir.InvocationExpression invocation) {
+ Name name = getName(invocation.name);
+ SelectorKind kind;
+ if (Elements.isOperatorName(invocation.name.name)) {
+ if (name == Names.INDEX_NAME || name == Names.INDEX_SET_NAME) {
+ kind = SelectorKind.INDEX;
+ } else {
+ kind = SelectorKind.OPERATOR;
+ }
+ } else {
+ kind = SelectorKind.CALL;
+ }
+
+ CallStructure callStructure = getCallStructure(invocation.arguments);
+ return new Selector(kind, name, callStructure);
+ }
+
+ Selector getGetterSelector(ir.PropertyGet getter) {
+ ir.Name irName = getter.name;
Name name = new Name(
irName.name, irName.isPrivate ? getElement(irName.library) : null);
- CallStructure callStructure = getCallStructure(invocation.arguments);
-
- return new Selector(kind, name, callStructure);
+ return new Selector.getter(name);
}
TypeMask typeOfInvocation(ir.MethodInvocation invocation) {
@@ -112,18 +127,56 @@
.typeOfSend(getNode(invocation), _elements);
}
+ TypeMask typeOfGet(ir.PropertyGet getter) {
+ return _compiler.globalInference.results
+ .typeOfSend(getNode(getter), _elements);
+ }
+
+ TypeMask inferredTypeOf(ir.Member node) {
+ return TypeMaskFactory.inferredTypeForElement(getElement(node), _compiler);
+ }
+
TypeMask selectorTypeOf(ir.MethodInvocation invocation) {
return TypeMaskFactory.inferredTypeForSelector(
getSelector(invocation), typeOfInvocation(invocation), _compiler);
}
- bool isIntercepted(ir.MethodInvocation invocation) {
- return _backend.isInterceptedSelector(getSelector(invocation));
+ TypeMask selectorGetterTypeOf(ir.PropertyGet getter) {
+ return TypeMaskFactory.inferredTypeForSelector(
+ getGetterSelector(getter), typeOfGet(getter), _compiler);
}
+ ConstantValue getConstantFor(ir.Node node) {
+ ConstantValue constantValue =
+ _backend.constants.getConstantValueForNode(getNode(node), _elements);
+ assert(invariant(getNode(node), constantValue != null,
+ message: 'No constant computed for $node'));
+ return constantValue;
+ }
+
+ bool isIntercepted(ir.Node node) {
+ Selector selector;
+ if (node is ir.PropertyGet) {
+ selector = getGetterSelector(node);
+ } else {
+ selector = getSelector(node);
+ }
+ return _backend.isInterceptedSelector(selector);
+ }
+
+ ir.Procedure get mapLiteralConstructor =>
+ kernel.functions[_backend.helpers.mapLiteralConstructor];
+
+ ir.Procedure get mapLiteralConstructorEmpty =>
+ kernel.functions[_backend.helpers.mapLiteralConstructorEmpty];
+
DartType getDartType(ir.DartType type) {
return type.accept(_typeConverter);
}
+
+ List<DartType> getDartTypes(List<ir.DartType> types) {
+ return types.map(getDartType).toList();
+ }
}
class DartTypeConverter extends ir.DartTypeVisitor<DartType> {
diff --git a/pkg/compiler/lib/src/ssa/kernel_impact.dart b/pkg/compiler/lib/src/ssa/kernel_impact.dart
index 30f66a5..15efe23 100644
--- a/pkg/compiler/lib/src/ssa/kernel_impact.dart
+++ b/pkg/compiler/lib/src/ssa/kernel_impact.dart
@@ -11,9 +11,11 @@
import '../elements/elements.dart';
import '../js_backend/backend.dart' show JavaScriptBackend;
import '../kernel/kernel.dart';
+import '../kernel/kernel_debug.dart';
import '../kernel/kernel_visitor.dart';
import '../resolution/registry.dart' show ResolutionWorldImpactBuilder;
import '../universe/feature.dart';
+import '../universe/selector.dart';
import '../universe/use.dart';
import 'kernel_ast_adapter.dart';
@@ -24,19 +26,27 @@
AstElement element = resolvedAst.element.implementation;
JavaScriptBackend backend = compiler.backend;
Kernel kernel = backend.kernelTask.kernel;
- ir.Procedure function = kernel.functions[element];
- if (function == null) {
- print("FOUND NULL FUNCTION: $element");
- print(kernel.functions);
- }
KernelImpactBuilder builder =
- new KernelImpactBuilder(function, element, resolvedAst, compiler, kernel);
- return builder.build();
+ new KernelImpactBuilder(resolvedAst, compiler, kernel);
+ if (element.isFunction) {
+ ir.Procedure function = kernel.functions[element];
+ if (function == null) {
+ print("FOUND NULL FUNCTION: $element");
+ } else {
+ return builder.buildProcedure(function);
+ }
+ } else {
+ ir.Field field = kernel.fields[element];
+ if (field == null) {
+ print("FOUND NULL FUNCTION: $element");
+ } else {
+ return builder.buildField(field);
+ }
+ }
+ return null;
}
class KernelImpactBuilder extends ir.Visitor {
- final ir.Procedure function;
- final FunctionElement functionElement;
final ResolvedAst resolvedAst;
final Compiler compiler;
@@ -45,42 +55,46 @@
ResolutionWorldImpactBuilder impactBuilder;
KernelAstAdapter astAdapter;
- KernelImpactBuilder(this.function, this.functionElement, this.resolvedAst,
- this.compiler, Kernel kernel) {
- this.impactBuilder = new ResolutionWorldImpactBuilder('$functionElement');
- this.astAdapter = new KernelAstAdapter(
- compiler.backend,
- resolvedAst,
- kernel.nodeToAst,
- kernel.nodeToElement,
- kernel.functions,
- kernel.classes,
- kernel.libraries);
- }
-
- ResolutionImpact build() {
- if (function.kind == ir.ProcedureKind.Method ||
- function.kind == ir.ProcedureKind.Operator) {
- buildMethod(function);
- } else {
- compiler.reporter.internalError(
- functionElement,
- "Unable to compute resolution impact for this kind of Kernel "
- "procedure: ${function.kind}");
- }
- return impactBuilder;
+ KernelImpactBuilder(this.resolvedAst, this.compiler, Kernel kernel) {
+ this.impactBuilder =
+ new ResolutionWorldImpactBuilder('${resolvedAst.element}');
+ this.astAdapter = new KernelAstAdapter(kernel, compiler.backend,
+ resolvedAst, kernel.nodeToAst, kernel.nodeToElement);
}
/// Add a checked-mode type use of [type] if it is not `dynamic`.
- DartType checkType(DartType type) {
+ DartType checkType(ir.DartType irType) {
+ DartType type = astAdapter.getDartType(irType);
if (!type.isDynamic) {
impactBuilder.registerTypeUse(new TypeUse.checkedModeCheck(type));
}
return type;
}
- void buildMethod(ir.Procedure method) {
- method.function.body.accept(this);
+ ResolutionImpact buildField(ir.Field field) {
+ checkType(field.type);
+ if (field.initializer != null) {
+ field.initializer.accept(this);
+ } else {
+ impactBuilder.registerFeature(Feature.FIELD_WITHOUT_INITIALIZER);
+ }
+ return impactBuilder;
+ }
+
+ ResolutionImpact buildProcedure(ir.Procedure procedure) {
+ if (procedure.kind == ir.ProcedureKind.Method ||
+ procedure.kind == ir.ProcedureKind.Operator) {
+ checkType(procedure.function.returnType);
+ procedure.function.positionalParameters.forEach((v) => checkType(v.type));
+ procedure.function.namedParameters.forEach((v) => checkType(v.type));
+ procedure.function.body.accept(this);
+ } else {
+ compiler.reporter.internalError(
+ resolvedAst.element,
+ "Unable to compute resolution impact for this kind of Kernel "
+ "procedure: ${procedure.kind}");
+ }
+ return impactBuilder;
}
void visitNodes(Iterable<ir.Node> nodes) {
@@ -144,8 +158,7 @@
@override
void visitListLiteral(ir.ListLiteral literal) {
visitNodes(literal.expressions);
- DartType elementType =
- checkType(astAdapter.getDartType(literal.typeArgument));
+ DartType elementType = checkType(literal.typeArgument);
impactBuilder.registerListLiteral(new ListLiteralUse(
compiler.coreTypes.listType(elementType),
@@ -156,8 +169,8 @@
@override
void visitMapLiteral(ir.MapLiteral literal) {
visitNodes(literal.entries);
- DartType keyType = checkType(astAdapter.getDartType(literal.keyType));
- DartType valueType = checkType(astAdapter.getDartType(literal.valueType));
+ DartType keyType = checkType(literal.keyType);
+ DartType valueType = checkType(literal.valueType);
impactBuilder.registerMapLiteral(new MapLiteralUse(
compiler.coreTypes.mapType(keyType, valueType),
isConstant: literal.isConst,
@@ -182,8 +195,50 @@
void visitStaticInvocation(ir.StaticInvocation invocation) {
_visitArguments(invocation.arguments);
Element target = astAdapter.getElement(invocation.target).declaration;
- impactBuilder.registerStaticUse(new StaticUse.staticInvoke(
- target, astAdapter.getCallStructure(invocation.arguments)));
+ if (target.isFactoryConstructor) {
+ impactBuilder.registerStaticUse(new StaticUse.constructorInvoke(
+ target, astAdapter.getCallStructure(invocation.arguments)));
+ // TODO(johnniwinther): We should not mark the type as instantiated but
+ // rather follow the type arguments directly.
+ //
+ // Consider this:
+ //
+ // abstract class A<T> {
+ // factory A.regular() => new B<T>();
+ // factory A.redirect() = B<T>;
+ // }
+ //
+ // class B<T> implements A<T> {}
+ //
+ // main() {
+ // print(new A<int>.regular() is B<int>);
+ // print(new A<String>.redirect() is B<String>);
+ // }
+ //
+ // To track that B is actually instantiated as B<int> and B<String> we
+ // need to follow the type arguments passed to A.regular and A.redirect
+ // to B. Currently, we only do this soundly if we register A<int> and
+ // A<String> as instantiated. We should instead register that A.T is
+ // instantiated as int and String.
+ ClassElement cls =
+ astAdapter.getElement(invocation.target.enclosingClass);
+ List<DartType> typeArguments =
+ astAdapter.getDartTypes(invocation.arguments.types);
+ impactBuilder.registerTypeUse(
+ new TypeUse.instantiation(new InterfaceType(cls, typeArguments)));
+ if (typeArguments.any((DartType type) => !type.isDynamic)) {
+ impactBuilder.registerFeature(Feature.TYPE_VARIABLE_BOUNDS_CHECK);
+ }
+ } else {
+ impactBuilder.registerStaticUse(new StaticUse.staticInvoke(
+ target, astAdapter.getCallStructure(invocation.arguments)));
+ }
+ }
+
+ @override
+ void visitStaticGet(ir.StaticGet node) {
+ Element target = astAdapter.getElement(node.target).declaration;
+ impactBuilder.registerStaticUse(new StaticUse.staticGet(target));
}
@override
@@ -195,7 +250,32 @@
}
@override
+ void visitPropertyGet(ir.PropertyGet node) {
+ node.receiver.accept(this);
+ impactBuilder.registerDynamicUse(new DynamicUse(
+ new Selector.getter(astAdapter.getName(node.name)), null));
+ }
+
+ @override
+ void visitPropertySet(ir.PropertySet node) {
+ node.receiver.accept(this);
+ node.value.accept(this);
+ impactBuilder.registerDynamicUse(new DynamicUse(
+ new Selector.setter(astAdapter.getName(node.name)), null));
+ }
+
+ @override
void visitNot(ir.Not not) {
not.operand.accept(this);
}
+
+ @override
+ void visitAssertStatement(ir.AssertStatement node) {
+ impactBuilder.registerFeature(
+ node.message != null ? Feature.ASSERT_WITH_MESSAGE : Feature.ASSERT);
+ node.visitChildren(this);
+ }
+
+ @override
+ void defaultNode(ir.Node node) => node.visitChildren(this);
}
diff --git a/pkg/compiler/lib/src/universe/feature.dart b/pkg/compiler/lib/src/universe/feature.dart
index a9faeb1..a7fd61f 100644
--- a/pkg/compiler/lib/src/universe/feature.dart
+++ b/pkg/compiler/lib/src/universe/feature.dart
@@ -40,8 +40,8 @@
/// A fall through in a switch case.
FALL_THROUGH_ERROR,
- /// A ++/-- operation.
- INC_DEC_OPERATION,
+ /// A field without an initializer.
+ FIELD_WITHOUT_INITIALIZER,
/// A field whose initialization is not a constant.
LAZY_FIELD,
diff --git a/pkg/dart2js_incremental/lib/caching_compiler.dart b/pkg/dart2js_incremental/lib/caching_compiler.dart
index 7401ba4..5582bab 100644
--- a/pkg/dart2js_incremental/lib/caching_compiler.dart
+++ b/pkg/dart2js_incremental/lib/caching_compiler.dart
@@ -14,6 +14,7 @@
CompilerImpl cachedCompiler,
Uri libraryRoot,
Uri packageRoot,
+ Uri packageConfig,
bool packagesAreImmutable: false,
Map<String, dynamic> environment,
Future<bool> reuseLibrary(LibraryElement library)}) {
@@ -60,6 +61,7 @@
new CompilerOptions.parse(
libraryRoot: libraryRoot,
packageRoot: packageRoot,
+ packageConfig: packageConfig,
options: options,
environment: environment));
JavaScriptBackend backend = compiler.backend;
diff --git a/pkg/dart2js_incremental/lib/dart2js_incremental.dart b/pkg/dart2js_incremental/lib/dart2js_incremental.dart
index 86ef905..e62c7c3 100644
--- a/pkg/dart2js_incremental/lib/dart2js_incremental.dart
+++ b/pkg/dart2js_incremental/lib/dart2js_incremental.dart
@@ -54,6 +54,7 @@
class IncrementalCompiler {
final Uri libraryRoot;
final Uri packageRoot;
+ final Uri packageConfig;
final CompilerInput inputProvider;
final CompilerDiagnostics diagnosticHandler;
final List<String> options;
@@ -67,6 +68,7 @@
IncrementalCompiler({
this.libraryRoot,
this.packageRoot,
+ this.packageConfig,
this.inputProvider,
this.diagnosticHandler,
this.options,
@@ -107,6 +109,7 @@
cachedCompiler: _compiler,
libraryRoot: libraryRoot,
packageRoot: packageRoot,
+ packageConfig: packageConfig,
inputProvider: inputProvider,
diagnosticHandler: diagnosticHandler,
options: options,
diff --git a/pkg/dev_compiler/karma.conf.js b/pkg/dev_compiler/karma.conf.js
index cf95523..3fbe32e 100644
--- a/pkg/dev_compiler/karma.conf.js
+++ b/pkg/dev_compiler/karma.conf.js
@@ -89,5 +89,9 @@
configuration.client.captureConsole = true;
}
+ if (process.env.DDC_BROWSERS) {
+ configuration.browsers = process.env.DDC_BROWSERS.split(':');
+ }
+
config.set(configuration);
};
diff --git a/pkg/dev_compiler/lib/js/amd/dart_sdk.js b/pkg/dev_compiler/lib/js/amd/dart_sdk.js
index 7d8c1b8..8ec4be2 100644
--- a/pkg/dev_compiler/lib/js/amd/dart_sdk.js
+++ b/pkg/dev_compiler/lib/js/amd/dart_sdk.js
@@ -1021,6 +1021,7 @@
if (!jsType) return;
let extProto = dartExtType.prototype;
let jsProto = jsType.prototype;
+ if (!jsProto) return;
jsProto[dart._extensionType] = dartExtType;
dart._installProperties(jsProto, extProto);
let originalSigFn = dart.getOwnPropertyDescriptor(dartExtType, dart._methodSig).get;
@@ -1761,7 +1762,7 @@
};
dart.nullSafe = function(obj, ...callbacks) {
if (obj == null) return obj;
- for (const callback of callbacks) {
+ for (let callback of callbacks) {
obj = callback(obj);
if (obj == null) break;
}
diff --git a/pkg/dev_compiler/lib/js/common/dart_sdk.js b/pkg/dev_compiler/lib/js/common/dart_sdk.js
index f8258be..1b39b69 100644
--- a/pkg/dev_compiler/lib/js/common/dart_sdk.js
+++ b/pkg/dev_compiler/lib/js/common/dart_sdk.js
@@ -1021,6 +1021,7 @@
if (!jsType) return;
let extProto = dartExtType.prototype;
let jsProto = jsType.prototype;
+ if (!jsProto) return;
jsProto[dart._extensionType] = dartExtType;
dart._installProperties(jsProto, extProto);
let originalSigFn = dart.getOwnPropertyDescriptor(dartExtType, dart._methodSig).get;
@@ -1761,7 +1762,7 @@
};
dart.nullSafe = function(obj, ...callbacks) {
if (obj == null) return obj;
- for (const callback of callbacks) {
+ for (let callback of callbacks) {
obj = callback(obj);
if (obj == null) break;
}
diff --git a/pkg/dev_compiler/lib/js/es6/dart_sdk.js b/pkg/dev_compiler/lib/js/es6/dart_sdk.js
index c37bee4..5a1b9f8 100644
--- a/pkg/dev_compiler/lib/js/es6/dart_sdk.js
+++ b/pkg/dev_compiler/lib/js/es6/dart_sdk.js
@@ -1019,6 +1019,7 @@
if (!jsType) return;
let extProto = dartExtType.prototype;
let jsProto = jsType.prototype;
+ if (!jsProto) return;
jsProto[dart._extensionType] = dartExtType;
dart._installProperties(jsProto, extProto);
let originalSigFn = dart.getOwnPropertyDescriptor(dartExtType, dart._methodSig).get;
@@ -1759,7 +1760,7 @@
};
dart.nullSafe = function(obj, ...callbacks) {
if (obj == null) return obj;
- for (const callback of callbacks) {
+ for (let callback of callbacks) {
obj = callback(obj);
if (obj == null) break;
}
diff --git a/pkg/dev_compiler/lib/js/legacy/dart_sdk.js b/pkg/dev_compiler/lib/js/legacy/dart_sdk.js
index a4d975f..1292685 100644
--- a/pkg/dev_compiler/lib/js/legacy/dart_sdk.js
+++ b/pkg/dev_compiler/lib/js/legacy/dart_sdk.js
@@ -1022,6 +1022,7 @@
if (!jsType) return;
let extProto = dartExtType.prototype;
let jsProto = jsType.prototype;
+ if (!jsProto) return;
jsProto[dart._extensionType] = dartExtType;
dart._installProperties(jsProto, extProto);
let originalSigFn = dart.getOwnPropertyDescriptor(dartExtType, dart._methodSig).get;
@@ -1762,7 +1763,7 @@
};
dart.nullSafe = function(obj, ...callbacks) {
if (obj == null) return obj;
- for (const callback of callbacks) {
+ for (let callback of callbacks) {
obj = callback(obj);
if (obj == null) break;
}
diff --git a/pkg/dev_compiler/lib/src/analyzer/context.dart b/pkg/dev_compiler/lib/src/analyzer/context.dart
index b70edea..734731b 100644
--- a/pkg/dev_compiler/lib/src/analyzer/context.dart
+++ b/pkg/dev_compiler/lib/src/analyzer/context.dart
@@ -1,5 +1,4 @@
// Copyright (c) 2015, 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.
@@ -8,19 +7,15 @@
show ResourceProvider, ResourceUriResolver;
import 'package:analyzer/file_system/physical_file_system.dart'
show PhysicalResourceProvider;
+import 'package:analyzer/source/custom_resolver.dart';
+import 'package:analyzer/source/package_map_resolver.dart';
+import 'package:analyzer/src/context/builder.dart';
import 'package:analyzer/src/context/context.dart' show AnalysisContextImpl;
import 'package:analyzer/src/dart/sdk/sdk.dart' show FolderBasedDartSdk;
import 'package:analyzer/src/generated/engine.dart'
show AnalysisContext, AnalysisEngine, AnalysisOptionsImpl;
-import 'package:analyzer/src/generated/java_io.dart' show JavaFile;
-import 'package:analyzer/src/generated/source.dart';
-import 'package:analyzer/src/generated/source_io.dart'
- show
- CustomUriResolver,
- DartUriResolver,
- PackageUriResolver,
- SourceFactory,
- UriResolver;
+import 'package:analyzer/src/generated/source.dart'
+ show DartUriResolver, SourceFactory, UriResolver;
import 'package:analyzer/src/summary/package_bundle_reader.dart'
show InSummaryUriResolver, InputPackagesResultProvider, SummaryDataStore;
import 'package:analyzer/src/summary/summary_sdk.dart' show SummaryBasedDartSdk;
@@ -157,26 +152,39 @@
List<UriResolver> fileResolvers,
SummaryDataStore summaryData,
ResourceProvider resourceProvider}) {
+ resourceProvider ??= PhysicalResourceProvider.INSTANCE;
var resolvers = <UriResolver>[];
if (options.customUrlMappings.isNotEmpty) {
- resolvers.add(new CustomUriResolver(options.customUrlMappings));
+ resolvers.add(
+ new CustomUriResolver(resourceProvider, options.customUrlMappings));
}
resolvers.add(sdkResolver);
if (summaryData != null) {
resolvers.add(new InSummaryUriResolver(resourceProvider, summaryData));
}
- if (fileResolvers == null) fileResolvers = createFileResolvers(options);
+ if (fileResolvers == null)
+ fileResolvers =
+ createFileResolvers(options, resourceProvider: resourceProvider);
resolvers.addAll(fileResolvers);
return new SourceFactory(resolvers, null, resourceProvider);
}
-List<UriResolver> createFileResolvers(AnalyzerOptions options) {
+List<UriResolver> createFileResolvers(AnalyzerOptions options,
+ {ResourceProvider resourceProvider}) {
+ resourceProvider ??= PhysicalResourceProvider.INSTANCE;
+ UriResolver packageResolver() {
+ ContextBuilder builder = new ContextBuilder(resourceProvider, null, null);
+ builder.defaultPackagesDirectoryPath = options.packageRoot;
+ return new PackageMapUriResolver(resourceProvider,
+ builder.convertPackagesToMap(builder.createPackageMap('')));
+ }
+
return [
- new ResourceUriResolver(PhysicalResourceProvider.INSTANCE),
+ new ResourceUriResolver(resourceProvider),
options.useMultiPackage
? new MultiPackageResolver(options.packagePaths)
- : new PackageUriResolver([new JavaFile(options.packageRoot)])
+ : packageResolver()
];
}
diff --git a/pkg/dev_compiler/lib/src/compiler/code_generator.dart b/pkg/dev_compiler/lib/src/compiler/code_generator.dart
index 783e7da..dd31245 100644
--- a/pkg/dev_compiler/lib/src/compiler/code_generator.dart
+++ b/pkg/dev_compiler/lib/src/compiler/code_generator.dart
@@ -2179,13 +2179,13 @@
// TODO(jmesserly): various problems here, see:
// https://github.com/dart-lang/dev_compiler/issues/116
var paramType = param.element.type;
- if (node is MethodDeclaration && _unsoundCovariant(paramType, true)) {
+ if (node is MethodDeclaration &&
+ (param.element.isCovariant || _unsoundCovariant(paramType, true)) &&
+ !_inWhitelistCode(node)) {
var castType = _emitType(paramType,
nameType: options.nameTypeTests || options.hoistTypeTests,
hoistType: options.hoistTypeTests);
- if (!_inWhitelistCode(node)) {
- body.add(js.statement('#._check(#);', [castType, jsParam]));
- }
+ body.add(js.statement('#._check(#);', [castType, jsParam]));
}
}
return body.isEmpty ? null : _statement(body);
@@ -2503,8 +2503,10 @@
var typeFormals = _emitTypeFormals(type.typeFormals);
var returnType = emitTypeRef(type.returnType);
if (type.typeFormals.isNotEmpty) {
- code = new JS.Block(
- [new JS.Block(_typeTable.discharge(type.typeFormals)), code]);
+ code = new JS.Block(<JS.Statement>[
+ new JS.Block(_typeTable.discharge(type.typeFormals)),
+ code
+ ]);
}
return new JS.Fun(formals, code,
typeParams: typeFormals, returnType: returnType);
@@ -4501,7 +4503,8 @@
var param =
_createTemporary('_', nodeTarget.staticType, nullable: false);
var baseNode = _stripNullAwareOp(node, param);
- tail.add(new JS.ArrowFun([_visit(param)], _visit(baseNode)));
+ tail.add(
+ new JS.ArrowFun(<JS.Parameter>[_visit(param)], _visit(baseNode)));
node = nodeTarget;
} else {
break;
diff --git a/pkg/dev_compiler/lib/src/compiler/command.dart b/pkg/dev_compiler/lib/src/compiler/command.dart
index 5aaf262..eff733c 100644
--- a/pkg/dev_compiler/lib/src/compiler/command.dart
+++ b/pkg/dev_compiler/lib/src/compiler/command.dart
@@ -91,6 +91,15 @@
}
var outPaths = argResults['out'] as List<String>;
var moduleFormats = parseModuleFormatOption(argResults);
+ bool singleOutFile = argResults['single-out-file'];
+ if (singleOutFile) {
+ for (var format in moduleFormats) {
+ if (format != ModuleFormat.amd && format != ModuleFormat.legacy) {
+ _usageException('Format $format cannot be combined with '
+ 'single-out-file. Only amd and legacy modes are supported.');
+ }
+ }
+ }
if (outPaths.isEmpty) {
_usageException('Please include the output file location. For example:\n'
@@ -137,7 +146,7 @@
// Write JS file, as well as source map and summary (if requested).
for (var i = 0; i < outPaths.length; i++) {
var outPath = outPaths[i];
- module.writeCodeSync(moduleFormats[i], outPath);
+ module.writeCodeSync(moduleFormats[i], singleOutFile, outPath);
if (module.summaryBytes != null) {
var summaryPath =
path.withoutExtension(outPath) + '.${compilerOpts.summaryExtension}';
diff --git a/pkg/dev_compiler/lib/src/compiler/compiler.dart b/pkg/dev_compiler/lib/src/compiler/compiler.dart
index b47ad25..bc1ae50 100644
--- a/pkg/dev_compiler/lib/src/compiler/compiler.dart
+++ b/pkg/dev_compiler/lib/src/compiler/compiler.dart
@@ -3,7 +3,7 @@
// BSD-style license that can be found in the LICENSE file.
import 'dart:collection' show HashSet, Queue;
-import 'dart:convert' show JSON;
+import 'dart:convert' show BASE64, JSON, UTF8;
import 'dart:io' show File;
import 'package:analyzer/dart/element/element.dart' show LibraryElement;
import 'package:analyzer/analyzer.dart'
@@ -161,6 +161,9 @@
/// into the output JavaScript module.
final bool sourceMapComment;
+ /// Whether to emit the source mapping file inline as a data url.
+ final bool inlineSourceMap;
+
/// Whether to emit a summary file containing API signatures.
///
/// This is required for a modular build process.
@@ -208,9 +211,14 @@
// TODO(ochafik): Simplify this code when our target platforms catch up.
final bool destructureNamedParams;
+ /// Mapping from absolute file paths to bazel short path to substitute in
+ /// source maps.
+ final Map<String, String> bazelMapping;
+
const CompilerOptions(
{this.sourceMap: true,
this.sourceMapComment: true,
+ this.inlineSourceMap: false,
this.summarizeApi: true,
this.summaryExtension: 'sum',
this.unsafeForceCompile: false,
@@ -221,11 +229,13 @@
this.hoistSignatureTypes: false,
this.nameTypeTests: true,
this.hoistTypeTests: true,
- this.useAngular2Whitelist: false});
+ this.useAngular2Whitelist: false,
+ this.bazelMapping: const {}});
CompilerOptions.fromArguments(ArgResults args)
: sourceMap = args['source-map'],
sourceMapComment = args['source-map-comment'],
+ inlineSourceMap = args['inline-source-map'],
summarizeApi = args['summarize'],
summaryExtension = args['summary-extension'],
unsafeForceCompile = args['unsafe-force-compile'],
@@ -236,7 +246,8 @@
hoistSignatureTypes = args['hoist-signature-types'],
nameTypeTests = args['name-type-tests'],
hoistTypeTests = args['hoist-type-tests'],
- useAngular2Whitelist = args['unsafe-angular2-whitelist'];
+ useAngular2Whitelist = args['unsafe-angular2-whitelist'],
+ bazelMapping = _parseBazelMappings(args['bazel-mapping']);
static void addArguments(ArgParser parser) {
parser
@@ -251,6 +262,8 @@
'disable if using X-SourceMap header',
defaultsTo: true,
hide: true)
+ ..addFlag('inline-source-map',
+ help: 'emit source mapping inline', defaultsTo: false)
..addFlag('emit-metadata',
help: 'emit metadata annotations queriable via mirrors',
defaultsTo: false)
@@ -276,7 +289,25 @@
help: 'Name types used in type tests', defaultsTo: true, hide: true)
..addFlag('hoist-type-tests',
help: 'Hoist types used in type tests', defaultsTo: true, hide: true)
- ..addFlag('unsafe-angular2-whitelist', defaultsTo: false, hide: true);
+ ..addFlag('unsafe-angular2-whitelist', defaultsTo: false, hide: true)
+ ..addOption('bazel-mapping',
+ help:
+ '--bazel-mapping=genfiles/to/library.dart,to/library.dart uses \n'
+ 'to/library.dart as the path for library.dart in source maps.',
+ allowMultiple: true,
+ splitCommas: false,
+ hide: true);
+ }
+
+ static Map<String, String> _parseBazelMappings(Iterable argument) {
+ var mappings = <String, String>{};
+ for (var mapping in argument) {
+ var splitMapping = mapping.split(',');
+ if (splitMapping.length >= 2) {
+ mappings[path.absolute(splitMapping[0])] = splitMapping[1];
+ }
+ }
+ return mappings;
}
}
@@ -343,7 +374,8 @@
//
// TODO(jmesserly): this should match our old logic, but I'm not sure we are
// correctly handling the pointer from the .js file to the .map file.
- JSModuleCode getCode(ModuleFormat format, String jsUrl, String mapUrl) {
+ JSModuleCode getCode(
+ ModuleFormat format, bool singleOutFile, String jsUrl, String mapUrl) {
var opts = new JS.JavaScriptPrintingOptions(
emitTypes: options.closure,
allowKeywordsInProperties: true,
@@ -358,22 +390,33 @@
printer = new JS.SimpleJavaScriptPrintingContext();
}
- var tree = transformModuleFormat(format, moduleTree);
+ var tree = transformModuleFormat(format, singleOutFile, moduleTree);
tree.accept(
new JS.Printer(opts, printer, localNamer: new JS.TemporaryNamer(tree)));
- if (options.sourceMap && options.sourceMapComment) {
- var relativeMapUrl = path
- .toUri(path.relative(path.fromUri(mapUrl), from: path.dirname(jsUrl)))
- .toString();
- assert(path.dirname(jsUrl) == path.dirname(mapUrl));
- printer.emit('\n//# sourceMappingURL=$relativeMapUrl\n');
+ Map builtMap;
+ if (options.sourceMap && sourceMap != null) {
+ builtMap =
+ placeSourceMap(sourceMap.build(jsUrl), mapUrl, options.bazelMapping);
+
+ if (options.sourceMapComment) {
+ var relativeMapUrl = path
+ .toUri(
+ path.relative(path.fromUri(mapUrl), from: path.dirname(jsUrl)))
+ .toString();
+ assert(path.dirname(jsUrl) == path.dirname(mapUrl));
+ printer.emit('\n//# sourceMappingURL=');
+ if (options.inlineSourceMap) {
+ var bytes = UTF8.encode(JSON.encode(builtMap));
+ var base64 = BASE64.encode(bytes);
+ printer..emit('data:application/json;base64,')..emit(base64);
+ } else {
+ printer.emit(relativeMapUrl);
+ }
+ printer.emit('\n');
+ }
}
- Map builtMap;
- if (sourceMap != null) {
- builtMap = placeSourceMap(sourceMap.build(jsUrl), mapUrl);
- }
return new JSModuleCode(printer.getText(), builtMap);
}
@@ -381,10 +424,22 @@
///
/// If [mapPath] is not supplied but [options.sourceMap] is set, mapPath
/// will default to [jsPath].map.
- void writeCodeSync(ModuleFormat format, String jsPath, [String mapPath]) {
- if (mapPath == null) mapPath = jsPath + '.map';
- var code = getCode(format, jsPath, mapPath);
- new File(jsPath).writeAsStringSync(code.code);
+ void writeCodeSync(ModuleFormat format, bool singleOutFile, String jsPath) {
+ String mapPath = jsPath + '.map';
+ var code = getCode(format, singleOutFile, jsPath, mapPath);
+ var c = code.code;
+ if (singleOutFile) {
+ // In singleOutFile mode we wrap each module in an eval statement to
+ // leverage sourceURL to improve the debugging experience when source maps
+ // are not enabled.
+ c += '\n//# sourceURL=${name}.js\n';
+ c = 'eval(${JSON.encode(c)});\n';
+ }
+ new File(jsPath).writeAsStringSync(c);
+ // TODO(jacobr): it is a bit strange we are writing the source map to a file
+ // even when options.inlineSourceMap is true. To be consistent perhaps we
+ // should also write a copy of the source file without a sourcemap even when
+ // inlineSourceMap is true.
if (code.sourceMap != null) {
new File(mapPath).writeAsStringSync(JSON.encode(code.sourceMap));
}
@@ -411,17 +466,22 @@
/// Adjusts the source paths in [sourceMap] to be relative to [sourceMapPath],
/// and returns the new map.
// TODO(jmesserly): find a new home for this.
-Map placeSourceMap(Map sourceMap, String sourceMapPath) {
+Map placeSourceMap(
+ Map sourceMap, String sourceMapPath, Map<String, String> bazelMappings) {
var dir = path.dirname(sourceMapPath);
-
var map = new Map.from(sourceMap);
- List list = new List.from(map['sources']);
+ var list = new List.from(map['sources']);
map['sources'] = list;
- String relative(String uri) =>
- path.toUri(path.relative(path.fromUri(uri), from: dir)).toString();
- for (int i = 0; i < list.length; i++) {
- list[i] = relative(list[i]);
+ String transformUri(String uri) {
+ var match = bazelMappings[path.absolute(uri)];
+ if (match != null) return match;
+
+ // Fall back to a relative path.
+ return path.toUri(path.relative(path.fromUri(uri), from: dir)).toString();
}
- map['file'] = relative(map['file']);
+ for (int i = 0; i < list.length; i++) {
+ list[i] = transformUri(list[i]);
+ }
+ map['file'] = transformUri(map['file']);
return map;
}
diff --git a/pkg/dev_compiler/lib/src/compiler/module_builder.dart b/pkg/dev_compiler/lib/src/compiler/module_builder.dart
index 7a4e845..828a0fa 100644
--- a/pkg/dev_compiler/lib/src/compiler/module_builder.dart
+++ b/pkg/dev_compiler/lib/src/compiler/module_builder.dart
@@ -46,23 +46,28 @@
/// [allowMultiple] formats to be specified, with each emitted into a separate
/// file.
void addModuleFormatOptions(ArgParser argParser, {bool allowMultiple: false}) {
- argParser.addOption('modules',
- help: 'module pattern to emit',
- allowed: [
- 'es6',
- 'common',
- 'amd',
- 'legacy', // deprecated
- 'node', // renamed to commonjs
- 'all' // to emit all flavors for the SDK
- ],
- allowedHelp: {
- 'es6': 'ECMAScript 6 modules',
- 'common': 'CommonJS/Node.js modules',
- 'amd': 'AMD/RequireJS modules'
- },
- allowMultiple: allowMultiple,
- defaultsTo: 'amd');
+ argParser
+ ..addOption('modules',
+ help: 'module pattern to emit',
+ allowed: [
+ 'es6',
+ 'common',
+ 'amd',
+ 'legacy', // deprecated
+ 'node', // renamed to commonjs
+ 'all' // to emit all flavors for the SDK
+ ],
+ allowedHelp: {
+ 'es6': 'ECMAScript 6 modules',
+ 'common': 'CommonJS/Node.js modules',
+ 'amd': 'AMD/RequireJS modules'
+ },
+ allowMultiple: allowMultiple,
+ defaultsTo: 'amd')
+ ..addFlag('single-out-file',
+ help: 'emit output so that libraries can be concatenated together into '
+ 'a single file. Only compatible with legacy and amd module formats.',
+ defaultsTo: false);
}
/// Transforms an ES6 [module] into a given module [format].
@@ -73,15 +78,17 @@
/// structure as possible with the original. The transformation is a shallow one
/// that affects the top-level module items, especially [ImportDeclaration]s and
/// [ExportDeclaration]s.
-Program transformModuleFormat(ModuleFormat format, Program module) {
+Program transformModuleFormat(
+ ModuleFormat format, bool singleOutFile, Program module) {
switch (format) {
case ModuleFormat.legacy:
- return new LegacyModuleBuilder().build(module);
+ return new LegacyModuleBuilder(singleOutFile).build(module);
case ModuleFormat.common:
- return new CommonJSModuleBuilder().build(module);
+ return new CommonJSModuleBuilder(singleOutFile).build(module);
case ModuleFormat.amd:
- return new AmdModuleBuilder().build(module);
+ return new AmdModuleBuilder(singleOutFile).build(module);
case ModuleFormat.es6:
+ assert(singleOutFile == false);
return module;
}
return null; // unreachable. suppresses a bogus analyzer message
@@ -130,6 +137,10 @@
/// Generates modules for with our legacy `dart_library.js` loading mechanism.
// TODO(jmesserly): remove this and replace with something that interoperates.
class LegacyModuleBuilder extends _ModuleBuilder {
+ /// The legacy module format always generates output compatible with a single
+ /// file mode.
+ LegacyModuleBuilder(bool singleOutFile);
+
Program build(Program module) {
// Collect imports/exports/statements.
visitProgram(module);
@@ -187,6 +198,14 @@
/// Generates CommonJS modules (used by Node.js).
class CommonJSModuleBuilder extends _ModuleBuilder {
+ final bool singleOutFile;
+
+ CommonJSModuleBuilder(this.singleOutFile) {
+ // singleOutFile mode is not currently supported by the CommonJS module
+ // builder.
+ assert(singleOutFile == false);
+ }
+
Program build(Program module) {
var importStatements = <Statement>[];
@@ -236,6 +255,10 @@
/// Generates AMD modules (used in browsers with RequireJS).
class AmdModuleBuilder extends _ModuleBuilder {
+ final bool singleOutFile;
+
+ AmdModuleBuilder(this.singleOutFile);
+
Program build(Program module) {
var importStatements = <Statement>[];
@@ -277,8 +300,15 @@
new Return(new ObjectInitializer(exportedProps, multiline: true)));
}
- var block = js.statement("define(#, function(#) { 'use strict'; #; });",
- [new ArrayInitializer(dependencies), fnParams, statements]);
+ var block = singleOutFile
+ ? js.statement("define(#, #, function(#) { 'use strict'; #; });", [
+ js.string(module.name, "'"),
+ new ArrayInitializer(dependencies),
+ fnParams,
+ statements
+ ])
+ : js.statement("define(#, function(#) { 'use strict'; #; });",
+ [new ArrayInitializer(dependencies), fnParams, statements]);
return new Program([block]);
}
diff --git a/pkg/dev_compiler/lib/src/compiler/side_effect_analysis.dart b/pkg/dev_compiler/lib/src/compiler/side_effect_analysis.dart
index d55c3fb..5da18ea 100644
--- a/pkg/dev_compiler/lib/src/compiler/side_effect_analysis.dart
+++ b/pkg/dev_compiler/lib/src/compiler/side_effect_analysis.dart
@@ -6,7 +6,7 @@
import 'package:analyzer/dart/ast/visitor.dart';
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/src/generated/constant.dart';
-import 'package:analyzer/src/generated/error.dart'
+import 'package:analyzer/error/listener.dart'
show AnalysisErrorListener, ErrorReporter;
import 'package:analyzer/src/generated/resolver.dart' show TypeProvider;
import 'package:analyzer/src/generated/source.dart' show Source;
diff --git a/pkg/dev_compiler/lib/src/compiler/type_utilities.dart b/pkg/dev_compiler/lib/src/compiler/type_utilities.dart
index 9c87835..260c200 100644
--- a/pkg/dev_compiler/lib/src/compiler/type_utilities.dart
+++ b/pkg/dev_compiler/lib/src/compiler/type_utilities.dart
@@ -73,6 +73,11 @@
return js.call('# || (# = #)', [temp, temp, typeRep]);
}
+ String _safeTypeName(String name) {
+ if (name == "<bottom>") return "bottom";
+ return name;
+ }
+
String _typeString(DartType type, {bool flat: false}) {
if (type is ParameterizedType && type.name != null) {
var clazz = type.name;
@@ -101,8 +106,7 @@
return "${paramString}To${rType}";
}
if (type is TypeParameterType) return type.name;
- if (type.name != null) return type.name;
- return "type";
+ return _safeTypeName(type.name ?? "type");
}
/// Heuristically choose a good name for the cache and generator
diff --git a/pkg/dev_compiler/package.json b/pkg/dev_compiler/package.json
index 4a87bf5..0c3ef0b 100644
--- a/pkg/dev_compiler/package.json
+++ b/pkg/dev_compiler/package.json
@@ -22,8 +22,10 @@
"karma-chai": "^0.1.0",
"karma-chrome-launcher": "^0.1.8",
"karma-electron-launcher": "^0.0.5",
+ "karma-firefox-launcher": "~0.1",
"karma-mocha": "^0.1.10",
"karma-requirejs": "^0.2.2",
+ "karma-safari-launcher": "^1.0.0",
"mocha": "^2.2.4",
"requirejs": "^2.1.17",
"webdriver-manager": "8.0.0"
diff --git a/pkg/dev_compiler/pubspec.lock b/pkg/dev_compiler/pubspec.lock
index c337317..792de61 100644
--- a/pkg/dev_compiler/pubspec.lock
+++ b/pkg/dev_compiler/pubspec.lock
@@ -159,10 +159,10 @@
version: "0.12.0+2"
meta:
description:
- name: meta
- url: "https://pub.dartlang.org"
- source: hosted
- version: "1.0.2"
+ path: "../meta"
+ relative: true
+ source: path
+ version: "1.0.3"
mime:
description:
name: mime
diff --git a/pkg/dev_compiler/pubspec.yaml b/pkg/dev_compiler/pubspec.yaml
index 30a5bb3..7abbb62 100644
--- a/pkg/dev_compiler/pubspec.yaml
+++ b/pkg/dev_compiler/pubspec.yaml
@@ -16,6 +16,7 @@
func: ^0.1.0
html: ^0.12.0
js: ^0.6.0
+ meta: ^1.0.3
path: ^1.3.0
pub_semver: ^1.1.0
source_maps: ^0.10.0
@@ -31,15 +32,9 @@
webdriver: ^1.1.0
dependency_overrides:
- # This is here until we can update package:test and dart_style
- analyzer:
- path: ../analyzer
+ # Depend directly on packages in the same repositiory
+ analyzer: { path: ../analyzer }
+ meta: { path: ../meta }
environment:
sdk: ">=1.12.0 <2.0.0"
-
-executables:
- # Similar to "analyzer.dart" and its command line "dartanalyzer" we use
- # "dartdevc".
- dartdevc: dartdevc
- dev_compiler: dartdevc
diff --git a/pkg/dev_compiler/test/codegen/language/await_for_test.dart b/pkg/dev_compiler/test/codegen/language/await_for_test.dart
index 8c6f18e..2777900 100644
--- a/pkg/dev_compiler/test/codegen/language/await_for_test.dart
+++ b/pkg/dev_compiler/test/codegen/language/await_for_test.dart
@@ -21,7 +21,7 @@
Trace t1 = new Trace();
-consumeOne() async {
+Future consumeOne() async {
// Equivalent to await for (x in makeMeAStream()) { ... }
var s = makeMeAStream();
var it = new StreamIterator(s);
@@ -34,7 +34,7 @@
Trace t2 = new Trace();
-consumeTwo() async {
+Future consumeTwo() async {
await for (var x in makeMeAStream()) {
t2.record(x);
}
@@ -43,7 +43,7 @@
Trace t3 = new Trace();
-consumeNested() async {
+Future consumeNested() async {
await for (var x in makeMeAStream()) {
t3.record(x);
await for (var y in makeMeAStream()) {
@@ -56,7 +56,7 @@
Trace t4 = new Trace();
-consumeSomeOfInfinite() async {
+Future consumeSomeOfInfinite() async {
int i = 0;
await for (var x in infiniteStream()) {
i++;
diff --git a/pkg/dev_compiler/test/codegen/language/checked_covariant_overrides_test.dart b/pkg/dev_compiler/test/codegen/language/checked_covariant_overrides_test.dart
new file mode 100644
index 0000000..6f538dc
--- /dev/null
+++ b/pkg/dev_compiler/test/codegen/language/checked_covariant_overrides_test.dart
@@ -0,0 +1,36 @@
+// Copyright (c) 2016, 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";
+import 'package:meta/meta.dart' show checked;
+
+// Test runtime behavior of @checked
+
+class View {
+ addChild(View v) {}
+ transform(View fn(View v)) {}
+}
+class MyView extends View {
+ addChild(@checked MyView v) {}
+ transform(@checked MyView fn(Object v)) {}
+}
+
+main() {
+ dynamic mv = new MyView();
+ dynamic v = new View();
+
+ mv.addChild(mv);
+ Expect.throws(() => mv.addChild(v));
+
+ mv.transform((_) => new MyView());
+
+ // TODO(jmesserly): these *should* be a cast failures, but DDC is currently
+ // ignoring function type failures w/ a warning at the console...
+
+ // * -> * not a subtype of Object -> MyView
+ // Expect.throws(() => mv.transform((_) => mv));
+
+ // View -> View not a subtype of Object -> MyView
+ // Expect.throws(() => mv.transform((View x) => x));
+}
diff --git a/pkg/dev_compiler/test/codegen/lib/html/indexeddb_1_test.dart b/pkg/dev_compiler/test/codegen/lib/html/indexeddb_1_test.dart
index f4422de..58c97c8 100644
--- a/pkg/dev_compiler/test/codegen/lib/html/indexeddb_1_test.dart
+++ b/pkg/dev_compiler/test/codegen/lib/html/indexeddb_1_test.dart
@@ -78,7 +78,7 @@
};
testReadWriteTyped(key, value, matcher,
- [dbName, storeName = STORE_NAME, version = VERSION,
+ [dbName, String storeName = STORE_NAME, version = VERSION,
stringifyResult = false]) => () {
if (dbName == null) {
dbName = nextDatabaseName();
diff --git a/pkg/dev_compiler/test/codegen_test.dart b/pkg/dev_compiler/test/codegen_test.dart
index 7b3577f..c6695bf 100644
--- a/pkg/dev_compiler/test/codegen_test.dart
+++ b/pkg/dev_compiler/test/codegen_test.dart
@@ -170,7 +170,7 @@
if (errors.isNotEmpty && !errors.endsWith('\n')) errors += '\n';
new File(outPath + '.txt').writeAsStringSync(errors);
- result.writeCodeSync(format, outPath + '.js');
+ result.writeCodeSync(format, false, outPath + '.js');
if (result.summaryBytes != null) {
new File(outPath + '.sum').writeAsBytesSync(result.summaryBytes);
@@ -184,7 +184,7 @@
var expectFile = new File(expectPath + '.js');
if (result.isValid) {
- result.writeCodeSync(format, expectFile.path);
+ result.writeCodeSync(format, false, expectFile.path);
} else {
expectFile.writeAsStringSync("//FAILED TO COMPILE");
}
diff --git a/pkg/dev_compiler/tool/input_sdk/private/ddc_runtime/classes.dart b/pkg/dev_compiler/tool/input_sdk/private/ddc_runtime/classes.dart
index 51a703e..d6f3423 100644
--- a/pkg/dev_compiler/tool/input_sdk/private/ddc_runtime/classes.dart
+++ b/pkg/dev_compiler/tool/input_sdk/private/ddc_runtime/classes.dart
@@ -422,6 +422,10 @@
let extProto = $dartExtType.prototype;
let jsProto = $jsType.prototype;
+ // TODO(vsm): This sometimes doesn't exist on FF. These types will be
+ // broken.
+ if (!jsProto) return;
+
// Mark the JS type's instances so we can easily check for extensions.
jsProto[$_extensionType] = $dartExtType;
$_installProperties(jsProto, extProto);
diff --git a/pkg/dev_compiler/tool/input_sdk/private/ddc_runtime/operations.dart b/pkg/dev_compiler/tool/input_sdk/private/ddc_runtime/operations.dart
index d30b628..913860a 100644
--- a/pkg/dev_compiler/tool/input_sdk/private/ddc_runtime/operations.dart
+++ b/pkg/dev_compiler/tool/input_sdk/private/ddc_runtime/operations.dart
@@ -509,7 +509,7 @@
///
nullSafe(obj, @rest callbacks) => JS('', '''(() => {
if ($obj == null) return $obj;
- for (const callback of $callbacks) {
+ for (let callback of $callbacks) {
$obj = callback($obj);
if ($obj == null) break;
}
diff --git a/pkg/dev_compiler/web/web_command.dart b/pkg/dev_compiler/web/web_command.dart
index dc10142..5f6514a 100644
--- a/pkg/dev_compiler/web/web_command.dart
+++ b/pkg/dev_compiler/web/web_command.dart
@@ -129,7 +129,7 @@
var moduleCode = module.isValid
? module
- .getCode(ModuleFormat.legacy, unit.name, unit.name + '.map')
+ .getCode(ModuleFormat.legacy, false, unit.name, unit.name + '.map')
.code
: '';
diff --git a/pkg/meta/CHANGELOG.md b/pkg/meta/CHANGELOG.md
index 4a462d7..b91da1c 100644
--- a/pkg/meta/CHANGELOG.md
+++ b/pkg/meta/CHANGELOG.md
@@ -1,3 +1,41 @@
+## 1.0.4
+* Introduce `@virtual` to allow field overrides in strong mode
+ (SDK issue [27384](https://github.com/dart-lang/sdk/issues/27384)).
+
+ ```dart
+ import 'package:meta/meta.dart' show virtual;
+ class Base {
+ @virtual int x;
+ }
+ class Derived extends Base {
+ int x;
+
+ // Expose the hidden storage slot:
+ int get superX => super.x;
+ set superX(int v) { super.x = v; }
+ }
+ ```
+
+## 1.0.3
+* Introduce `@checked` to override a method and tighten a parameter
+ type (SDK issue [25578](https://github.com/dart-lang/sdk/issues/25578)).
+
+ ```dart
+ import 'package:meta/meta.dart' show checked;
+ class View {
+ addChild(View v) {}
+ }
+ class MyView extends View {
+ // this override is legal, it will check at runtime if we actually
+ // got a MyView.
+ addChild(@checked MyView v) {}
+ }
+ main() {
+ dynamic mv = new MyView();
+ mv.addChild(new View()); // runtime error
+ }
+ ```
+
## 1.0.2
* Introduce `@visibleForTesting` annotation for declarations that may be referenced only in the library or in a test.
diff --git a/pkg/meta/lib/meta.dart b/pkg/meta/lib/meta.dart
index a9424f9..9842875 100644
--- a/pkg/meta/lib/meta.dart
+++ b/pkg/meta/lib/meta.dart
@@ -128,6 +128,21 @@
const Required([this.reason]);
}
+/// Used to annotate a parameter of an instance method that overrides another
+/// method.
+///
+/// Indicates that this parameter may have a tighter type than the parameter on
+/// its superclass. The actual argument will be checked at runtime to ensure it
+/// is a subtype of the overridden parameter type.
+const _Checked checked = const _Checked();
+
+/// Used to annotate a field is allowed to be overridden in Strong Mode.
+const _Virtual virtual = const _Virtual();
+
+class _Checked {
+ const _Checked();
+}
+
class _Factory {
const _Factory();
}
@@ -148,6 +163,10 @@
const _Protected();
}
+class _Virtual {
+ const _Virtual();
+}
+
class _VisibleForTesting {
const _VisibleForTesting();
}
diff --git a/pkg/meta/pubspec.yaml b/pkg/meta/pubspec.yaml
index f9c9dc3..421a0ba7 100644
--- a/pkg/meta/pubspec.yaml
+++ b/pkg/meta/pubspec.yaml
@@ -1,5 +1,5 @@
name: meta
-version: 1.0.2
+version: 1.0.4
author: Dart Team <misc@dartlang.org>
homepage: http://www.dartlang.org
description: >
diff --git a/pkg/pkg.gyp b/pkg/pkg.gyp
index a108bea..7a7ae9a 100644
--- a/pkg/pkg.gyp
+++ b/pkg/pkg.gyp
@@ -26,11 +26,13 @@
],
'outputs': [
'<(SHARED_INTERMEDIATE_DIR)/packages.stamp',
+ '<(PRODUCT_DIR)/.packages',
],
'action': [
- 'python', '../tools/make_links.py',
+ 'python', '../tools/make_links.py', '--create-links',
+ '--create-package-file',
'--timestamp_file=<(SHARED_INTERMEDIATE_DIR)/packages.stamp',
- '<(PRODUCT_DIR)/packages',
+ '<(PRODUCT_DIR)',
'<@(_inputs)',
# Pub imports dart2js as compiler_unsupported so it can work outside
# the SDK. Map that to the compiler package.
diff --git a/pkg/pkg.status b/pkg/pkg.status
index 1094bed..a647224 100644
--- a/pkg/pkg.status
+++ b/pkg/pkg.status
@@ -17,6 +17,8 @@
# Analyzer2dart is not maintained anymore.
analyzer2dart/test/*: Skip
+dart_messages/test/dart_messages_test: Skip # Requires a package root.
+
[ $compiler == none && ($runtime == drt || $runtime == dartium) ]
mutation_observer: Skip # Issue 21149
unittest/*: Skip # Issue 21949
diff --git a/runtime/bin/bin.gypi b/runtime/bin/bin.gypi
index 43b5915..a31cb93 100644
--- a/runtime/bin/bin.gypi
+++ b/runtime/bin/bin.gypi
@@ -1147,6 +1147,11 @@
},
},
}],
+ ['OS == "linux" and asan == 0', {
+ 'dependencies': [
+ '../third_party/tcmalloc/tcmalloc.gypi:tcmalloc',
+ ],
+ }],
],
'configurations': {
'Dart_Linux_Base': {
@@ -1393,6 +1398,11 @@
'libraries': [ '-lws2_32.lib', '-lRpcrt4.lib', '-lwinmm.lib' ],
},
}],
+ ['OS == "linux" and asan == 0', {
+ 'dependencies': [
+ '../third_party/tcmalloc/tcmalloc.gypi:tcmalloc',
+ ],
+ }],
],
'configurations': {
'Dart_Linux_Base': {
diff --git a/runtime/bin/main.cc b/runtime/bin/main.cc
index 9f71238..277220e 100644
--- a/runtime/bin/main.cc
+++ b/runtime/bin/main.cc
@@ -494,6 +494,43 @@
}
+#if !defined(TARGET_OS_MACOS)
+extern const char* commandline_root_certs_file;
+extern const char* commandline_root_certs_cache;
+
+static bool ProcessRootCertsFileOption(const char* arg,
+ CommandLineOptions* vm_options) {
+ ASSERT(arg != NULL);
+ if (*arg == '-') {
+ return false;
+ }
+ if (commandline_root_certs_cache != NULL) {
+ Log::PrintErr("Only one of --root-certs-file and --root-certs-cache "
+ "may be specified");
+ return false;
+ }
+ commandline_root_certs_file = arg;
+ return true;
+}
+
+
+static bool ProcessRootCertsCacheOption(const char* arg,
+ CommandLineOptions* vm_options) {
+ ASSERT(arg != NULL);
+ if (*arg == '-') {
+ return false;
+ }
+ if (commandline_root_certs_file != NULL) {
+ Log::PrintErr("Only one of --root-certs-file and --root-certs-cache "
+ "may be specified");
+ return false;
+ }
+ commandline_root_certs_cache = arg;
+ return true;
+}
+#endif // !defined(TARGET_OS_MACOS)
+
+
static struct {
const char* option_name;
bool (*process)(const char* option, CommandLineOptions* vm_options);
@@ -522,6 +559,10 @@
{ "--hot-reload-rollback-test-mode", ProcessHotReloadRollbackTestModeOption },
{ "--short_socket_read", ProcessShortSocketReadOption },
{ "--short_socket_write", ProcessShortSocketWriteOption },
+#if !defined(TARGET_OS_MACOS)
+ { "--root-certs-file=", ProcessRootCertsFileOption },
+ { "--root-certs-cache=", ProcessRootCertsCacheOption },
+#endif // !defined(TARGET_OS_MACOS)
{ NULL, NULL }
};
@@ -960,6 +1001,15 @@
"--enable-vm-service[=<port>[/<bind-address>]]\n"
" enables the VM service and listens on specified port for connections\n"
" (default port number is 8181, default bind address is 127.0.0.1).\n"
+#if !defined(TARGET_OS_MACOS)
+"\n"
+"--root-certs-file=<path>\n"
+" The path to a file containing the trusted root certificates to use for\n"
+" secure socket connections.\n"
+"--root-certs-cache=<path>\n"
+" The path to a cache directory containing the trusted root certificates to\n"
+" use for secure socket connections.\n"
+#endif // !defined(TARGET_OS_MACOS)
"\n"
"The following options are only used for VM development and may\n"
"be changed in any future version:\n");
diff --git a/runtime/bin/root_certificates_unsupported.cc b/runtime/bin/root_certificates_unsupported.cc
index a899e3c..304a59e 100644
--- a/runtime/bin/root_certificates_unsupported.cc
+++ b/runtime/bin/root_certificates_unsupported.cc
@@ -5,7 +5,9 @@
#if !defined(DART_IO_DISABLED) && !defined(DART_IO_SECURE_SOCKET_DISABLED)
#include "platform/globals.h"
-#if defined(TARGET_OS_MACOS) || defined(TARGET_OS_ANDROID)
+#if defined(TARGET_OS_MACOS) || \
+ defined(TARGET_OS_ANDROID) || \
+ defined(DART_IO_ROOT_CERTS_DISABLED)
namespace dart {
namespace bin {
@@ -16,7 +18,7 @@
} // namespace bin
} // namespace dart
-#endif // defined(TARGET_OS_MACOS) || defined(TARGET_OS_ANDROID)
+#endif // defined(TARGET_OS_MACOS) || defined(TARGET_OS_ANDROID) || ...
#endif // !defined(DART_IO_DISABLED) &&
// !defined(DART_IO_SECURE_SOCKET_DISABLED)
diff --git a/runtime/bin/secure_socket_boringssl.cc b/runtime/bin/secure_socket_boringssl.cc
index e881815..132588d 100644
--- a/runtime/bin/secure_socket_boringssl.cc
+++ b/runtime/bin/secure_socket_boringssl.cc
@@ -28,6 +28,8 @@
#include "bin/builtin.h"
#include "bin/dartutils.h"
+#include "bin/directory.h"
+#include "bin/file.h"
#include "bin/lockers.h"
#include "bin/log.h"
#include "bin/socket.h"
@@ -64,6 +66,10 @@
static const int SSL_ERROR_MESSAGE_BUFFER_SIZE = 1000;
+const char* commandline_root_certs_file = NULL;
+const char* commandline_root_certs_cache = NULL;
+
+
/* Get the error messages from BoringSSL, and put them in buffer as a
* null-terminated string. */
static void FetchErrorString(char* buffer, int length) {
@@ -788,22 +794,10 @@
}
-void FUNCTION_NAME(SecurityContext_TrustBuiltinRoots)(
- Dart_NativeArguments args) {
- SSLContext* context = GetSecurityContext(args);
-#if defined(TARGET_OS_ANDROID)
- // On Android, we don't compile in the trusted root certificates. Insead,
- // we use the directory of trusted certificates already present on the device.
- // This saves ~240KB from the size of the binary. This has the drawback that
- // SSL_do_handshake will synchronously hit the filesystem looking for root
- // certs during its trust evaluation. We call SSL_do_handshake directly from
- // the Dart thread so that Dart code can be invoked from the "bad certificate"
- // callback called by SSL_do_handshake.
- const char* android_cacerts = "/system/etc/security/cacerts";
- int status = SSL_CTX_load_verify_locations(
- context->context(), NULL, android_cacerts);
- CheckStatus(status, "TlsException", "Failure trusting builtint roots");
-#else
+static void AddCompiledInCerts(SSLContext* context) {
+ if (root_certificates_pem == NULL) {
+ return;
+ }
X509_STORE* store = SSL_CTX_get_cert_store(context->context());
BIO* roots_bio =
BIO_new_mem_buf(const_cast<unsigned char*>(root_certificates_pem),
@@ -825,7 +819,90 @@
// reading PEM certificates.
ASSERT((ERR_peek_error() == 0) || NoPEMStartLine());
ERR_clear_error();
+}
+
+
+static void LoadRootCertFile(SSLContext* context, const char* file) {
+ if (SSL_LOG_STATUS) {
+ Log::Print("Looking for trusted roots in %s\n", file);
+ }
+ if (!File::Exists(file)) {
+ ThrowIOException(-1, "TlsException", "Failed to find root cert file");
+ }
+ int status = SSL_CTX_load_verify_locations(context->context(), file, NULL);
+ CheckStatus(status, "TlsException", "Failure trusting builtint roots");
+ if (SSL_LOG_STATUS) {
+ Log::Print("Trusting roots from: %s\n", file);
+ }
+}
+
+
+static void LoadRootCertCache(SSLContext* context, const char* cache) {
+ if (SSL_LOG_STATUS) {
+ Log::Print("Looking for trusted roots in %s\n", cache);
+ }
+ if (Directory::Exists(cache) != Directory::EXISTS) {
+ ThrowIOException(-1, "TlsException", "Failed to find root cert cache");
+ }
+ int status = SSL_CTX_load_verify_locations(context->context(), NULL, cache);
+ CheckStatus(status, "TlsException", "Failure trusting builtint roots");
+ if (SSL_LOG_STATUS) {
+ Log::Print("Trusting roots from: %s\n", cache);
+ }
+}
+
+
+void FUNCTION_NAME(SecurityContext_TrustBuiltinRoots)(
+ Dart_NativeArguments args) {
+ SSLContext* context = GetSecurityContext(args);
+
+ // First, try to use locations specified on the command line.
+ if (commandline_root_certs_file != NULL) {
+ LoadRootCertFile(context, commandline_root_certs_file);
+ return;
+ }
+
+ if (commandline_root_certs_cache != NULL) {
+ LoadRootCertCache(context, commandline_root_certs_cache);
+ return;
+ }
+
+#if defined(TARGET_OS_ANDROID)
+ // On Android, we don't compile in the trusted root certificates. Insead,
+ // we use the directory of trusted certificates already present on the device.
+ // This saves ~240KB from the size of the binary. This has the drawback that
+ // SSL_do_handshake will synchronously hit the filesystem looking for root
+ // certs during its trust evaluation. We call SSL_do_handshake directly from
+ // the Dart thread so that Dart code can be invoked from the "bad certificate"
+ // callback called by SSL_do_handshake.
+ const char* android_cacerts = "/system/etc/security/cacerts";
+ LoadRootCertCache(context, android_cacerts);
+ return;
+#elif defined(TARGET_OS_LINUX)
+ // On Linux, we use the compiled-in trusted certs as a last resort. First,
+ // we try to find the trusted certs in various standard locations. A good
+ // discussion of the complexities of this endeavor can be found here:
+ //
+ // https://www.happyassassin.net/2015/01/12/a-note-about-ssltls-trusted-certificate-stores-and-platforms/
+ const char* bundle = "/etc/pki/tls/certs/ca-bundle.crt";
+ const char* cachedir = "/etc/ssl/certs";
+ if (File::Exists(bundle)) {
+ LoadRootCertFile(context, bundle);
+ return;
+ }
+
+ if (Directory::Exists(cachedir) == Directory::EXISTS) {
+ LoadRootCertCache(context, cachedir);
+ return;
+ }
#endif // defined(TARGET_OS_ANDROID)
+
+ // Fall back on the compiled-in certs if the standard locations don't exist,
+ // or we aren't on Linux.
+ AddCompiledInCerts(context);
+ if (SSL_LOG_STATUS) {
+ Log::Print("Trusting compiled-in roots\n");
+ }
}
@@ -1494,19 +1571,27 @@
// Make the connection:
if (is_server_) {
status = SSL_accept(ssl_);
- if (SSL_LOG_STATUS) Log::Print("SSL_accept status: %d\n", status);
+ if (SSL_LOG_STATUS) {
+ Log::Print("SSL_accept status: %d\n", status);
+ }
if (status != 1) {
// TODO(whesse): expect a needs-data error here. Handle other errors.
error = SSL_get_error(ssl_, status);
- if (SSL_LOG_STATUS) Log::Print("SSL_accept error: %d\n", error);
+ if (SSL_LOG_STATUS) {
+ Log::Print("SSL_accept error: %d\n", error);
+ }
}
} else {
status = SSL_connect(ssl_);
- if (SSL_LOG_STATUS) Log::Print("SSL_connect status: %d\n", status);
+ if (SSL_LOG_STATUS) {
+ Log::Print("SSL_connect status: %d\n", status);
+ }
if (status != 1) {
// TODO(whesse): expect a needs-data error here. Handle other errors.
error = SSL_get_error(ssl_, status);
- if (SSL_LOG_STATUS) Log::Print("SSL_connect error: %d\n", error);
+ if (SSL_LOG_STATUS) {
+ Log::Print("SSL_connect error: %d\n", error);
+ }
}
}
Handshake();
diff --git a/runtime/bin/secure_socket_unsupported.cc b/runtime/bin/secure_socket_unsupported.cc
index dc49825..fb7e713 100644
--- a/runtime/bin/secure_socket_unsupported.cc
+++ b/runtime/bin/secure_socket_unsupported.cc
@@ -11,6 +11,9 @@
namespace dart {
namespace bin {
+const char* commandline_root_certs_file = NULL;
+const char* commandline_root_certs_cache = NULL;
+
void FUNCTION_NAME(SecureSocket_Init)(Dart_NativeArguments args) {
Dart_ThrowException(DartUtils::NewDartArgumentError(
"Secure Sockets unsupported on this platform"));
diff --git a/runtime/dart-runtime.gyp b/runtime/dart-runtime.gyp
index dfe7307..6ed2306 100644
--- a/runtime/dart-runtime.gyp
+++ b/runtime/dart-runtime.gyp
@@ -186,7 +186,6 @@
'target_name': 'runtime_all',
'type': 'none',
'dependencies': [
- '../pkg/pkg.gyp:pkg_packages',
'sample_extension',
],
},
diff --git a/runtime/include/dart_api.h b/runtime/include/dart_api.h
index 3d02adc..c9c0d1a 100755
--- a/runtime/include/dart_api.h
+++ b/runtime/include/dart_api.h
@@ -1178,9 +1178,10 @@
/**
* Called when the embedder has caught a top level unhandled exception error
- * in the current isolate. Also marks the isolate as paused at exit.
+ * in the current isolate.
*
- * NOTE: It is illegal to call this twice on the same isolate.
+ * NOTE: It is illegal to call this twice on the same isolate without first
+ * clearing the sticky error to null.
*
* \param error The unhandled exception error.
*/
@@ -1194,6 +1195,14 @@
/**
+ * Gets the sticky error for the current isolate.
+ *
+ * \return A handle to the sticky error object or null.
+ */
+DART_EXPORT Dart_Handle Dart_GetStickyError();
+
+
+/**
* Handles the next pending message for the current isolate.
*
* May generate an unhandled exception error.
diff --git a/runtime/lib/errors_patch.dart b/runtime/lib/errors_patch.dart
index 77251fe..961f71c 100644
--- a/runtime/lib/errors_patch.dart
+++ b/runtime/lib/errors_patch.dart
@@ -358,3 +358,10 @@
return msg_buf.toString();
}
}
+
+
+class _CompileTimeError extends Error {
+ final String _errorMsg;
+ _CompileTimeError(this._errorMsg);
+ String toString() => _errorMsg;
+}
diff --git a/runtime/observatory/BUILD.gn b/runtime/observatory/BUILD.gn
index c0903ea..3943253 100644
--- a/runtime/observatory/BUILD.gn
+++ b/runtime/observatory/BUILD.gn
@@ -121,7 +121,7 @@
]
outputs = [
- "$root_out_dir/observatory/build/web/index.html.polymer.bootstrap.dart.js",
+ "$root_out_dir/observatory/build/web/main.dart.js",
]
}
@@ -134,7 +134,7 @@
inputs = [
script,
- "$root_out_dir/observatory/build/web/index.html.polymer.bootstrap.dart.js",
+ "$root_out_dir/observatory/build/web/main.dart.js",
]
args = [
@@ -148,7 +148,7 @@
]
outputs = [
- "$root_out_dir/observatory/deployed/web/index.html.polymer.bootstrap.dart.js",
+ "$root_out_dir/observatory/deployed/web/main.dart.js",
]
}
@@ -161,7 +161,7 @@
inputs = [
script,
- "$root_out_dir/observatory/deployed/web/index.html.polymer.bootstrap.dart.js",
+ "$root_out_dir/observatory/deployed/web/main.dart.js",
]
args = [
diff --git a/runtime/observatory/lib/app.dart b/runtime/observatory/lib/app.dart
index e8c0f4a..f096ad8 100644
--- a/runtime/observatory/lib/app.dart
+++ b/runtime/observatory/lib/app.dart
@@ -11,11 +11,13 @@
import 'package:logging/logging.dart';
import 'package:observatory/service_html.dart';
import 'package:observatory/elements.dart';
+import 'package:observatory/src/elements/helpers/uris.dart';
import 'package:observatory/event.dart';
import 'package:observatory/models.dart' as M;
import 'package:observatory/repositories.dart';
import 'package:observatory/tracer.dart';
import 'package:observatory/utils.dart';
+import 'package:stack_trace/stack_trace.dart';
import 'package:usage/usage_html.dart';
export 'package:observatory/utils.dart';
diff --git a/runtime/observatory/lib/event.dart b/runtime/observatory/lib/event.dart
index ce30fb2..4ca9106 100644
--- a/runtime/observatory/lib/event.dart
+++ b/runtime/observatory/lib/event.dart
@@ -106,12 +106,17 @@
final Iterable<M.Breakpoint> pauseBreakpoints;
final M.Frame topFrame;
final bool atAsyncSuspension;
+
/// [optional]
final M.Breakpoint breakpoint;
- PauseBreakpointEvent(this.timestamp, this.isolate,
- Iterable<M.Breakpoint> pauseBreakpoints, this.topFrame,
- this.atAsyncSuspension, [this.breakpoint])
- : pauseBreakpoints = new List.unmodifiable(pauseBreakpoints){
+ PauseBreakpointEvent(
+ this.timestamp,
+ this.isolate,
+ Iterable<M.Breakpoint> pauseBreakpoints,
+ this.topFrame,
+ this.atAsyncSuspension,
+ [this.breakpoint])
+ : pauseBreakpoints = new List.unmodifiable(pauseBreakpoints) {
assert(timestamp != null);
assert(isolate != null);
assert(pauseBreakpoints != null);
@@ -125,8 +130,8 @@
final M.IsolateRef isolate;
final M.Frame topFrame;
final bool atAsyncSuspension;
- PauseInterruptedEvent(this.timestamp, this.isolate, this.topFrame,
- this.atAsyncSuspension) {
+ PauseInterruptedEvent(
+ this.timestamp, this.isolate, this.topFrame, this.atAsyncSuspension) {
assert(timestamp != null);
assert(isolate != null);
assert(atAsyncSuspension != null);
@@ -138,8 +143,8 @@
final M.IsolateRef isolate;
final M.Frame topFrame;
final M.InstanceRef exception;
- PauseExceptionEvent(this.timestamp, this.isolate, this.topFrame,
- this.exception) {
+ PauseExceptionEvent(
+ this.timestamp, this.isolate, this.topFrame, this.exception) {
assert(timestamp != null);
assert(isolate != null);
assert(topFrame != null);
@@ -235,8 +240,8 @@
final M.IsolateRef isolate;
final String extensionKind;
final M.ExtensionData extensionData;
- ExtensionEvent(this.timestamp, this.isolate, this.extensionKind,
- this.extensionData) {
+ ExtensionEvent(
+ this.timestamp, this.isolate, this.extensionKind, this.extensionData) {
assert(timestamp != null);
assert(isolate != null);
assert(extensionKind != null);
@@ -248,9 +253,9 @@
final DateTime timestamp;
final M.IsolateRef isolate;
final Iterable<M.TimelineEvent> timelineEvents;
- TimelineEventsEvent(this.timestamp, this.isolate,
- Iterable<M.TimelineEvent> timelineEvents)
- : timelineEvents = new List.unmodifiable(timelineEvents){
+ TimelineEventsEvent(
+ this.timestamp, this.isolate, Iterable<M.TimelineEvent> timelineEvents)
+ : timelineEvents = new List.unmodifiable(timelineEvents) {
assert(timestamp != null);
assert(isolate != null);
assert(timelineEvents != null);
@@ -267,7 +272,7 @@
}
M.Event createEventFromServiceEvent(S.ServiceEvent event) {
- switch(event.kind) {
+ switch (event.kind) {
case S.ServiceEvent.kVMUpdate:
return new VMUpdateEvent(event.timestamp, event.vm);
case S.ServiceEvent.kIsolateStart:
@@ -277,18 +282,19 @@
case S.ServiceEvent.kIsolateUpdate:
return new IsolateUpdateEvent(event.timestamp, event.isolate);
case S.ServiceEvent.kIsolateReload:
- return new IsolateReloadEvent(event.timestamp, event.isolate, event.error);
+ return new IsolateReloadEvent(
+ event.timestamp, event.isolate, event.error);
case S.ServiceEvent.kIsolateExit:
return new IsolateExitEvent(event.timestamp, event.isolate);
case S.ServiceEvent.kBreakpointAdded:
- return new BreakpointAddedEvent(event.timestamp, event.isolate,
- event.breakpoint);
+ return new BreakpointAddedEvent(
+ event.timestamp, event.isolate, event.breakpoint);
case S.ServiceEvent.kBreakpointResolved:
- return new BreakpointResolvedEvent(event.timestamp, event.isolate,
- event.breakpoint);
+ return new BreakpointResolvedEvent(
+ event.timestamp, event.isolate, event.breakpoint);
case S.ServiceEvent.kBreakpointRemoved:
- return new BreakpointRemovedEvent(event.timestamp, event.isolate,
- event.breakpoint);
+ return new BreakpointRemovedEvent(
+ event.timestamp, event.isolate, event.breakpoint);
case S.ServiceEvent.kDebuggerSettingsUpdate:
return new DebuggerSettingsUpdateEvent(event.timestamp, event.isolate);
case S.ServiceEvent.kResume:
@@ -298,8 +304,12 @@
case S.ServiceEvent.kPauseExit:
return new PauseExitEvent(event.timestamp, event.isolate);
case S.ServiceEvent.kPauseBreakpoint:
- return new PauseBreakpointEvent(event.timestamp, event.isolate,
- event.pauseBreakpoints, event.topFrame, event.atAsyncSuspension,
+ return new PauseBreakpointEvent(
+ event.timestamp,
+ event.isolate,
+ event.pauseBreakpoints,
+ event.topFrame,
+ event.atAsyncSuspension,
event.breakpoint);
case S.Isolate.kLoggingStream:
return new LoggingEvent(event.timestamp, event.isolate, event.logRecord);
@@ -307,11 +317,10 @@
return new PauseInterruptedEvent(event.timestamp, event.isolate,
event.topFrame, event.atAsyncSuspension);
case S.ServiceEvent.kPauseException:
- return new PauseExceptionEvent(event.timestamp, event.isolate,
- event.topFrame, event.exception);
+ return new PauseExceptionEvent(
+ event.timestamp, event.isolate, event.topFrame, event.exception);
case S.ServiceEvent.kInspect:
- return new InspectEvent(event.timestamp, event.isolate,
- event.inspectee);
+ return new InspectEvent(event.timestamp, event.isolate, event.inspectee);
case S.ServiceEvent.kGC:
return new GCEvent(event.timestamp, event.isolate);
case S.ServiceEvent.kNone:
diff --git a/runtime/observatory/lib/object_graph.dart b/runtime/observatory/lib/object_graph.dart
index ce6ff65..c2b4169 100644
--- a/runtime/observatory/lib/object_graph.dart
+++ b/runtime/observatory/lib/object_graph.dart
@@ -16,7 +16,7 @@
}
static int finish(int hash) {
- hash = 0x1fffffff & (hash + ((0x03ffffff & hash) << 3));
+ hash = 0x1fffffff & (hash + ((0x03ffffff & hash) << 3));
hash = hash ^ (hash >> 11);
return 0x1fffffff & (hash + ((0x00003fff & hash) << 15));
}
@@ -68,7 +68,6 @@
}
}
-
// Port of dart::ReadStream from vm/datastream.h.
//
// The heap snapshot is a series of variable-length unsigned integers. For
@@ -254,11 +253,13 @@
nibble = nibble & 0xF;
strAddr = nibble.toRadixString(16) + strAddr;
}
+
combine32(thirtyTwoBits) {
for (int shift = 0; shift < 32; shift += 4) {
combine4((thirtyTwoBits >> shift) & 0xF);
}
}
+
combine32(low32);
combine32(high32);
return strAddr;
@@ -337,8 +338,8 @@
class ObjectGraph {
ObjectGraph(List<ByteData> chunks, int nodeCount)
- : this._chunks = chunks
- , this._N = nodeCount;
+ : this._chunks = chunks,
+ this._N = nodeCount;
int get size => _size;
int get vertexCount => _N;
@@ -349,7 +350,7 @@
Iterable<ObjectVertex> getMostRetained({int classId, int limit}) {
List<ObjectVertex> _mostRetained =
- new List<ObjectVertex>.from(vertices.where((u) => !u.isRoot));
+ new List<ObjectVertex>.from(vertices.where((u) => !u.isRoot));
_mostRetained.sort((u, v) => v.retainedSize - u.retainedSize);
var result = _mostRetained;
@@ -512,7 +513,7 @@
assert(id == N + 1);
assert(edge <= E); // edge is smaller because E was computed before we knew
- // if references pointed into the VM isolate
+ // if references pointed into the VM isolate
_E = edge;
_firstSuccs = firstSuccs;
@@ -604,7 +605,7 @@
}
// Assign indices into predecessors array.
- var firstPreds = numPreds; // Alias.
+ var firstPreds = numPreds; // Alias.
var nextPreds = new Uint32List(N + 1);
var predIndex = 0;
for (var i = 1; i <= N; i++) {
@@ -621,8 +622,8 @@
var startSuccIndex = firstSuccs[i];
var limitSuccIndex = firstSuccs[i + 1];
for (var succIndex = startSuccIndex;
- succIndex < limitSuccIndex;
- succIndex++) {
+ succIndex < limitSuccIndex;
+ succIndex++) {
var succId = succs[succIndex];
var predIndex = nextPreds[succId]++;
preds[predIndex] = i;
@@ -633,12 +634,8 @@
_preds = preds;
}
- static int _eval(int v,
- Uint32List ancestor,
- Uint32List semi,
- Uint32List label,
- Uint32List stackNode,
- Uint8List stackState) {
+ static int _eval(int v, Uint32List ancestor, Uint32List semi,
+ Uint32List label, Uint32List stackNode, Uint8List stackState) {
if (ancestor[v] == 0) {
return label[v];
} else {
@@ -683,13 +680,8 @@
// Note the version in the main text of Lengauer & Tarjan incorrectly
// uses parent instead of ancestor. The correct version is in Appendix B.
- static void _link(int v,
- int w,
- Uint32List size,
- Uint32List label,
- Uint32List semi,
- Uint32List child,
- Uint32List ancestor) {
+ static void _link(int v, int w, Uint32List size, Uint32List label,
+ Uint32List semi, Uint32List child, Uint32List ancestor) {
assert(size[0] == 0);
assert(label[0] == 0);
assert(semi[0] == 0);
@@ -751,9 +743,7 @@
// Lengauer & Tarjan Step 2.
var startPred = firstPreds[w];
var limitPred = firstPreds[w + 1];
- for (var predIndex = startPred;
- predIndex < limitPred;
- predIndex++) {
+ for (var predIndex = startPred; predIndex < limitPred; predIndex++) {
var v = preds[predIndex];
var u = _eval(v, ancestor, semi, label, stackNode, stackState);
if (semi[u] < semi[w]) {
diff --git a/runtime/observatory/lib/service_common.dart b/runtime/observatory/lib/service_common.dart
index cd146ee..3a47f20 100644
--- a/runtime/observatory/lib/service_common.dart
+++ b/runtime/observatory/lib/service_common.dart
@@ -65,11 +65,8 @@
/// Minimal common interface for 'WebSocket' in [dart:io] and [dart:html].
abstract class CommonWebSocket {
- void connect(String address,
- void onOpen(),
- void onMessage(dynamic data),
- void onError(),
- void onClose());
+ void connect(String address, void onOpen(), void onMessage(dynamic data),
+ void onError(), void onClose());
bool get isOpen;
void send(dynamic data);
void close();
@@ -83,12 +80,11 @@
final Completer _disconnected = new Completer<String>();
final WebSocketVMTarget target;
final Map<String, _WebSocketRequest> _delayedRequests =
- new Map<String, _WebSocketRequest>();
+ new Map<String, _WebSocketRequest>();
final Map<String, _WebSocketRequest> _pendingRequests =
new Map<String, _WebSocketRequest>();
int _requestSerial = 0;
bool _hasInitiatedConnect = false;
- bool _hasFinishedConnect = false;
Utf8Decoder _utf8Decoder = const Utf8Decoder();
String get displayName => '${name}@${target.name}';
@@ -100,28 +96,32 @@
}
void _notifyConnect() {
- _hasFinishedConnect = true;
if (!_connected.isCompleted) {
- Logger.root.info('WebSocketVM connection opened: ${target.networkAddress}');
+ Logger.root
+ .info('WebSocketVM connection opened: ${target.networkAddress}');
_connected.complete(this);
}
}
+
Future get onConnect => _connected.future;
+ bool get wasOrIsConnected => _connected.isCompleted;
+ bool get isConnected => wasOrIsConnected && !isDisconnected;
void _notifyDisconnect(String reason) {
- if (!_hasFinishedConnect) {
- return;
- }
if (!_disconnected.isCompleted) {
- Logger.root.info('WebSocketVM connection error: ${target.networkAddress}');
+ Logger.root
+ .info('WebSocketVM connection error: ${target.networkAddress}');
_disconnected.complete(reason);
}
}
+
Future get onDisconnect => _disconnected.future;
bool get isDisconnected => _disconnected.isCompleted;
- void disconnect({String reason : 'WebSocket closed'}) {
+ void disconnect({String reason: 'WebSocket closed'}) {
if (_hasInitiatedConnect) {
- _webSocket.close();
+ if (_webSocket != null) {
+ _webSocket.close();
+ }
}
// We don't need to cancel requests and notify here. These
// functions will be called again when the onClose callback
@@ -134,8 +134,14 @@
Future<Map> invokeRpcRaw(String method, Map params) {
if (!_hasInitiatedConnect) {
_hasInitiatedConnect = true;
- _webSocket.connect(
- target.networkAddress, _onOpen, _onMessage, _onError, _onClose);
+ try {
+ _webSocket.connect(
+ target.networkAddress, _onOpen, _onMessage, _onError, _onClose);
+ } catch (_) {
+ _webSocket = null;
+ var exception = new NetworkRpcException('WebSocket closed');
+ return new Future.error(exception);
+ }
}
if (_disconnected.isCompleted) {
// This connection was closed already.
@@ -144,7 +150,7 @@
}
String serial = (_requestSerial++).toString();
var request = new _WebSocketRequest(method, params);
- if (_webSocket.isOpen) {
+ if ((_webSocket != null) && _webSocket.isOpen) {
// Already connected, send request immediately.
_sendRequest(serial, request);
} else {
@@ -180,12 +186,12 @@
map = JSON.decode(message);
} catch (e, st) {
Logger.root.severe('Disconnecting: Error decoding message: $e\n$st');
- disconnect(reason:'Connection saw corrupt JSON message: $e');
+ disconnect(reason: 'Connection saw corrupt JSON message: $e');
return null;
}
if (map == null) {
Logger.root.severe("Disconnecting: Unable to decode 'null' message");
- disconnect(reason:"Connection saw 'null' message");
+ disconnect(reason: "Connection saw 'null' message");
return null;
}
return map;
@@ -202,9 +208,7 @@
var meta = _utf8Decoder.convert(new Uint8List.view(
bytes.buffer, bytes.offsetInBytes + offset, metaSize));
offset += metaSize;
- var data = new ByteData.view(
- bytes.buffer,
- bytes.offsetInBytes + offset,
+ var data = new ByteData.view(bytes.buffer, bytes.offsetInBytes + offset,
bytes.lengthInBytes - offset);
var map = _parseJSON(meta);
if (map == null || map['method'] != 'streamNotify') {
@@ -212,7 +216,9 @@
}
var event = map['params']['event'];
var streamId = map['params']['streamId'];
- scheduleMicrotask(() { postServiceEvent(streamId, event, data); });
+ scheduleMicrotask(() {
+ postServiceEvent(streamId, event, data);
+ });
});
}
@@ -225,7 +231,9 @@
if (map['method'] == 'streamNotify') {
var event = map['params']['event'];
var streamId = map['params']['streamId'];
- scheduleMicrotask(() { postServiceEvent(streamId, event, null); });
+ scheduleMicrotask(() {
+ postServiceEvent(streamId, event, null);
+ });
return;
}
@@ -241,8 +249,7 @@
if (request.method != 'getTagProfile' &&
request.method != 'getIsolateMetric' &&
request.method != 'getVMMetric') {
- Logger.root.info(
- 'RESPONSE [${serial}] ${request.method}');
+ Logger.root.info('RESPONSE [${serial}] ${request.method}');
}
var result = map['result'];
@@ -263,10 +270,11 @@
}
}
- void _cancelRequests(Map<String,_WebSocketRequest> requests,
- String message) {
- requests.forEach((_, _WebSocketRequest request) {
- var exception = new NetworkRpcException(message);
+ void _cancelRequests(
+ Map<String, _WebSocketRequest> requests, String message) {
+ requests.forEach((String serial, _WebSocketRequest request) {
+ var exception = new NetworkRpcException(message +
+ '(id: $serial method: ${request.method} params: ${request.params})');
request.completer.completeError(exception);
});
requests.clear();
@@ -300,7 +308,7 @@
/// Send the request over WebSocket.
void _sendRequest(String serial, _WebSocketRequest request) {
- assert (_webSocket.isOpen);
+ assert(_webSocket.isOpen);
// Mark request as pending.
assert(_pendingRequests.containsKey(serial) == false);
_pendingRequests[serial] = request;
@@ -310,15 +318,11 @@
message = JSON.encode({
'id': int.parse(serial),
'method': 'Dart.observatoryQuery',
- 'params': {
- 'id': serial,
- 'query': request.method
- }
+ 'params': {'id': serial, 'query': request.method}
});
} else {
- message = JSON.encode({'id': serial,
- 'method': request.method,
- 'params': request.params});
+ message = JSON.encode(
+ {'id': serial, 'method': request.method, 'params': request.params});
}
if (request.method != 'getTagProfile' &&
request.method != 'getIsolateMetric' &&
@@ -329,4 +333,6 @@
// Send message.
_webSocket.send(message);
}
+
+ String toString() => displayName;
}
diff --git a/runtime/observatory/lib/service_html.dart b/runtime/observatory/lib/service_html.dart
index fe5b1c3..f4b166e 100644
--- a/runtime/observatory/lib/service_html.dart
+++ b/runtime/observatory/lib/service_html.dart
@@ -16,11 +16,8 @@
class _HtmlWebSocket implements CommonWebSocket {
WebSocket _webSocket;
- void connect(String address,
- void onOpen(),
- void onMessage(dynamic data),
- void onError(),
- void onClose()) {
+ void connect(String address, void onOpen(), void onMessage(dynamic data),
+ void onError(), void onClose()) {
_webSocket = new WebSocket(address);
_webSocket.onClose.listen((CloseEvent) => onClose());
_webSocket.onError.listen((Event) => onError());
@@ -44,9 +41,8 @@
fileReader.readAsArrayBuffer(data);
return fileReader.onLoadEnd.first.then((e) {
var result = fileReader.result;
- return new ByteData.view(result.buffer,
- result.offsetInBytes,
- result.length);
+ return new ByteData.view(
+ result.buffer, result.offsetInBytes, result.length);
});
}
}
diff --git a/runtime/observatory/lib/service_io.dart b/runtime/observatory/lib/service_io.dart
index 2a91426..63857cb 100644
--- a/runtime/observatory/lib/service_io.dart
+++ b/runtime/observatory/lib/service_io.dart
@@ -17,15 +17,11 @@
class _IOWebSocket implements CommonWebSocket {
WebSocket _webSocket;
- void connect(String address,
- void onOpen(),
- void onMessage(dynamic data),
- void onError(),
- void onClose()) {
+ void connect(String address, void onOpen(), void onMessage(dynamic data),
+ void onError(), void onClose()) {
WebSocket.connect(address).then((WebSocket socket) {
_webSocket = socket;
- _webSocket.listen(
- onMessage,
+ _webSocket.listen(onMessage,
onError: (dynamic) => onError(),
onDone: onClose,
cancelOnError: true);
@@ -52,9 +48,7 @@
assert(data is Uint8List);
Logger.root.info('Binary data size in bytes: ${data.lengthInBytes}');
return new Future.sync(() =>
- new ByteData.view(data.buffer,
- data.offsetInBytes,
- data.lengthInBytes));
+ new ByteData.view(data.buffer, data.offsetInBytes, data.lengthInBytes));
}
}
diff --git a/runtime/observatory/lib/src/allocation_profile/allocation_profile.dart b/runtime/observatory/lib/src/allocation_profile/allocation_profile.dart
index 739597b..1f7cff11 100644
--- a/runtime/observatory/lib/src/allocation_profile/allocation_profile.dart
+++ b/runtime/observatory/lib/src/allocation_profile/allocation_profile.dart
@@ -14,11 +14,11 @@
final Iterable<ClassHeapStats> members;
AllocationProfile(S.ServiceMap map)
- : lastAccumulatorReset = _intString2DateTime(map[_lastAccumulatorReset]),
- lastServiceGC = _intString2DateTime(map[_lastServiceGC]),
- oldSpace = new S.HeapSpace()..update(map['heaps']['old']),
- newSpace = new S.HeapSpace()..update(map['heaps']['new']),
- members = map['members'].map(_convertMember).toList();
+ : lastAccumulatorReset = _intString2DateTime(map[_lastAccumulatorReset]),
+ lastServiceGC = _intString2DateTime(map[_lastServiceGC]),
+ oldSpace = new S.HeapSpace()..update(map['heaps']['old']),
+ newSpace = new S.HeapSpace()..update(map['heaps']['new']),
+ members = map['members'].map(_convertMember).toList();
static DateTime _intString2DateTime(String milliseconds) {
if ((milliseconds == null) || milliseconds == '') {
@@ -41,9 +41,9 @@
final int promotedBytes;
ClassHeapStats(S.ServiceMap map)
- : clazz = map['class'],
- oldSpace = new S.Allocations()..update(map['old']),
- newSpace = new S.Allocations()..update(map['new']),
- promotedInstances = map['promotedInstances'],
- promotedBytes = map['promotedBytes'];
+ : clazz = map['class'],
+ oldSpace = new S.Allocations()..update(map['old']),
+ newSpace = new S.Allocations()..update(map['new']),
+ promotedInstances = map['promotedInstances'],
+ promotedBytes = map['promotedBytes'];
}
diff --git a/runtime/observatory/lib/src/app/application.dart b/runtime/observatory/lib/src/app/application.dart
index 5306b13..977550f 100644
--- a/runtime/observatory/lib/src/app/application.dart
+++ b/runtime/observatory/lib/src/app/application.dart
@@ -16,41 +16,75 @@
LocationManager _locationManager;
LocationManager get locationManager => _locationManager;
Page currentPage;
+ bool _vmConnected = false;
VM _vm;
VM get vm => _vm;
- _setVM(VM vm) {
- if (_vm == vm) {
+ bool isConnectedVMTarget(WebSocketVMTarget target) {
+ if (_vm is CommonWebSocketVM) {
+ if ((_vm as CommonWebSocketVM).target == target) {
+ return _vm.isConnected;
+ }
+ }
+ return false;
+ }
+
+ _switchVM(VM newVM) {
+ final VM oldVM = _vm;
+
+ Logger.root.info('_switchVM from:${oldVM} to:${newVM}');
+
+ if (oldVM == newVM) {
// Do nothing.
return;
}
- if (_vm != null) {
- _gcSubscription = null;
- // Disconnect from current VM.
- notifications.deleteAll();
- _vm.disconnect();
- }
- if (vm != null) {
- Logger.root.info('Registering new VM callbacks');
- vm.onConnect.then((_) {
+ if (oldVM != null) {
+ print('disconnecting from the old VM ${oldVM}--');
+ // Disconnect from current VM.
+ stopGCEventListener();
+ notifications.deleteAll();
+ oldVM.disconnect();
+ }
+
+ if (newVM != null) {
+ // Mark that we haven't connected yet.
+ _vmConnected = false;
+ // On connect:
+ newVM.onConnect.then((_) {
+ // We connected.
+ _vmConnected = true;
notifications.deleteDisconnectEvents();
});
-
- vm.onDisconnect.then((String reason) {
- if (this.vm != vm) {
+ // On disconnect:
+ newVM.onDisconnect.then((String reason) {
+ if (this.vm != newVM) {
// This disconnect event occured *after* a new VM was installed.
return;
}
- events.add(new ConnectionClosedEvent(new DateTime.now(), reason));
+ // Let anyone looking at the targets know that we have disconnected
+ // from one.
+ targets.emitDisconnectEvent();
+ if (!_vmConnected) {
+ // Connection error. Navigate back to the connect page.
+ Logger.root.info('Connection failed, navigating to VM connect page.');
+ // Clear the vm.
+ _vm = null;
+ app.locationManager.go(Uris.vmConnect());
+ } else {
+ // Disconnect. Stay at the current page and push an a connection
+ // closed event.
+ Logger.root.info('Lost an existing connection to a VM');
+ events.add(new ConnectionClosedEvent(new DateTime.now(), reason));
+ }
});
-
// TODO(cbernaschina) smart connection of streams in the events object.
- vm.listenEventStream(VM.kVMStream, _onEvent);
- vm.listenEventStream(VM.kIsolateStream, _onEvent);
- vm.listenEventStream(VM.kDebugStream, _onEvent);
+ newVM.listenEventStream(VM.kVMStream, _onEvent);
+ newVM.listenEventStream(VM.kIsolateStream, _onEvent);
+ newVM.listenEventStream(VM.kDebugStream, _onEvent);
}
- _vm = vm;
+
+ _vm = newVM;
}
StreamSubscription _gcSubscription;
@@ -87,7 +121,6 @@
_loggingSubscription = null;
}
-
final ObservatoryApplicationElement rootElement;
ServiceObject lastErrorOrException;
@@ -104,6 +137,7 @@
void _deletePauseEvents(e) {
notifications.deletePauseEvents(isolate: e.isolate);
}
+
void _addNotification(M.Event e) {
notifications.add(new EventNotification(e));
}
@@ -192,13 +226,24 @@
ObservatoryApplication(this.rootElement) {
_locationManager = new LocationManager(this);
- targets.onChange.listen((e) {
- if (targets.current == null) return _setVM(null);
- if ((_vm as WebSocketVM)?.target != targets.current) {
- _setVM(new WebSocketVM(targets.current));
+ targets.onChange.listen((TargetChangeEvent e) {
+ if (e.disconnected) {
+ // We don't care about disconnected events.
+ return;
+ }
+ if (targets.current == null) {
+ _switchVM(null);
+ }
+ final bool currentTarget =
+ (_vm as WebSocketVM)?.target == targets.current;
+ final bool currentTargetConnected = (_vm != null) && !_vm.isDisconnected;
+ if (!currentTarget || !currentTargetConnected) {
+ _switchVM(new WebSocketVM(targets.current));
}
});
- _setVM(new WebSocketVM(targets.current));
+
+ Logger.root.info('Setting initial target to ${targets.current.name}');
+ _switchVM(new WebSocketVM(targets.current));
_initOnce();
// delete pause events.
@@ -217,11 +262,12 @@
events.onPauseInterrupted.listen(_addNotification);
events.onPauseException.listen(_addNotification);
events.onInspect.listen(_addNotification);
+ events.onConnectionClosed.listen(_addNotification);
}
loadCrashDump(Map crashDump) {
- _setVM(new FakeVM(crashDump['result']));
- app.locationManager.go('#/vm');
+ _switchVM(new FakeVM(crashDump['result']));
+ app.locationManager.go(Uris.vm());
}
void handleException(e, st) {
@@ -238,5 +284,5 @@
}
// This map keeps track of which curly-blocks have been expanded by the user.
- Map<String,bool> expansions = {};
+ Map<String, bool> expansions = {};
}
diff --git a/runtime/observatory/lib/src/app/location_manager.dart b/runtime/observatory/lib/src/app/location_manager.dart
index ae684b8..38dd94c 100644
--- a/runtime/observatory/lib/src/app/location_manager.dart
+++ b/runtime/observatory/lib/src/app/location_manager.dart
@@ -5,8 +5,6 @@
part of app;
class LocationManager {
- final _defaultPath = '/vm';
-
final ObservatoryApplication _app;
/// [internalArguments] are parameters specified after a '---' in the
@@ -14,6 +12,7 @@
final Map<String, String> internalArguments = new Map<String, String>();
Uri _uri;
+
/// [uri] is the application uri. Application uris consist of a path and
/// the queryParameters map.
Uri get uri => _uri;
@@ -25,12 +24,12 @@
if ((window.location.hash == '') || (window.location.hash == '#')) {
// Observatory has loaded but no application path has been specified,
// use the default.
- applicationPath = makeLink(_defaultPath);
+ // By default we navigate to the VM page.
+ applicationPath = Uris.vm();
}
// Update current application path.
- window.history.replaceState(applicationPath,
- document.title,
- applicationPath);
+ window.history
+ .replaceState(applicationPath, document.title, applicationPath);
_updateApplicationLocation(applicationPath);
}
@@ -54,7 +53,7 @@
/// Update the application location. After this function returns,
/// [uri] and [debugArguments] will be updated.
_updateApplicationLocation(String url) {
- if (url == makeLink('/vm-connect')) {
+ if (url == Uris.vmConnect()) {
// When we go to the vm-connect page, drop all notifications.
_app.notifications.deleteAll();
}
@@ -91,11 +90,11 @@
/// Notify the current page that something has changed.
_visit() {
- runZoned(() => _app._visit(_uri, internalArguments),
- onError: (e, st) {
+ Chain.capture(() => _app._visit(_uri, internalArguments), onError: (e, st) {
if (e is IsolateNotFound) {
var newPath = ((_app.vm == null || _app.vm.isDisconnected)
- ? '/vm-connect' : '/isolate-reconnect');
+ ? '/vm-connect'
+ : '/isolate-reconnect');
var parameters = {};
parameters.addAll(_uri.queryParameters);
parameters['originalUri'] = _uri.toString();
@@ -111,15 +110,6 @@
/// Navigate to [url].
void go(String url, [bool addToBrowserHistory = true]) {
- if ((url != makeLink('/vm-connect')) &&
- (_app.vm == null || _app.vm.isDisconnected)) {
- if (!window.confirm('Connection with VM has been lost. '
- 'Proceeding will lose current page.')) {
- return;
- }
- url = makeLink('/vm-connect');
- }
-
if (addToBrowserHistory) {
_addToBrowserHistory(url);
}
@@ -130,7 +120,8 @@
/// Starting with the current uri path and queryParameters, update
/// queryParameters present in [updateParameters], then generate a new uri
/// and navigate to that.
- goReplacingParameters(Map updatedParameters, [bool addToBrowserHistory = true]) {
+ goReplacingParameters(Map updatedParameters,
+ [bool addToBrowserHistory = true]) {
go(makeLinkReplacingParameters(updatedParameters), addToBrowserHistory);
}
@@ -158,9 +149,9 @@
/// Utility event handler when clicking on application url link.
void onGoto(MouseEvent event) {
if ((event.button > 0) ||
- event.metaKey ||
- event.ctrlKey ||
- event.shiftKey ||
+ event.metaKey ||
+ event.ctrlKey ||
+ event.shiftKey ||
event.altKey) {
// Mouse event is not a left-click OR
// mouse event is a left-click with a modifier key:
diff --git a/runtime/observatory/lib/src/app/notification.dart b/runtime/observatory/lib/src/app/notification.dart
index 140e0dc..1f5f9d7 100644
--- a/runtime/observatory/lib/src/app/notification.dart
+++ b/runtime/observatory/lib/src/app/notification.dart
@@ -5,7 +5,8 @@
part of app;
class ExceptionNotification implements M.ExceptionNotification {
- final Exception exception;
+ final exception;
+
/// [optional]
final StackTrace stacktrace;
ExceptionNotification(this.exception, {this.stacktrace});
diff --git a/runtime/observatory/lib/src/app/page.dart b/runtime/observatory/lib/src/app/page.dart
index 600199c..e5fc6da 100644
--- a/runtime/observatory/lib/src/app/page.dart
+++ b/runtime/observatory/lib/src/app/page.dart
@@ -32,17 +32,17 @@
final _topRetainingInstancesRepository = new TopRetainingInstancesRepository();
final _typeArgumentsRepository = new TypeArgumentsRepository();
-
class IsolateNotFound implements Exception {
String isolateId;
IsolateNotFound(this.isolateId);
String toString() => "IsolateNotFound: $isolateId";
}
+
RetainedSizeRepository _retainedSizeRepository = new RetainedSizeRepository();
-ReachableSizeRepository _reachableSizeRepository
- = new ReachableSizeRepository();
-RetainingPathRepository _retainingPathRepository
- = new RetainingPathRepository();
+ReachableSizeRepository _reachableSizeRepository =
+ new ReachableSizeRepository();
+RetainingPathRepository _retainingPathRepository =
+ new RetainingPathRepository();
/// A [Page] controls the user interface of Observatory. At any given time
/// one page will be the current page. Pages are registered at startup.
@@ -152,16 +152,22 @@
void _visit(Uri uri) {
super._visit(uri);
+ if (app.vm == null) {
+ Logger.root.severe('VMPage has no VM');
+ // Reroute to vm-connect.
+ app.locationManager.go(Uris.vmConnect());
+ return;
+ }
app.vm.reload().then((VM vm) {
container.children = [
- new VMViewElement(vm, app.events, app.notifications,
- _isolateRepository, _scriptRepository,
- queue: app.queue)
+ new VMViewElement(vm, app.events, app.notifications, _isolateRepository,
+ _scriptRepository,
+ queue: app.queue)
];
}).catchError((e, stack) {
Logger.root.severe('VMPage visit error: $e');
// Reroute to vm-connect.
- app.locationManager.go(app.locationManager.makeLink('/vm-connect'));
+ app.locationManager.go(Uris.vmConnect());
});
}
}
@@ -171,11 +177,9 @@
@override
onInstall() {
- element = new FlagListElement(app.vm,
- app.events,
- new FlagsRepository(app.vm),
- app.notifications,
- queue: app.queue);
+ element = new FlagListElement(
+ app.vm, app.events, new FlagsRepository(app.vm), app.notifications,
+ queue: app.queue);
}
void _visit(Uri uri) {
@@ -212,45 +216,57 @@
await obj.reload();
if (obj is Class) {
container.children = [
- new ClassViewElement(app.vm, obj.isolate, obj, app.events,
- app.notifications,
- _classRepository,
- _retainedSizeRepository,
- _reachableSizeRepository,
- _inboundReferencesRepository,
- _retainingPathRepository,
- _fieldRepository,
- _scriptRepository,
- _instanceRepository,
- _evalRepository,
- _stronglyReachangleInstancesRepository,
- _topRetainingInstancesRepository,
- _classSampleProfileRepository,
- queue: app.queue)
+ new ClassViewElement(
+ app.vm,
+ obj.isolate,
+ obj,
+ app.events,
+ app.notifications,
+ _classRepository,
+ _retainedSizeRepository,
+ _reachableSizeRepository,
+ _inboundReferencesRepository,
+ _retainingPathRepository,
+ _fieldRepository,
+ _scriptRepository,
+ _instanceRepository,
+ _evalRepository,
+ _stronglyReachangleInstancesRepository,
+ _topRetainingInstancesRepository,
+ _classSampleProfileRepository,
+ queue: app.queue)
];
} else if (obj is Code) {
await obj.loadScript();
container.children = [
- new CodeViewElement(app.vm, obj.isolate, obj, app.events,
- app.notifications,
- _retainedSizeRepository,
- _reachableSizeRepository,
- _inboundReferencesRepository,
- _retainingPathRepository,
- _instanceRepository,
- queue: app.queue)
+ new CodeViewElement(
+ app.vm,
+ obj.isolate,
+ obj,
+ app.events,
+ app.notifications,
+ _retainedSizeRepository,
+ _reachableSizeRepository,
+ _inboundReferencesRepository,
+ _retainingPathRepository,
+ _instanceRepository,
+ queue: app.queue)
];
} else if (obj is Context) {
container.children = [
- new ContextViewElement(app.vm, obj.isolate, obj, app.events,
- app.notifications,
- _contextRepository,
- _retainedSizeRepository,
- _reachableSizeRepository,
- _inboundReferencesRepository,
- _retainingPathRepository,
- _instanceRepository,
- queue: app.queue)
+ new ContextViewElement(
+ app.vm,
+ obj.isolate,
+ obj,
+ app.events,
+ app.notifications,
+ _contextRepository,
+ _retainedSizeRepository,
+ _reachableSizeRepository,
+ _inboundReferencesRepository,
+ _retainingPathRepository,
+ _instanceRepository,
+ queue: app.queue)
];
} else if (obj is DartError) {
container.children = [
@@ -258,111 +274,142 @@
];
} else if (obj is Field) {
container.children = [
- new FieldViewElement(app.vm, obj.isolate, obj, app.events,
- app.notifications,
- _fieldRepository,
- _classRepository,
- _retainedSizeRepository,
- _reachableSizeRepository,
- _inboundReferencesRepository,
- _retainingPathRepository,
- _scriptRepository,
- _instanceRepository,
- queue: app.queue)
+ new FieldViewElement(
+ app.vm,
+ obj.isolate,
+ obj,
+ app.events,
+ app.notifications,
+ _fieldRepository,
+ _classRepository,
+ _retainedSizeRepository,
+ _reachableSizeRepository,
+ _inboundReferencesRepository,
+ _retainingPathRepository,
+ _scriptRepository,
+ _instanceRepository,
+ queue: app.queue)
];
} else if (obj is Instance) {
container.children = [
- new InstanceViewElement(app.vm, obj.isolate, obj, app.events,
- app.notifications,
- _instanceRepository,
- _classRepository,
- _retainedSizeRepository,
- _reachableSizeRepository,
- _inboundReferencesRepository,
- _retainingPathRepository,
- _scriptRepository,
- _evalRepository,
- _typeArgumentsRepository,
- _breakpointRepository,
- _functionRepository,
- queue: app.queue)
+ new InstanceViewElement(
+ app.vm,
+ obj.isolate,
+ obj,
+ app.events,
+ app.notifications,
+ _instanceRepository,
+ _classRepository,
+ _retainedSizeRepository,
+ _reachableSizeRepository,
+ _inboundReferencesRepository,
+ _retainingPathRepository,
+ _scriptRepository,
+ _evalRepository,
+ _typeArgumentsRepository,
+ _breakpointRepository,
+ _functionRepository,
+ queue: app.queue)
];
} else if (obj is Isolate) {
container.children = [
- new IsolateViewElement(app.vm, obj, app.events,
- app.notifications,
- _isolateRepository,
- _scriptRepository,
- _functionRepository,
- _libraryRepository,
- _instanceRepository,
- _evalRepository,
- queue: app.queue)
+ new IsolateViewElement(
+ app.vm,
+ obj,
+ app.events,
+ app.notifications,
+ _isolateRepository,
+ _scriptRepository,
+ _functionRepository,
+ _libraryRepository,
+ _instanceRepository,
+ _evalRepository,
+ queue: app.queue)
];
} else if (obj is ServiceFunction) {
container.children = [
- new FunctionViewElement(app.vm, obj.isolate, obj, app.events,
- app.notifications,
- _functionRepository,
- _classRepository,
- _retainedSizeRepository,
- _reachableSizeRepository,
- _inboundReferencesRepository,
- _retainingPathRepository,
- _scriptRepository,
- _instanceRepository,
- queue: app.queue)
+ new FunctionViewElement(
+ app.vm,
+ obj.isolate,
+ obj,
+ app.events,
+ app.notifications,
+ _functionRepository,
+ _classRepository,
+ _retainedSizeRepository,
+ _reachableSizeRepository,
+ _inboundReferencesRepository,
+ _retainingPathRepository,
+ _scriptRepository,
+ _instanceRepository,
+ queue: app.queue)
];
} else if (obj is ICData) {
container.children = [
- new ICDataViewElement(app.vm, obj.isolate, obj, app.events,
- app.notifications,
- _icdataRepository,
- _retainedSizeRepository,
- _reachableSizeRepository,
- _inboundReferencesRepository,
- _retainingPathRepository,
- _instanceRepository,
- queue: app.queue)
+ new ICDataViewElement(
+ app.vm,
+ obj.isolate,
+ obj,
+ app.events,
+ app.notifications,
+ _icdataRepository,
+ _retainedSizeRepository,
+ _reachableSizeRepository,
+ _inboundReferencesRepository,
+ _retainingPathRepository,
+ _instanceRepository,
+ queue: app.queue)
];
} else if (obj is Library) {
container.children = [
- new LibraryViewElement(app.vm, obj.isolate, obj, app.events,
- app.notifications,
- _libraryRepository,
- _fieldRepository,
- _retainedSizeRepository,
- _reachableSizeRepository,
- _inboundReferencesRepository,
- _retainingPathRepository,
- _scriptRepository,
- _instanceRepository,
- _evalRepository,
- queue: app.queue)
+ new LibraryViewElement(
+ app.vm,
+ obj.isolate,
+ obj,
+ app.events,
+ app.notifications,
+ _libraryRepository,
+ _fieldRepository,
+ _retainedSizeRepository,
+ _reachableSizeRepository,
+ _inboundReferencesRepository,
+ _retainingPathRepository,
+ _scriptRepository,
+ _instanceRepository,
+ _evalRepository,
+ queue: app.queue)
];
} else if (obj is MegamorphicCache) {
container.children = [
- new MegamorphicCacheViewElement(app.vm, obj.isolate, obj, app.events,
- app.notifications,
- _megamorphicCacheRepository,
- _retainedSizeRepository,
- _reachableSizeRepository,
- _inboundReferencesRepository,
- _retainingPathRepository,
- _instanceRepository,
- queue: app.queue)
+ new MegamorphicCacheViewElement(
+ app.vm,
+ obj.isolate,
+ obj,
+ app.events,
+ app.notifications,
+ _megamorphicCacheRepository,
+ _retainedSizeRepository,
+ _reachableSizeRepository,
+ _inboundReferencesRepository,
+ _retainingPathRepository,
+ _instanceRepository,
+ queue: app.queue)
];
} else if (obj is ObjectPool) {
container.children = [
- new ObjectPoolViewElement(app.vm, obj.isolate, obj, app.events,
- app.notifications,
- _objectPoolRepository,
- _retainedSizeRepository,
- _reachableSizeRepository,
- _inboundReferencesRepository,
- _retainingPathRepository,
- _instanceRepository,
- queue: app.queue)
+ new ObjectPoolViewElement(
+ app.vm,
+ obj.isolate,
+ obj,
+ app.events,
+ app.notifications,
+ _objectPoolRepository,
+ _retainedSizeRepository,
+ _reachableSizeRepository,
+ _inboundReferencesRepository,
+ _retainingPathRepository,
+ _instanceRepository,
+ queue: app.queue)
];
} else if (obj is Script) {
var pos;
@@ -372,32 +419,42 @@
} catch (_) {}
}
container.children = [
- new ScriptViewElement(app.vm, obj.isolate, obj, app.events,
- app.notifications,
- _scriptRepository,
- _retainedSizeRepository,
- _reachableSizeRepository,
- _inboundReferencesRepository,
- _retainingPathRepository,
- _instanceRepository,
- pos: pos, queue: app.queue)
+ new ScriptViewElement(
+ app.vm,
+ obj.isolate,
+ obj,
+ app.events,
+ app.notifications,
+ _scriptRepository,
+ _retainedSizeRepository,
+ _reachableSizeRepository,
+ _inboundReferencesRepository,
+ _retainingPathRepository,
+ _instanceRepository,
+ pos: pos,
+ queue: app.queue)
];
} else if (obj is HeapObject) {
container.children = [
- new ObjectViewElement(app.vm, obj.isolate, obj, app.events,
- app.notifications,
- _objectRepository,
- _retainedSizeRepository,
- _reachableSizeRepository,
- _inboundReferencesRepository,
- _retainingPathRepository,
- _instanceRepository,
- queue: app.queue)
+ new ObjectViewElement(
+ app.vm,
+ obj.isolate,
+ obj,
+ app.events,
+ app.notifications,
+ _objectRepository,
+ _retainedSizeRepository,
+ _reachableSizeRepository,
+ _inboundReferencesRepository,
+ _retainingPathRepository,
+ _instanceRepository,
+ queue: app.queue)
];
} else if (obj is Sentinel) {
container.children = [
- new SentinelViewElement(app.vm, obj.isolate, obj, app.events,
- app.notifications, queue: app.queue)
+ new SentinelViewElement(
+ app.vm, obj.isolate, obj, app.events, app.notifications,
+ queue: app.queue)
];
} else {
container.children = [
@@ -407,7 +464,6 @@
}
}
-
/// Class tree page.
class ClassTreePage extends SimplePage {
ClassTreePage(app) : super('class-tree', 'class-tree', app);
@@ -423,11 +479,8 @@
super._visit(uri);
getIsolate(uri).then((isolate) {
container.children = [
- new ClassTreeElement(app.vm,
- isolate,
- app.events,
- app.notifications,
- _classRepository)
+ new ClassTreeElement(
+ app.vm, isolate, app.events, app.notifications, _classRepository)
];
});
}
@@ -442,8 +495,8 @@
super._visit(uri);
getIsolate(uri).then((isolate) async {
container.children = [
- new DebuggerPageElement(isolate, _instanceRepository,
- _scriptRepository, app.events)
+ new DebuggerPageElement(
+ isolate, _instanceRepository, _scriptRepository, app.events)
];
});
}
@@ -471,11 +524,8 @@
super._visit(uri);
getIsolate(uri).then((isolate) async {
container.children = [
- new ObjectStoreViewElement(isolate.vm, isolate,
- app.events,
- app.notifications,
- _objectstoreRepository,
- _instanceRepository)
+ new ObjectStoreViewElement(isolate.vm, isolate, app.events,
+ app.notifications, _objectstoreRepository, _instanceRepository)
];
});
}
@@ -498,8 +548,7 @@
getIsolate(uri).then((isolate) {
container.children = [
new CpuProfileElement(isolate.vm, isolate, app.events,
- app.notifications,
- _isolateSampleProfileRepository)
+ app.notifications, _isolateSampleProfileRepository)
];
});
}
@@ -522,8 +571,7 @@
getIsolate(uri).then((isolate) {
container.children = [
new CpuProfileTableElement(isolate.vm, isolate, app.events,
- app.notifications,
- _isolateSampleProfileRepository)
+ app.notifications, _isolateSampleProfileRepository)
];
});
}
@@ -546,9 +594,8 @@
getIsolate(uri).then((isolate) {
container.children = [
new AllocationProfileElement(isolate.vm, isolate, app.events,
- app.notifications,
- _allocationProfileRepository,
- queue: app.queue)
+ app.notifications, _allocationProfileRepository,
+ queue: app.queue)
];
});
}
@@ -578,8 +625,8 @@
getIsolate(uri).then((isolate) {
container.children = [
new PortsElement(isolate.vm, isolate, app.events, app.notifications,
- _portsRepository, _instanceRepository,
- queue: app.queue)
+ _portsRepository, _instanceRepository,
+ queue: app.queue)
];
});
}
@@ -600,10 +647,14 @@
super._visit(uri);
getIsolate(uri).then((isolate) {
container.children = [
- new PersistentHandlesPageElement(isolate.vm, isolate, app.events,
- app.notifications,
- _persistentHandlesRepository,
- _instanceRepository, queue: app.queue)
+ new PersistentHandlesPageElement(
+ isolate.vm,
+ isolate,
+ app.events,
+ app.notifications,
+ _persistentHandlesRepository,
+ _instanceRepository,
+ queue: app.queue)
];
});
}
@@ -625,7 +676,7 @@
getIsolate(uri).then((isolate) {
container.children = [
new HeapMapElement(isolate.vm, isolate, app.events, app.notifications,
- queue: app.queue)
+ queue: app.queue)
];
});
}
@@ -647,8 +698,8 @@
getIsolate(uri).then((isolate) {
container.children = [
new HeapSnapshotElement(isolate.vm, isolate, app.events,
- app.notifications, _heapSnapshotRepository,
- _instanceRepository, queue: app.queue)
+ app.notifications, _heapSnapshotRepository, _instanceRepository,
+ queue: app.queue)
];
});
}
@@ -684,8 +735,8 @@
assert(canVisit(uri));
getIsolate(uri).then((isolate) {
container.children = [
- new LoggingPageElement(app.vm, isolate, app.events,
- app.notifications, queue: app.queue)
+ new LoggingPageElement(app.vm, isolate, app.events, app.notifications,
+ queue: app.queue)
];
});
}
@@ -695,9 +746,9 @@
ErrorViewPage(app) : super(app);
void onInstall() {
- element = new ErrorViewElement(app.notifications,
- app.lastErrorOrException as DartError,
- queue: app.queue);
+ element = new ErrorViewElement(
+ app.notifications, app.lastErrorOrException as DartError,
+ queue: app.queue);
}
void _visit(Uri uri) {
@@ -715,10 +766,10 @@
void onInstall() {
if (element == null) {
element = new VMConnectElement(
- ObservatoryApplication.app.targets,
- ObservatoryApplication.app.loadCrashDump,
- ObservatoryApplication.app.notifications,
- queue: ObservatoryApplication.app.queue);
+ ObservatoryApplication.app.targets,
+ ObservatoryApplication.app.loadCrashDump,
+ ObservatoryApplication.app.notifications,
+ queue: ObservatoryApplication.app.queue);
}
assert(element != null);
}
@@ -743,9 +794,12 @@
void _visit(Uri uri) {
app.vm.reload();
container.children = [
- new IsolateReconnectElement(app.vm, app.events, app.notifications,
- uri.queryParameters['isolateId'],
- Uri.parse(uri.queryParameters['originalUri']))
+ new IsolateReconnectElement(
+ app.vm,
+ app.events,
+ app.notifications,
+ uri.queryParameters['isolateId'],
+ Uri.parse(uri.queryParameters['originalUri']))
];
assert(element != null);
assert(canVisit(uri));
@@ -769,8 +823,8 @@
await _metricRepository.startSampling(isolate);
container.children = [
new MetricsPageElement(isolate.vm, isolate, app.events,
- app.notifications, _metricRepository,
- queue: app.queue)
+ app.notifications, _metricRepository,
+ queue: app.queue)
];
});
}
@@ -794,7 +848,7 @@
void onInstall() {
element = new TimelinePageElement(app.vm, app.events, app.notifications,
- queue: app.queue);
+ queue: app.queue);
}
void _visit(Uri uri) {
diff --git a/runtime/observatory/lib/src/app/settings.dart b/runtime/observatory/lib/src/app/settings.dart
index 2a7bbb3..32339d0 100644
--- a/runtime/observatory/lib/src/app/settings.dart
+++ b/runtime/observatory/lib/src/app/settings.dart
@@ -42,4 +42,4 @@
var fullKey = _fullKey(key);
return _Settings.get(fullKey);
}
-}
\ No newline at end of file
+}
diff --git a/runtime/observatory/lib/src/app/view_model.dart b/runtime/observatory/lib/src/app/view_model.dart
index e7e546f..d312cb3 100644
--- a/runtime/observatory/lib/src/app/view_model.dart
+++ b/runtime/observatory/lib/src/app/view_model.dart
@@ -10,11 +10,11 @@
static String toStringFormatter(dynamic v) {
return v != null ? v.toString() : '<null>';
}
+
final String label;
final ValueFormatter formatter;
SortedTableColumn.withFormatter(this.label, this.formatter);
- SortedTableColumn(this.label)
- : formatter = toStringFormatter;
+ SortedTableColumn(this.label) : formatter = toStringFormatter;
}
class SortedTableRow {
@@ -35,6 +35,7 @@
assert(index < columns.length);
_sortColumnIndex = index;
}
+
int get sortColumnIndex => _sortColumnIndex;
bool _sortDescending = true;
bool get sortDescending => _sortDescending;
@@ -42,7 +43,6 @@
_sortDescending = descending;
}
-
dynamic getSortKeyFor(int row, int col) {
return rows[row].values[col];
}
diff --git a/runtime/observatory/lib/src/cli/command.dart b/runtime/observatory/lib/src/cli/command.dart
index b9eebb0..28ffbff 100644
--- a/runtime/observatory/lib/src/cli/command.dart
+++ b/runtime/observatory/lib/src/cli/command.dart
@@ -84,7 +84,7 @@
if (matches.isEmpty) {
return [];
} else if (matches.length == 1) {
- var childMatches = matches[0]._match(args.sublist(1), preferExact);
+ var childMatches = matches[0]._match(args.sublist(1), preferExact);
if (childMatches.isEmpty) {
return matches;
} else {
@@ -96,32 +96,31 @@
}
// Builds a list of completions for this command.
- Future<List<String>> _buildCompletions(List<String> args,
- bool addEmptyString) {
- return complete(args.sublist(_depth, args.length))
- .then((completions) {
- if (addEmptyString && completions.isEmpty &&
- args[args.length - 1] == '') {
- // Special case allowance for an empty particle at the end of
- // the command.
- completions = [''];
- }
- var prefix = _concatArgs(args, _depth);
- return completions.map((str) => '${prefix}${str}').toList();
- });
+ Future<List<String>> _buildCompletions(
+ List<String> args, bool addEmptyString) {
+ return complete(args.sublist(_depth, args.length)).then((completions) {
+ if (addEmptyString &&
+ completions.isEmpty &&
+ args[args.length - 1] == '') {
+ // Special case allowance for an empty particle at the end of
+ // the command.
+ completions = [''];
+ }
+ var prefix = _concatArgs(args, _depth);
+ return completions.map((str) => '${prefix}${str}').toList();
+ });
}
-
}
// The root of a tree of commands.
class RootCommand extends _CommandBase {
RootCommand(List<Command> children, [List<String> history])
- : this._(children, history ?? ['']);
+ : this._(children, history ?? ['']);
- RootCommand._(List<Command> children, List<String> history)
+ RootCommand._(List<Command> children, List<String> history)
: history = history,
historyPos = history.length - 1,
- super(children);
+ super(children);
// Provides a list of possible completions for a line of text.
Future<List<String>> completeCommand(String line) {
@@ -132,7 +131,7 @@
// subcommands of the last command.
args.add('');
}
- var commands = _match(args, false);
+ var commands = _match(args, false);
if (commands.isEmpty) {
// No matching commands.
return new Future.value([]);
@@ -160,11 +159,13 @@
if (matchLen == args.length) {
// If we are showing all possiblities, also include local
// completions for the parent command.
- return commands[0]._parent._buildCompletions(args, false)
- .then((localCompletions) {
- completions.addAll(localCompletions);
- return completions;
- });
+ return commands[0]
+ ._parent
+ ._buildCompletions(args, false)
+ .then((localCompletions) {
+ completions.addAll(localCompletions);
+ return completions;
+ });
}
return new Future.value(completions);
}
@@ -173,7 +174,7 @@
Future runCommand(String line) {
_historyAdvance(line);
var args = _splitLine(line);
- var commands = _match(args, true);
+ var commands = _match(args, true);
if (commands.isEmpty) {
// TODO(turnidge): Add a proper exception class for this.
return new Future.error('No such command');
diff --git a/runtime/observatory/lib/src/cpu_profile/cpu_profile.dart b/runtime/observatory/lib/src/cpu_profile/cpu_profile.dart
index 9cb7ebd..1c6d980 100644
--- a/runtime/observatory/lib/src/cpu_profile/cpu_profile.dart
+++ b/runtime/observatory/lib/src/cpu_profile/cpu_profile.dart
@@ -43,8 +43,7 @@
class CodeCallTree extends CallTree<CodeCallTreeNode>
implements M.CodeCallTree {
- CodeCallTree(bool inclusive, CodeCallTreeNode root)
- : super(inclusive, root) {
+ CodeCallTree(bool inclusive, CodeCallTreeNode root) : super(inclusive, root) {
_setCodePercentage(null, root);
}
@@ -73,8 +72,8 @@
}
}
- _recordCallerAndCalleesInner(CodeCallTreeNode caller,
- CodeCallTreeNode callee) {
+ _recordCallerAndCalleesInner(
+ CodeCallTreeNode caller, CodeCallTreeNode callee) {
if (caller != null) {
caller.profileCode._recordCallee(callee.profileCode, callee.count);
callee.profileCode._recordCaller(caller.profileCode, caller.count);
@@ -164,8 +163,7 @@
return false;
}
- setCodeAttributes() {
- }
+ setCodeAttributes() {}
}
/// Predicate filter function. Returns true if path from root to [node] and all
@@ -176,8 +174,10 @@
abstract class _FilteredCallTreeBuilder {
/// The filter.
final CallTreeNodeFilter filter;
+
/// The unfiltered tree.
final CallTree _unfilteredTree;
+
/// The filtered tree (construct by [build]).
final CallTree filtered;
final List _currentPath = [];
@@ -194,8 +194,7 @@
_descend(_unfilteredTree.root);
}
- CallTreeNode _findInChildren(CallTreeNode current,
- CallTreeNode needle) {
+ CallTreeNode _findInChildren(CallTreeNode current, CallTreeNode needle) {
for (var child in current.children) {
if (child.profileData == needle.profileData) {
return child;
@@ -283,12 +282,15 @@
}
class _FilteredFunctionCallTreeBuilder extends _FilteredCallTreeBuilder {
- _FilteredFunctionCallTreeBuilder(CallTreeNodeFilter filter,
- FunctionCallTree tree)
- : super(filter, tree,
- new FunctionCallTree(tree.inclusive,
- new FunctionCallTreeNode(tree.root.profileData,
- tree.root.count)));
+ _FilteredFunctionCallTreeBuilder(
+ CallTreeNodeFilter filter, FunctionCallTree tree)
+ : super(
+ filter,
+ tree,
+ new FunctionCallTree(
+ tree.inclusive,
+ new FunctionCallTreeNode(
+ tree.root.profileData, tree.root.count)));
_copyNode(FunctionCallTreeNode node) {
return new FunctionCallTreeNode(node.profileData, node.count);
@@ -296,12 +298,12 @@
}
class _FilteredCodeCallTreeBuilder extends _FilteredCallTreeBuilder {
- _FilteredCodeCallTreeBuilder(CallTreeNodeFilter filter,
- CodeCallTree tree)
- : super(filter, tree,
+ _FilteredCodeCallTreeBuilder(CallTreeNodeFilter filter, CodeCallTree tree)
+ : super(
+ filter,
+ tree,
new CodeCallTree(tree.inclusive,
- new CodeCallTreeNode(tree.root.profileData,
- tree.root.count)));
+ new CodeCallTreeNode(tree.root.profileData, tree.root.count)));
_copyNode(CodeCallTreeNode node) {
return new CodeCallTreeNode(node.profileData, node.count);
@@ -321,8 +323,8 @@
return treeFilter.filtered;
}
- void _setFunctionPercentage(FunctionCallTreeNode parent,
- FunctionCallTreeNode node) {
+ void _setFunctionPercentage(
+ FunctionCallTreeNode parent, FunctionCallTreeNode node) {
assert(node != null);
var parentPercentage = 1.0;
var parentCount = node.count;
@@ -340,11 +342,13 @@
}
}
- _markFunctionCallsInner(FunctionCallTreeNode caller,
- FunctionCallTreeNode callee) {
+ _markFunctionCallsInner(
+ FunctionCallTreeNode caller, FunctionCallTreeNode callee) {
if (caller != null) {
- caller.profileFunction._recordCallee(callee.profileFunction, callee.count);
- callee.profileFunction._recordCaller(caller.profileFunction, caller.count);
+ caller.profileFunction
+ ._recordCallee(callee.profileFunction, callee.count);
+ callee.profileFunction
+ ._recordCaller(caller.profileFunction, caller.count);
}
for (var child in callee.children) {
_markFunctionCallsInner(callee, child);
@@ -395,7 +399,7 @@
assert(profileTicks != null);
assert((profileTicks.length % 3) == 0);
for (var i = 0; i < profileTicks.length; i += 3) {
- var address = int.parse(profileTicks[i], radix:16);
+ var address = int.parse(profileTicks[i], radix: 16);
var exclusive = int.parse(profileTicks[i + 1]);
var inclusive = int.parse(profileTicks[i + 2]);
var tick = new CodeTick(exclusive, inclusive);
@@ -425,7 +429,7 @@
attributes.add('stub');
} else if (code.kind == M.CodeKind.dart) {
if (code.isNative) {
- attributes.add('ffi'); // Not to be confused with a C function.
+ attributes.add('ffi'); // Not to be confused with a C function.
} else {
attributes.add('dart');
}
@@ -457,21 +461,19 @@
formattedExclusivePercent =
Utils.formatPercent(exclusiveTicks, profile.sampleCount);
- formattedCpuTime =
- Utils.formatTimeMilliseconds(
- profile.approximateMillisecondsForCount(exclusiveTicks));
+ formattedCpuTime = Utils.formatTimeMilliseconds(
+ profile.approximateMillisecondsForCount(exclusiveTicks));
- formattedOnStackTime =
- Utils.formatTimeMilliseconds(
- profile.approximateMillisecondsForCount(inclusiveTicks));
+ formattedOnStackTime = Utils.formatTimeMilliseconds(
+ profile.approximateMillisecondsForCount(inclusiveTicks));
formattedInclusiveTicks =
- '${Utils.formatPercent(inclusiveTicks, profile.sampleCount)} '
- '($inclusiveTicks)';
+ '${Utils.formatPercent(inclusiveTicks, profile.sampleCount)} '
+ '($inclusiveTicks)';
formattedExclusiveTicks =
- '${Utils.formatPercent(exclusiveTicks, profile.sampleCount)} '
- '($exclusiveTicks)';
+ '${Utils.formatPercent(exclusiveTicks, profile.sampleCount)} '
+ '($exclusiveTicks)';
}
_recordCaller(ProfileCode caller, int count) {
@@ -580,7 +582,7 @@
} else if (M.isSyntheticFunction(function.kind)) {
attribs.add('synthetic');
} else if (function.isNative) {
- attribs.add('ffi'); // Not to be confused with a C function.
+ attribs.add('ffi'); // Not to be confused with a C function.
} else {
attribs.add('dart');
}
@@ -607,13 +609,11 @@
formattedExclusivePercent =
Utils.formatPercent(exclusiveTicks, profile.sampleCount);
- formattedCpuTime =
- Utils.formatTimeMilliseconds(
- profile.approximateMillisecondsForCount(exclusiveTicks));
+ formattedCpuTime = Utils.formatTimeMilliseconds(
+ profile.approximateMillisecondsForCount(exclusiveTicks));
- formattedOnStackTime =
- Utils.formatTimeMilliseconds(
- profile.approximateMillisecondsForCount(inclusiveTicks));
+ formattedOnStackTime = Utils.formatTimeMilliseconds(
+ profile.approximateMillisecondsForCount(inclusiveTicks));
formattedInclusiveTicks =
'${Utils.formatPercent(inclusiveTicks, profile.sampleCount)} '
@@ -641,10 +641,8 @@
}
}
-
// TODO(johnmccutchan): Rename to SampleProfile
class CpuProfile extends M.SampleProfile {
-
Isolate isolate;
int sampleCount = 0;
@@ -718,7 +716,7 @@
static Future sleep([Duration duration = const Duration(microseconds: 0)]) {
final Completer completer = new Completer();
- new Timer(duration, () => completer.complete() );
+ new Timer(duration, () => completer.complete());
return completer.future;
}
@@ -757,8 +755,7 @@
stackDepth = profile['stackDepth'];
timeSpan = profile['timeSpan'];
- num length = profile['codes'].length +
- profile['functions'].length;
+ num length = profile['codes'].length + profile['functions'].length;
// Process code table.
for (var codeRegion in profile['codes']) {
diff --git a/runtime/observatory/lib/src/debugger/debugger_location.dart b/runtime/observatory/lib/src/debugger/debugger_location.dart
index d1b4054..ba05ed5 100644
--- a/runtime/observatory/lib/src/debugger/debugger_location.dart
+++ b/runtime/observatory/lib/src/debugger/debugger_location.dart
@@ -38,8 +38,8 @@
if (match != null) {
return _parseFunction(debugger, match);
}
- return new Future.value(new DebuggerLocation.error(
- "Invalid source location '${locDesc}'"));
+ return new Future.value(
+ new DebuggerLocation.error("Invalid source location '${locDesc}'"));
}
static Future<Frame> _currentFrame(Debugger debugger) async {
@@ -63,8 +63,8 @@
return new DebuggerLocation.file(script, line, col);
}
- static Future<DebuggerLocation> _parseScriptLine(Debugger debugger,
- Match match) async {
+ static Future<DebuggerLocation> _parseScriptLine(
+ Debugger debugger, Match match) async {
var scriptName = match.group(1);
if (scriptName != null) {
scriptName = scriptName.substring(0, scriptName.length - 1);
@@ -75,17 +75,15 @@
if (colStr != null) {
colStr = colStr.substring(1);
}
- var line = int.parse(lineStr, onError:(_) => -1);
- var col = (colStr != null
- ? int.parse(colStr, onError:(_) => -1)
- : null);
+ var line = int.parse(lineStr, onError: (_) => -1);
+ var col = (colStr != null ? int.parse(colStr, onError: (_) => -1) : null);
if (line == -1) {
- return new Future.value(new DebuggerLocation.error(
- "Line '${lineStr}' must be an integer"));
+ return new Future.value(
+ new DebuggerLocation.error("Line '${lineStr}' must be an integer"));
}
if (col == -1) {
- return new Future.value(new DebuggerLocation.error(
- "Column '${colStr}' must be an integer"));
+ return new Future.value(
+ new DebuggerLocation.error("Column '${colStr}' must be an integer"));
}
if (scriptName != null) {
@@ -97,8 +95,8 @@
return new DebuggerLocation.file(scripts[0], line, col);
} else {
// TODO(turnidge): Allow the user to disambiguate.
- return
- new DebuggerLocation.error("Script '${scriptName}' is ambiguous");
+ return new DebuggerLocation.error(
+ "Script '${scriptName}' is ambiguous");
}
} else {
// No script provided. Default to top of stack for now.
@@ -113,9 +111,8 @@
}
}
- static Future<List<Script>> _lookupScript(Isolate isolate,
- String name,
- {bool allowPrefix: false}) {
+ static Future<List<Script>> _lookupScript(Isolate isolate, String name,
+ {bool allowPrefix: false}) {
var pending = [];
for (var lib in isolate.libraries) {
if (!lib.loaded) {
@@ -141,9 +138,8 @@
});
}
- static List<ServiceFunction> _lookupFunction(Isolate isolate,
- String name,
- { bool allowPrefix: false }) {
+ static List<ServiceFunction> _lookupFunction(Isolate isolate, String name,
+ {bool allowPrefix: false}) {
var matches = [];
for (var lib in isolate.libraries) {
assert(lib.loaded);
@@ -162,9 +158,8 @@
return matches;
}
- static Future<List<Class>> _lookupClass(Isolate isolate,
- String name,
- { bool allowPrefix: false }) async {
+ static Future<List<Class>> _lookupClass(Isolate isolate, String name,
+ {bool allowPrefix: false}) async {
if (isolate == null) {
return [];
}
@@ -207,8 +202,8 @@
// TODO(turnidge): This does not handle named functions which are
// inside of named functions, e.g. foo.bar.baz.
- static Future<DebuggerLocation> _parseFunction(Debugger debugger,
- Match match) {
+ static Future<DebuggerLocation> _parseFunction(
+ Debugger debugger, Match match) {
Isolate isolate = debugger.isolate;
var base = match.group(1);
var qualifier = match.group(2);
@@ -285,19 +280,19 @@
});
}
- static Future<List<String>> _completeFunction(Debugger debugger,
- Match match) {
+ static Future<List<String>> _completeFunction(
+ Debugger debugger, Match match) {
Isolate isolate = debugger.isolate;
var base = match.group(1);
var qualifier = match.group(2);
base = (base == null ? '' : base);
if (qualifier == null) {
- return _lookupClass(isolate, base, allowPrefix:true).then((classes) {
+ return _lookupClass(isolate, base, allowPrefix: true).then((classes) {
var completions = [];
// Complete top-level function names.
- var functions = _lookupFunction(isolate, base, allowPrefix:true);
+ var functions = _lookupFunction(isolate, base, allowPrefix: true);
var funcNames = functions.map((f) => f.name).toList();
funcNames.sort();
completions.addAll(funcNames);
@@ -310,7 +305,7 @@
return completions;
});
} else {
- return _lookupClass(isolate, base, allowPrefix:false).then((classes) {
+ return _lookupClass(isolate, base, allowPrefix: false).then((classes) {
var completions = [];
for (var cls in classes) {
for (var function in cls.functions) {
@@ -379,18 +374,17 @@
if (!scriptNameComplete) {
// The script name is incomplete. Complete it.
var scripts =
- await _lookupScript(debugger.isolate, scriptName, allowPrefix:true);
+ await _lookupScript(debugger.isolate, scriptName, allowPrefix: true);
List completions = [];
for (var script in scripts) {
completions.add(script.name + ':');
}
completions.sort();
return completions;
-
} else {
// The script name is complete. Look it up.
var scripts =
- await _lookupScript(debugger.isolate, scriptName, allowPrefix:false);
+ await _lookupScript(debugger.isolate, scriptName, allowPrefix: false);
if (scripts.isEmpty) {
return [];
}
@@ -400,8 +394,8 @@
// Complete the line.
var sharedPrefix = '${script.name}:';
List completions = [];
- var report = await script.isolate.getSourceReport(
- [Isolate.kPossibleBreakpointsReport], script);
+ var report = await script.isolate
+ .getSourceReport([Isolate.kPossibleBreakpointsReport], script);
Set<int> possibleBpts = getPossibleBreakpointLines(report, script);
for (var line in possibleBpts) {
var currentLineStr = line.toString();
@@ -411,7 +405,6 @@
}
}
return completions;
-
} else {
// Complete the column.
int lineNum = int.parse(lineStr);
diff --git a/runtime/observatory/lib/src/elements/allocation_profile.dart b/runtime/observatory/lib/src/elements/allocation_profile.dart
index f126544..d782f55 100644
--- a/runtime/observatory/lib/src/elements/allocation_profile.dart
+++ b/runtime/observatory/lib/src/elements/allocation_profile.dart
@@ -36,22 +36,19 @@
className,
}
-enum _SortingDirection {
- ascending,
- descending
-}
+enum _SortingDirection { ascending, descending }
-class AllocationProfileElement extends HtmlElement implements Renderable {
+class AllocationProfileElement extends HtmlElement implements Renderable {
static const tag = const Tag<AllocationProfileElement>('allocation-profile',
- dependencies: const [
- ClassRefElement.tag,
- NavTopMenuElement.tag,
- NavVMMenuElement.tag,
- NavIsolateMenuElement.tag,
- NavRefreshElement.tag,
- NavNotifyElement.tag,
- VirtualCollectionElement.tag
- ]);
+ dependencies: const [
+ ClassRefElement.tag,
+ NavTopMenuElement.tag,
+ NavVMMenuElement.tag,
+ NavIsolateMenuElement.tag,
+ NavRefreshElement.tag,
+ NavNotifyElement.tag,
+ VirtualCollectionElement.tag
+ ]);
RenderingScheduler<AllocationProfileElement> _r;
@@ -67,20 +64,20 @@
bool _autoRefresh = false;
bool _isCompacted = false;
StreamSubscription _gcSubscription;
- _SortingField _sortingField =
- _SortingField.className;
- _SortingDirection _sortingDirection =
- _SortingDirection.ascending;
+ _SortingField _sortingField = _SortingField.className;
+ _SortingDirection _sortingDirection = _SortingDirection.ascending;
M.VMRef get vm => _vm;
M.IsolateRef get isolate => _isolate;
M.NotificationRepository get notifications => _notifications;
- factory AllocationProfileElement(M.VM vm, M.IsolateRef isolate,
- M.EventRepository events,
- M.NotificationRepository notifications,
- M.AllocationProfileRepository repository,
- {RenderingQueue queue}) {
+ factory AllocationProfileElement(
+ M.VM vm,
+ M.IsolateRef isolate,
+ M.EventRepository events,
+ M.NotificationRepository notifications,
+ M.AllocationProfileRepository repository,
+ {RenderingQueue queue}) {
assert(vm != null);
assert(isolate != null);
assert(events != null);
@@ -125,16 +122,18 @@
new NavVMMenuElement(_vm, _events, queue: _r.queue),
new NavIsolateMenuElement(_isolate, _events, queue: _r.queue),
navMenu('allocation profile'),
- new NavRefreshElement(label: 'Download', disabled: _profile == null,
- queue: _r.queue)
- ..onRefresh.listen((_) => _downloadCSV()),
+ new NavRefreshElement(
+ label: 'Download',
+ disabled: _profile == null,
+ queue: _r.queue)..onRefresh.listen((_) => _downloadCSV()),
new NavRefreshElement(label: 'Reset Accumulator', queue: _r.queue)
..onRefresh.listen((_) => _refresh(reset: true)),
new NavRefreshElement(label: 'GC', queue: _r.queue)
..onRefresh.listen((_) => _refresh(gc: true)),
new NavRefreshElement(queue: _r.queue)
..onRefresh.listen((_) => _refresh()),
- new DivElement()..classes = ['nav-option']
+ new DivElement()
+ ..classes = ['nav-option']
..children = [
new CheckboxInputElement()
..id = 'allocation-profile-auto-refresh'
@@ -146,7 +145,8 @@
],
new NavNotifyElement(_notifications, queue: _r.queue)
]),
- new DivElement()..classes = ['content-centered-big']
+ new DivElement()
+ ..classes = ['content-centered-big']
..children = [
new HeadingElement.h2()..text = 'Allocation Profile',
new HRElement()
@@ -154,10 +154,9 @@
];
if (_profile == null) {
children.addAll([
- new DivElement()..classes = ['content-centered-big']
- ..children = [
- new HeadingElement.h2()..text = 'Loading...'
- ]
+ new DivElement()
+ ..classes = ['content-centered-big']
+ ..children = [new HeadingElement.h2()..text = 'Loading...']
]);
} else {
final newChartHost = new DivElement()..classes = ['host'];
@@ -165,64 +164,84 @@
final oldChartHost = new DivElement()..classes = ['host'];
final oldChartLegend = new DivElement()..classes = ['legend'];
children.addAll([
- new DivElement()..classes = ['content-centered-big']
- ..children = _isCompacted ? [] : [
- new DivElement()..classes = ['memberList']
- ..children = [
- new DivElement()..classes = ['memberItem']
- ..children = [
- new DivElement()..classes = ['memberName']
- ..text = 'last forced GC at',
- new DivElement()..classes = ['memberValue']
- ..text = _profile.lastServiceGC == null ? '---'
- : '${_profile.lastServiceGC}',
- ],
- new DivElement()..classes = ['memberItem']
- ..children = [
- new DivElement()..classes = ['memberName']
- ..text = 'last accumulator reset at',
- new DivElement()..classes = ['memberValue']
- ..text = _profile.lastAccumulatorReset == null ? '---'
- : '${_profile.lastAccumulatorReset}',
- ]
- ],
- new HRElement(),
- ],
- new DivElement()..classes = ['content-centered-big', 'compactable']
+ new DivElement()
+ ..classes = ['content-centered-big']
+ ..children = _isCompacted
+ ? []
+ : [
+ new DivElement()
+ ..classes = ['memberList']
+ ..children = [
+ new DivElement()
+ ..classes = ['memberItem']
+ ..children = [
+ new DivElement()
+ ..classes = ['memberName']
+ ..text = 'last forced GC at',
+ new DivElement()
+ ..classes = ['memberValue']
+ ..text = _profile.lastServiceGC == null
+ ? '---'
+ : '${_profile.lastServiceGC}',
+ ],
+ new DivElement()
+ ..classes = ['memberItem']
+ ..children = [
+ new DivElement()
+ ..classes = ['memberName']
+ ..text = 'last accumulator reset at',
+ new DivElement()
+ ..classes = ['memberValue']
+ ..text = _profile.lastAccumulatorReset == null
+ ? '---'
+ : '${_profile.lastAccumulatorReset}',
+ ]
+ ],
+ new HRElement(),
+ ],
+ new DivElement()
+ ..classes = ['content-centered-big', 'compactable']
..children = [
- new DivElement()..classes = ['heap-space', 'left']
+ new DivElement()
+ ..classes = ['heap-space', 'left']
..children = _isCompacted
- ? [
- new HeadingElement.h2()
- ..text = 'New Generation '
- '(${_usedCaption(_profile.newSpace)})',
- ]
- : [
- new HeadingElement.h2()..text = 'New Generation',
- new BRElement(),
- new DivElement()..classes = ['memberList']
- ..children = _createSpaceMembers(_profile.newSpace),
- new BRElement(),
- new DivElement()..classes = ['chart']
- ..children = [newChartLegend, newChartHost]
- ],
- new DivElement()..classes = ['heap-space', 'right']
+ ? [
+ new HeadingElement.h2()
+ ..text = 'New Generation '
+ '(${_usedCaption(_profile.newSpace)})',
+ ]
+ : [
+ new HeadingElement.h2()..text = 'New Generation',
+ new BRElement(),
+ new DivElement()
+ ..classes = ['memberList']
+ ..children = _createSpaceMembers(_profile.newSpace),
+ new BRElement(),
+ new DivElement()
+ ..classes = ['chart']
+ ..children = [newChartLegend, newChartHost]
+ ],
+ new DivElement()
+ ..classes = ['heap-space', 'right']
..children = _isCompacted
- ? [
- new HeadingElement.h2()
- ..text = '(${_usedCaption(_profile.newSpace)}) '
- 'Old Generation',
- ]
- : [
- new HeadingElement.h2()..text = 'Old Generation',
- new BRElement(),
- new DivElement()..classes = ['memberList']
- ..children = _createSpaceMembers(_profile.oldSpace),
- new BRElement(),
- new DivElement()..classes = ['chart']
- ..children = [oldChartLegend, oldChartHost]
- ],
- new ButtonElement()..classes = ['compact']
+ ? [
+ new HeadingElement.h2()
+ ..text = '(${_usedCaption(_profile.newSpace)}) '
+ 'Old Generation',
+ ]
+ : [
+ new HeadingElement.h2()..text = 'Old Generation',
+ new BRElement(),
+ new DivElement()
+ ..classes = ['memberList']
+ ..children = _createSpaceMembers(_profile.oldSpace),
+ new BRElement(),
+ new DivElement()
+ ..classes = ['chart']
+ ..children = [oldChartLegend, oldChartHost]
+ ],
+ new ButtonElement()
+ ..classes = ['compact']
..text = _isCompacted ? 'expand ▼' : 'compact ▲'
..onClick.listen((_) {
_isCompacted = !_isCompacted;
@@ -234,11 +253,10 @@
..classes = _isCompacted ? ['collection', 'expanded'] : ['collection']
..children = [
new VirtualCollectionElement(
- _createCollectionLine,
- _updateCollectionLine,
- createHeader: _createCollectionHeader,
- items: _profile.members.toList()..sort(_createSorter()),
- queue: _r.queue)
+ _createCollectionLine, _updateCollectionLine,
+ createHeader: _createCollectionHeader,
+ items: _profile.members.toList()..sort(_createSorter()),
+ queue: _r.queue)
]
]);
_renderGraph(newChartHost, newChartLegend, _profile.newSpace);
@@ -297,114 +315,122 @@
}
}
- static Element _createCollectionLine() =>
- new DivElement()
- ..classes = ['collection-item']
- ..children = [
- new SpanElement()..classes = ['bytes']
- ..text = '0B',
- new SpanElement()..classes = ['instances']
- ..text = '0',
- new SpanElement()..classes = ['bytes']
- ..text = '0B',
- new SpanElement()..classes = ['instances']
- ..text = '0',
- new SpanElement()..classes = ['bytes']
- ..text = '0B',
- new SpanElement()..classes = ['instances']
- ..text = '0',
- new SpanElement()..classes = ['bytes']
- ..text = '0B',
- new SpanElement()..classes = ['instances']
- ..text = '0',
- new SpanElement()..classes = ['bytes']
- ..text = '0B',
- new SpanElement()..classes = ['instances']
- ..text = '0',
- new SpanElement()..classes = ['bytes']
- ..text = '0B',
- new SpanElement()..classes = ['instances']
- ..text = '0',
- new SpanElement()..classes = ['name']
- ];
+ static Element _createCollectionLine() => new DivElement()
+ ..classes = ['collection-item']
+ ..children = [
+ new SpanElement()
+ ..classes = ['bytes']
+ ..text = '0B',
+ new SpanElement()
+ ..classes = ['instances']
+ ..text = '0',
+ new SpanElement()
+ ..classes = ['bytes']
+ ..text = '0B',
+ new SpanElement()
+ ..classes = ['instances']
+ ..text = '0',
+ new SpanElement()
+ ..classes = ['bytes']
+ ..text = '0B',
+ new SpanElement()
+ ..classes = ['instances']
+ ..text = '0',
+ new SpanElement()
+ ..classes = ['bytes']
+ ..text = '0B',
+ new SpanElement()
+ ..classes = ['instances']
+ ..text = '0',
+ new SpanElement()
+ ..classes = ['bytes']
+ ..text = '0B',
+ new SpanElement()
+ ..classes = ['instances']
+ ..text = '0',
+ new SpanElement()
+ ..classes = ['bytes']
+ ..text = '0B',
+ new SpanElement()
+ ..classes = ['instances']
+ ..text = '0',
+ new SpanElement()..classes = ['name']
+ ];
- Element _createCollectionHeader() =>
- new DivElement()
- ..children = [
- new DivElement()
- ..classes = ['collection-item']
- ..children = [
- new SpanElement()..classes = ['group']
- ..text = 'Accumulated',
- new SpanElement()..classes = ['group']
- ..text = 'Current',
- new SpanElement()..classes = ['group']
- ..text = '(NEW) Accumulated',
- new SpanElement()..classes = ['group']
- ..text = '(NEW) Current',
- new SpanElement()..classes = ['group']
- ..text = '(OLD) Accumulated',
- new SpanElement()..classes = ['group']
- ..text = '(OLD) Current',
- ],
- new DivElement()
- ..classes = ['collection-item']
- ..children = [
- _createHeaderButton(const ['bytes'], 'Size',
- _SortingField.accumulatedSize,
- _SortingDirection.descending),
- _createHeaderButton(const ['instances'], 'Instances',
- _SortingField.accumulatedInstances,
- _SortingDirection.descending),
- _createHeaderButton(const ['bytes'], 'Size',
- _SortingField.currentSize,
- _SortingDirection.descending),
- _createHeaderButton(const ['instances'], 'Instances',
- _SortingField.currentInstances,
- _SortingDirection.descending),
- _createHeaderButton(const ['bytes'], 'Size',
- _SortingField.newAccumulatedSize,
- _SortingDirection.descending),
- _createHeaderButton(const ['instances'], 'Instances',
- _SortingField.newAccumulatedInstances,
- _SortingDirection.descending),
- _createHeaderButton(const ['bytes'], 'Size',
- _SortingField.newCurrentSize,
- _SortingDirection.descending),
- _createHeaderButton(const ['instances'], 'Instances',
- _SortingField.newCurrentInstances,
- _SortingDirection.descending),
- _createHeaderButton(const ['bytes'], 'Size',
- _SortingField.oldAccumulatedSize,
- _SortingDirection.descending),
- _createHeaderButton(const ['instances'], 'Instances',
- _SortingField.oldAccumulatedInstances,
- _SortingDirection.descending),
- _createHeaderButton(const ['bytes'], 'Size',
- _SortingField.oldCurrentSize,
- _SortingDirection.descending),
- _createHeaderButton(const ['instances'], 'Instances',
- _SortingField.oldCurrentInstances,
- _SortingDirection.descending),
- _createHeaderButton(const ['name'], 'Class',
- _SortingField.className,
- _SortingDirection.ascending)
- ],
- ];
+ Element _createCollectionHeader() => new DivElement()
+ ..children = [
+ new DivElement()
+ ..classes = ['collection-item']
+ ..children = [
+ new SpanElement()
+ ..classes = ['group']
+ ..text = 'Accumulated',
+ new SpanElement()
+ ..classes = ['group']
+ ..text = 'Current',
+ new SpanElement()
+ ..classes = ['group']
+ ..text = '(NEW) Accumulated',
+ new SpanElement()
+ ..classes = ['group']
+ ..text = '(NEW) Current',
+ new SpanElement()
+ ..classes = ['group']
+ ..text = '(OLD) Accumulated',
+ new SpanElement()
+ ..classes = ['group']
+ ..text = '(OLD) Current',
+ ],
+ new DivElement()
+ ..classes = ['collection-item']
+ ..children = [
+ _createHeaderButton(const ['bytes'], 'Size',
+ _SortingField.accumulatedSize, _SortingDirection.descending),
+ _createHeaderButton(const ['instances'], 'Instances',
+ _SortingField.accumulatedInstances, _SortingDirection.descending),
+ _createHeaderButton(const ['bytes'], 'Size',
+ _SortingField.currentSize, _SortingDirection.descending),
+ _createHeaderButton(const ['instances'], 'Instances',
+ _SortingField.currentInstances, _SortingDirection.descending),
+ _createHeaderButton(const ['bytes'], 'Size',
+ _SortingField.newAccumulatedSize, _SortingDirection.descending),
+ _createHeaderButton(
+ const ['instances'],
+ 'Instances',
+ _SortingField.newAccumulatedInstances,
+ _SortingDirection.descending),
+ _createHeaderButton(const ['bytes'], 'Size',
+ _SortingField.newCurrentSize, _SortingDirection.descending),
+ _createHeaderButton(const ['instances'], 'Instances',
+ _SortingField.newCurrentInstances, _SortingDirection.descending),
+ _createHeaderButton(const ['bytes'], 'Size',
+ _SortingField.oldAccumulatedSize, _SortingDirection.descending),
+ _createHeaderButton(
+ const ['instances'],
+ 'Instances',
+ _SortingField.oldAccumulatedInstances,
+ _SortingDirection.descending),
+ _createHeaderButton(const ['bytes'], 'Size',
+ _SortingField.oldCurrentSize, _SortingDirection.descending),
+ _createHeaderButton(const ['instances'], 'Instances',
+ _SortingField.oldCurrentInstances, _SortingDirection.descending),
+ _createHeaderButton(const ['name'], 'Class', _SortingField.className,
+ _SortingDirection.ascending)
+ ],
+ ];
- ButtonElement _createHeaderButton(List<String> classes,
- String text,
- _SortingField field,
- _SortingDirection direction) =>
- new ButtonElement()..classes = classes
- ..text = _sortingField != field ? text :
- _sortingDirection == _SortingDirection.ascending
- ? '$text▼' : '$text▲'
- ..onClick.listen((_) => _setSorting(field, direction));
+ ButtonElement _createHeaderButton(List<String> classes, String text,
+ _SortingField field, _SortingDirection direction) =>
+ new ButtonElement()
+ ..classes = classes
+ ..text = _sortingField != field
+ ? text
+ : _sortingDirection == _SortingDirection.ascending
+ ? '$text▼'
+ : '$text▲'
+ ..onClick.listen((_) => _setSorting(field, direction));
-
- void _setSorting(_SortingField field,
- _SortingDirection defaultDirection) {
+ void _setSorting(_SortingField field, _SortingDirection defaultDirection) {
if (_sortingField == field) {
switch (_sortingDirection) {
case _SortingDirection.descending:
@@ -421,8 +447,7 @@
_r.dirty();
}
- void _updateCollectionLine(Element e, M.ClassHeapStats item,
- index) {
+ void _updateCollectionLine(Element e, M.ClassHeapStats item, index) {
e.children[0].text = Utils.formatSize(_getAccumulatedSize(item));
e.children[1].text = '${_getAccumulatedInstances(item)}';
e.children[2].text = Utils.formatSize(_getCurrentSize(item));
@@ -436,93 +461,110 @@
e.children[10].text = Utils.formatSize(_getOldCurrentSize(item));
e.children[11].text = '${_getOldCurrentInstances(item)}';
e.children[12] = new ClassRefElement(_isolate, item.clazz, queue: _r.queue)
- ..classes = ['name'];
+ ..classes = ['name'];
}
static String _usedCaption(M.HeapSpace space) =>
- '${Utils.formatSize(space.used)}'
- ' of '
- '${Utils.formatSize(space.capacity)}';
+ '${Utils.formatSize(space.used)}'
+ ' of '
+ '${Utils.formatSize(space.capacity)}';
static List<Element> _createSpaceMembers(M.HeapSpace space) {
final used = _usedCaption(space);
final ext = '${Utils.formatSize(space.external)}';
final collections = '${space.collections}';
final avgCollectionTime =
- '${Utils.formatDurationInMilliseconds(space.avgCollectionTime)} ms';
+ '${Utils.formatDurationInMilliseconds(space.avgCollectionTime)} ms';
final totalCollectionTime =
- '${Utils.formatDurationInSeconds(space.totalCollectionTime)} secs';
+ '${Utils.formatDurationInSeconds(space.totalCollectionTime)} secs';
final avgCollectionPeriod =
- '${Utils.formatDurationInMilliseconds(space.avgCollectionPeriod)} ms';
+ '${Utils.formatDurationInMilliseconds(space.avgCollectionPeriod)} ms';
return [
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'used',
- new DivElement()..classes = ['memberValue']
+ new DivElement()
+ ..classes = ['memberValue']
..text = used
],
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'external',
- new DivElement()..classes = ['memberValue']
+ new DivElement()
+ ..classes = ['memberValue']
..text = ext
],
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
- ..text = 'collections',
- new DivElement()..classes = ['memberValue']
+ new DivElement()
+ ..classes = ['memberName']
+ ..text = 'collections',
+ new DivElement()
+ ..classes = ['memberValue']
..text = collections
],
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'average collection time',
- new DivElement()..classes = ['memberValue']
+ new DivElement()
+ ..classes = ['memberValue']
..text = avgCollectionTime
],
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'cumulative collection time',
- new DivElement()..classes = ['memberValue']
+ new DivElement()
+ ..classes = ['memberValue']
..text = totalCollectionTime
],
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'average time between collections',
- new DivElement()..classes = ['memberValue']
+ new DivElement()
+ ..classes = ['memberValue']
..text = avgCollectionPeriod
]
];
}
static final _columns = [
- new ChartColumnSpec(label: 'Type', type: ChartColumnSpec.TYPE_STRING),
- new ChartColumnSpec(label: 'Size', formatter: (v) => v.toString())
+ new ChartColumnSpec(label: 'Type', type: ChartColumnSpec.TYPE_STRING),
+ new ChartColumnSpec(label: 'Size', formatter: (v) => v.toString())
];
static void _renderGraph(Element host, Element legend, M.HeapSpace space) {
- final series = [new ChartSeries("Work", [1], new PieChartRenderer(
- sortDataByValue: false
- ))];
+ final series = [
+ new ChartSeries("Work", [1], new PieChartRenderer(sortDataByValue: false))
+ ];
final rect = host.getBoundingClientRect();
final minSize = new Rect.size(rect.width, rect.height);
final config = new ChartConfig(series, [0])
- ..minimumSize = minSize
- ..legend = new ChartLegend(legend, showValues: true);
+ ..minimumSize = minSize
+ ..legend = new ChartLegend(legend, showValues: true);
final data = new ChartData(_columns, [
['Used', space.used],
['Free', space.capacity - space.used],
['External', space.external]
]);
- new LayoutArea(host, data, config, state: new ChartState(),
- autoUpdate: true)
- ..draw();
+ new LayoutArea(host, data, config,
+ state: new ChartState(), autoUpdate: true)..draw();
}
Future _refresh({bool gc: false, bool reset: false}) async {
@@ -534,25 +576,29 @@
void _downloadCSV() {
assert(_profile != null);
- final header = ['"Accumulator Size"',
- '"Accumulator Instances"',
- '"Current Size"',
- '"Current Instances"',
- '"(NEW) Accumulator Size"',
- '"(NEW) Accumulator Instances"',
- '"(NEW) Current Size"',
- '"(NEW) Current Instances"',
- '"(OLD) Accumulator Size"',
- '"(OLD) Accumulator Instances"',
- '"(OLD) Current Size"',
- '"(OLD) Current Instances"',
- 'Class'
- ].join(';') + '\n';
+ final header = [
+ '"Accumulator Size"',
+ '"Accumulator Instances"',
+ '"Current Size"',
+ '"Current Instances"',
+ '"(NEW) Accumulator Size"',
+ '"(NEW) Accumulator Instances"',
+ '"(NEW) Current Size"',
+ '"(NEW) Current Instances"',
+ '"(OLD) Accumulator Size"',
+ '"(OLD) Accumulator Instances"',
+ '"(OLD) Current Size"',
+ '"(OLD) Current Instances"',
+ 'Class'
+ ].join(',') +
+ '\n';
AnchorElement tl = document.createElement('a');
- tl..attributes['href'] = 'data:text/plain;charset=utf-8,' +
- Uri.encodeComponent(header +
- (_profile.members.toList()..sort(_createSorter()))
- .map(_csvOut).join('\n'))
+ tl
+ ..attributes['href'] = 'data:text/plain;charset=utf-8,' +
+ Uri.encodeComponent(header +
+ (_profile.members.toList()..sort(_createSorter()))
+ .map(_csvOut)
+ .join('\n'))
..attributes['download'] = 'heap-profile.csv'
..click();
}
@@ -572,7 +618,7 @@
_getOldCurrentSize(s),
_getOldCurrentInstances(s),
s.clazz.name
- ].join(';');
+ ].join(',');
}
static int _getAccumulatedSize(M.ClassHeapStats s) =>
@@ -587,16 +633,14 @@
s.newSpace.accumulated.bytes;
static int _getNewAccumulatedInstances(M.ClassHeapStats s) =>
s.newSpace.accumulated.instances;
- static int _getNewCurrentSize(M.ClassHeapStats s) =>
- s.newSpace.current.bytes;
+ static int _getNewCurrentSize(M.ClassHeapStats s) => s.newSpace.current.bytes;
static int _getNewCurrentInstances(M.ClassHeapStats s) =>
s.newSpace.current.instances;
static int _getOldAccumulatedSize(M.ClassHeapStats s) =>
s.oldSpace.accumulated.bytes;
static int _getOldAccumulatedInstances(M.ClassHeapStats s) =>
s.oldSpace.accumulated.instances;
- static int _getOldCurrentSize(M.ClassHeapStats s) =>
- s.oldSpace.current.bytes;
+ static int _getOldCurrentSize(M.ClassHeapStats s) => s.oldSpace.current.bytes;
static int _getOldCurrentInstances(M.ClassHeapStats s) =>
s.oldSpace.current.instances;
}
diff --git a/runtime/observatory/lib/src/elements/class_allocation_profile.dart b/runtime/observatory/lib/src/elements/class_allocation_profile.dart
index adf4387..88987ae 100644
--- a/runtime/observatory/lib/src/elements/class_allocation_profile.dart
+++ b/runtime/observatory/lib/src/elements/class_allocation_profile.dart
@@ -13,17 +13,17 @@
class ClassAllocationProfileElement extends HtmlElement implements Renderable {
static const tag = const Tag<ClassAllocationProfileElement>(
- 'class-allocation-profile',
- dependencies: const [
- SampleBufferControlElement.tag,
- StackTraceTreeConfigElement.tag,
- CpuProfileVirtualTreeElement.tag,
- ]);
+ 'class-allocation-profile',
+ dependencies: const [
+ SampleBufferControlElement.tag,
+ StackTraceTreeConfigElement.tag,
+ CpuProfileVirtualTreeElement.tag,
+ ]);
RenderingScheduler<ClassAllocationProfileElement> _r;
Stream<RenderedEvent<ClassAllocationProfileElement>> get onRendered =>
- _r.onRendered;
+ _r.onRendered;
M.IsolateRef _isolate;
M.Class _cls;
@@ -34,13 +34,12 @@
ProfileTreeMode _mode = ProfileTreeMode.function;
M.ProfileTreeDirection _direction = M.ProfileTreeDirection.exclusive;
-
-
M.IsolateRef get isolate => _isolate;
M.Class get cls => _cls;
factory ClassAllocationProfileElement(M.IsolateRef isolate, M.Class cls,
- M.ClassSampleProfileRepository profiles, {RenderingQueue queue}) {
+ M.ClassSampleProfileRepository profiles,
+ {RenderingQueue queue}) {
assert(isolate != null);
assert(cls != null);
assert(profiles != null);
@@ -85,14 +84,17 @@
CpuProfileVirtualTreeElement tree;
content.addAll([
new BRElement(),
- new StackTraceTreeConfigElement(mode: _mode, direction: _direction,
- showFilter: false, queue: _r.queue)
- ..onModeChange.listen((e) {
- _mode = tree.mode = e.element.mode;
- })
- ..onDirectionChange.listen((e) {
- _direction = tree.direction = e.element.direction;
- }),
+ new StackTraceTreeConfigElement(
+ mode: _mode,
+ direction: _direction,
+ showFilter: false,
+ queue: _r.queue)
+ ..onModeChange.listen((e) {
+ _mode = tree.mode = e.element.mode;
+ })
+ ..onDirectionChange.listen((e) {
+ _direction = tree.direction = e.element.direction;
+ }),
new BRElement(),
tree = new CpuProfileVirtualTreeElement(_isolate, _progress.profile,
queue: _r.queue)
diff --git a/runtime/observatory/lib/src/elements/class_instances.dart b/runtime/observatory/lib/src/elements/class_instances.dart
index 4b29032..c5cba51 100644
--- a/runtime/observatory/lib/src/elements/class_instances.dart
+++ b/runtime/observatory/lib/src/elements/class_instances.dart
@@ -16,13 +16,13 @@
import 'package:observatory/utils.dart';
class ClassInstancesElement extends HtmlElement implements Renderable {
- static const tag = const Tag<ClassInstancesElement>('class-instances',
- dependencies: const [
- ClassRefElement.tag,
- InboundReferencesElement.tag,
- RetainingPathElement.tag,
- TopRetainingInstancesElement.tag
- ]);
+ static const tag =
+ const Tag<ClassInstancesElement>('class-instances', dependencies: const [
+ ClassRefElement.tag,
+ InboundReferencesElement.tag,
+ RetainingPathElement.tag,
+ TopRetainingInstancesElement.tag
+ ]);
RenderingScheduler<ClassInstancesElement> _r;
@@ -43,7 +43,9 @@
M.IsolateRef get isolate => _isolate;
M.Class get cls => _cls;
- factory ClassInstancesElement(M.IsolateRef isolate, M.Class cls,
+ factory ClassInstancesElement(
+ M.IsolateRef isolate,
+ M.Class cls,
M.RetainedSizeRepository retainedSizes,
M.ReachableSizeRepository reachableSizes,
M.StronglyReachableInstancesRepository stronglyReachableInstances,
@@ -88,54 +90,74 @@
TopRetainingInstancesElement _topRetainig;
void render() {
- _strong = _strong ?? new StronglyReachableInstancesElement(_isolate,
- _cls, _stronglyReachableInstances, _instances, queue: _r.queue);
- _topRetainig = _topRetainig ?? new TopRetainingInstancesElement(_isolate,
- _cls, _topRetainingInstances, _instances, queue: _r.queue);
- final instanceCount = _cls.newSpace.current.instances +
- _cls.oldSpace.current.instances;
- final size = Utils.formatSize(_cls.newSpace.current.bytes +
- _cls.oldSpace.current.bytes);
+ _strong = _strong ??
+ new StronglyReachableInstancesElement(
+ _isolate, _cls, _stronglyReachableInstances, _instances,
+ queue: _r.queue);
+ _topRetainig = _topRetainig ??
+ new TopRetainingInstancesElement(
+ _isolate, _cls, _topRetainingInstances, _instances,
+ queue: _r.queue);
+ final instanceCount =
+ _cls.newSpace.current.instances + _cls.oldSpace.current.instances;
+ final size = Utils
+ .formatSize(_cls.newSpace.current.bytes + _cls.oldSpace.current.bytes);
children = [
- new DivElement()..classes = ['memberList']
+ new DivElement()
+ ..classes = ['memberList']
..children = [
- new DivElement()..classes = const ['memberItem']
+ new DivElement()
+ ..classes = const ['memberItem']
..children = [
- new DivElement()..classes = const ['memberName']
+ new DivElement()
+ ..classes = const ['memberName']
..text = 'currently allocated',
- new DivElement()..classes = const ['memberValue']
+ new DivElement()
+ ..classes = const ['memberValue']
..text = 'count ${instanceCount} (shallow size ${size})'
],
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'strongly reachable ',
- new DivElement()..classes = ['memberValue']
+ new DivElement()
+ ..classes = ['memberValue']
..children = [_strong]
],
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..title = 'Space reachable from this object, '
- 'excluding class references'
+ 'excluding class references'
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'Reachable size ',
- new DivElement()..classes = ['memberValue']
+ new DivElement()
+ ..classes = ['memberValue']
..children = _createReachableSizeValue()
],
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..title = 'Space that would be reclaimed if references to this '
- 'object were replaced with null'
+ 'object were replaced with null'
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'Retained size ',
- new DivElement()..classes = ['memberValue']
+ new DivElement()
+ ..classes = ['memberValue']
..children = _createRetainedSizeValue()
],
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'toplist by retained memory ',
- new DivElement()..classes = ['memberValue']
+ new DivElement()
+ ..classes = ['memberValue']
..children = [_topRetainig]
]
]
@@ -146,29 +168,26 @@
final content = <Element>[];
if (_reachableSize != null) {
if (_reachableSize.isSentinel) {
- content.add(
- new SentinelValueElement(_reachableSize.asSentinel, queue: _r.queue)
- );
+ content.add(new SentinelValueElement(_reachableSize.asSentinel,
+ queue: _r.queue));
} else {
- content.add(
- new SpanElement()..text = Utils.formatSize(int.parse(
- _reachableSize.asValue.valueAsString))
- );
+ content.add(new SpanElement()
+ ..text = Utils
+ .formatSize(int.parse(_reachableSize.asValue.valueAsString)));
}
} else {
- content.add(
- new SpanElement()..text = '...'
- );
+ content.add(new SpanElement()..text = '...');
}
- final button = new ButtonElement()..classes = ['reachable_size']
+ final button = new ButtonElement()
+ ..classes = ['reachable_size']
..disabled = _loadingReachableBytes
..text = '↺';
button.onClick.listen((_) async {
- button.disabled = true;
- _loadingReachableBytes = true;
- _reachableSize = await _reachableSizes.get(_isolate, _cls.id);
- _r.dirty();
- });
+ button.disabled = true;
+ _loadingReachableBytes = true;
+ _reachableSize = await _reachableSizes.get(_isolate, _cls.id);
+ _r.dirty();
+ });
content.add(button);
return content;
}
@@ -177,29 +196,26 @@
final content = <Element>[];
if (_retainedSize != null) {
if (_retainedSize.isSentinel) {
- content.add(
- new SentinelValueElement(_retainedSize.asSentinel, queue: _r.queue)
- );
+ content.add(new SentinelValueElement(_retainedSize.asSentinel,
+ queue: _r.queue));
} else {
- content.add(
- new SpanElement()..text = Utils.formatSize(int.parse(
- _retainedSize.asValue.valueAsString))
- );
+ content.add(new SpanElement()
+ ..text =
+ Utils.formatSize(int.parse(_retainedSize.asValue.valueAsString)));
}
} else {
- content.add(
- new SpanElement()..text = '...'
- );
+ content.add(new SpanElement()..text = '...');
}
- final button = new ButtonElement()..classes = ['retained_size']
+ final button = new ButtonElement()
+ ..classes = ['retained_size']
..disabled = _loadingRetainedBytes
..text = '↺';
button.onClick.listen((_) async {
- button.disabled = true;
- _loadingRetainedBytes = true;
- _retainedSize = await _retainedSizes.get(_isolate, _cls.id);
- _r.dirty();
- });
+ button.disabled = true;
+ _loadingRetainedBytes = true;
+ _retainedSize = await _retainedSizes.get(_isolate, _cls.id);
+ _r.dirty();
+ });
content.add(button);
return content;
}
diff --git a/runtime/observatory/lib/src/elements/class_tree.dart b/runtime/observatory/lib/src/elements/class_tree.dart
index 5fb3328..d9d2814 100644
--- a/runtime/observatory/lib/src/elements/class_tree.dart
+++ b/runtime/observatory/lib/src/elements/class_tree.dart
@@ -18,15 +18,16 @@
import 'package:observatory/src/elements/nav/top_menu.dart';
import 'package:observatory/src/elements/nav/vm_menu.dart';
-
-class ClassTreeElement extends HtmlElement implements Renderable{
- static const tag = const Tag<ClassTreeElement>('class-tree',
- dependencies: const [ClassRefElement.tag,
- NavIsolateMenuElement.tag,
- NavNotifyElement.tag,
- NavTopMenuElement.tag,
- NavVMMenuElement.tag,
- VirtualTreeElement.tag]);
+class ClassTreeElement extends HtmlElement implements Renderable {
+ static const tag =
+ const Tag<ClassTreeElement>('class-tree', dependencies: const [
+ ClassRefElement.tag,
+ NavIsolateMenuElement.tag,
+ NavNotifyElement.tag,
+ NavTopMenuElement.tag,
+ NavVMMenuElement.tag,
+ VirtualTreeElement.tag
+ ]);
RenderingScheduler _r;
@@ -41,11 +42,13 @@
final _subclasses = <String, Iterable<M.Class>>{};
final _mixins = <String, List<M.Instance>>{};
- factory ClassTreeElement(M.VMRef vm, M.IsolateRef isolate,
- M.EventRepository events,
- M.NotificationRepository notifications,
- M.ClassRepository classes,
- {RenderingQueue queue}) {
+ factory ClassTreeElement(
+ M.VMRef vm,
+ M.IsolateRef isolate,
+ M.EventRepository events,
+ M.NotificationRepository notifications,
+ M.ClassRepository classes,
+ {RenderingQueue queue}) {
assert(vm != null);
assert(isolate != null);
assert(events != null);
@@ -92,16 +95,18 @@
..classes = ['content-centered']
..children = [
new HeadingElement.h1()..text = 'Class Hierarchy',
- new BRElement(), new HRElement(),
- _object == null ? (new HeadingElement.h2()..text = 'Loading...')
- : _createTree()
+ new BRElement(),
+ new HRElement(),
+ _object == null
+ ? (new HeadingElement.h2()..text = 'Loading...')
+ : _createTree()
]
];
}
Element _createTree() {
_tree = new VirtualTreeElement(_create, _update, _children,
- items: [_object], queue: _r.queue);
+ items: [_object], queue: _r.queue);
_tree.expand(_object, autoExpandSingleChildNodes: true);
return _tree;
}
@@ -116,10 +121,9 @@
Future<M.Class> _register(M.Class cls) async {
_subclasses[cls.id] = await Future.wait(
- (await Future.wait(cls.subclasses.map(_getActualChildrens)))
- .expand((f) => f)
- .map(_register)
- );
+ (await Future.wait(cls.subclasses.map(_getActualChildrens)))
+ .expand((f) => f)
+ .map(_register));
return cls;
}
@@ -132,20 +136,22 @@
return [cls];
}
return (await Future.wait(cls.subclasses.map(_getActualChildrens)))
- .expand((f) => f)
- ..forEach((subcls) {
- _mixins[subcls.id] = (_mixins[subcls.id] ?? [])..add(cls.mixin);
- });
+ .expand((f) => f)
+ ..forEach((subcls) {
+ _mixins[subcls.id] = (_mixins[subcls.id] ?? [])..add(cls.mixin);
+ });
}
static Element _create(toggle) {
- return new DivElement()..classes = ['class-tree-item']
- ..children = [
- new SpanElement()..classes = ['lines'],
- new ButtonElement()..classes = ['expander']
- ..onClick.listen((_) => toggle(autoToggleSingleChildNodes: true)),
- new SpanElement()..classes = ['name']
- ];
+ return new DivElement()
+ ..classes = ['class-tree-item']
+ ..children = [
+ new SpanElement()..classes = ['lines'],
+ new ButtonElement()
+ ..classes = ['expander']
+ ..onClick.listen((_) => toggle(autoToggleSingleChildNodes: true)),
+ new SpanElement()..classes = ['name']
+ ];
}
void _update(HtmlElement el, M.Class cls, int index) {
@@ -164,12 +170,15 @@
}
List<Element> _createMixins(List<M.Instance> types) {
- final children = types.expand((type) => [
- new SpanElement()..text = ', ',
- type.typeClass == null
- ? (new SpanElement()..text = type.name.split('<').first)
- : new ClassRefElement(_isolate, type.typeClass, queue: _r.queue)
- ]).toList();
+ final children = types
+ .expand((type) => [
+ new SpanElement()..text = ', ',
+ type.typeClass == null
+ ? (new SpanElement()..text = type.name.split('<').first)
+ : new ClassRefElement(_isolate, type.typeClass,
+ queue: _r.queue)
+ ])
+ .toList();
children.first.text = ' with ';
return children;
}
diff --git a/runtime/observatory/lib/src/elements/class_view.dart b/runtime/observatory/lib/src/elements/class_view.dart
index c87bee1..f649a31 100644
--- a/runtime/observatory/lib/src/elements/class_view.dart
+++ b/runtime/observatory/lib/src/elements/class_view.dart
@@ -33,28 +33,28 @@
import 'package:observatory/src/elements/view_footer.dart';
class ClassViewElement extends HtmlElement implements Renderable {
- static const tag = const Tag<ClassViewElement>('class-view',
- dependencies: const [
- ClassInstancesElement.tag,
- ClassRefElement.tag,
- CurlyBlockElement.tag,
- ErrorRefElement.tag,
- EvalBoxElement.tag,
- FieldRefElement.tag,
- FunctionRefElement.tag,
- InstanceRefElement.tag,
- LibraryRefElement.tag,
- NavClassMenuElement.tag,
- NavTopMenuElement.tag,
- NavVMMenuElement.tag,
- NavIsolateMenuElement.tag,
- NavRefreshElement.tag,
- NavNotifyElement.tag,
- ObjectCommonElement.tag,
- SourceInsetElement.tag,
- SourceLinkElement.tag,
- ViewFooterElement.tag
- ]);
+ static const tag =
+ const Tag<ClassViewElement>('class-view', dependencies: const [
+ ClassInstancesElement.tag,
+ ClassRefElement.tag,
+ CurlyBlockElement.tag,
+ ErrorRefElement.tag,
+ EvalBoxElement.tag,
+ FieldRefElement.tag,
+ FunctionRefElement.tag,
+ InstanceRefElement.tag,
+ LibraryRefElement.tag,
+ NavClassMenuElement.tag,
+ NavTopMenuElement.tag,
+ NavVMMenuElement.tag,
+ NavIsolateMenuElement.tag,
+ NavRefreshElement.tag,
+ NavNotifyElement.tag,
+ ObjectCommonElement.tag,
+ SourceInsetElement.tag,
+ SourceLinkElement.tag,
+ ViewFooterElement.tag
+ ]);
RenderingScheduler<ClassViewElement> _r;
@@ -79,28 +79,30 @@
M.ClassSampleProfileRepository _profiles;
Iterable<M.Field> _classFields;
-
M.VMRef get vm => _vm;
M.IsolateRef get isolate => _isolate;
M.NotificationRepository get notifications => _notifications;
M.Class get cls => _cls;
- factory ClassViewElement(M.VM vm, M.IsolateRef isolate, M.Class cls,
- M.EventRepository events,
- M.NotificationRepository notifications,
- M.ClassRepository classes,
- M.RetainedSizeRepository retainedSizes,
- M.ReachableSizeRepository reachableSizes,
- M.InboundReferencesRepository references,
- M.RetainingPathRepository retainingPaths,
- M.FieldRepository fields,
- M.ScriptRepository scripts,
- M.InstanceRepository instances,
- M.EvalRepository eval,
- M.StronglyReachableInstancesRepository stronglyReachable,
- M.TopRetainingInstancesRepository topRetained,
- M.ClassSampleProfileRepository profiles,
- {RenderingQueue queue}) {
+ factory ClassViewElement(
+ M.VM vm,
+ M.IsolateRef isolate,
+ M.Class cls,
+ M.EventRepository events,
+ M.NotificationRepository notifications,
+ M.ClassRepository classes,
+ M.RetainedSizeRepository retainedSizes,
+ M.ReachableSizeRepository reachableSizes,
+ M.InboundReferencesRepository references,
+ M.RetainingPathRepository retainingPaths,
+ M.FieldRepository fields,
+ M.ScriptRepository scripts,
+ M.InstanceRepository instances,
+ M.EvalRepository eval,
+ M.StronglyReachableInstancesRepository stronglyReachable,
+ M.TopRetainingInstancesRepository topRetained,
+ M.ClassSampleProfileRepository profiles,
+ {RenderingQueue queue}) {
assert(vm != null);
assert(isolate != null);
assert(events != null);
@@ -161,12 +163,20 @@
bool _loadProfile = false;
void render() {
- _common = _common ?? new ObjectCommonElement(_isolate, _cls, _retainedSizes,
- _reachableSizes, _references, _retainingPaths, _instances,
- queue: _r.queue);
- _classInstances = _classInstances ?? new ClassInstancesElement(_isolate,
- _cls, _retainedSizes, _reachableSizes, _stronglyReachableInstances,
- _topRetainedInstances, _instances, queue: _r.queue);
+ _common = _common ??
+ new ObjectCommonElement(_isolate, _cls, _retainedSizes, _reachableSizes,
+ _references, _retainingPaths, _instances,
+ queue: _r.queue);
+ _classInstances = _classInstances ??
+ new ClassInstancesElement(
+ _isolate,
+ _cls,
+ _retainedSizes,
+ _reachableSizes,
+ _stronglyReachableInstances,
+ _topRetainedInstances,
+ _instances,
+ queue: _r.queue);
var header = '';
if (_cls.isAbstract) {
header += 'abstract ';
@@ -180,91 +190,102 @@
new NavVMMenuElement(_vm, _events, queue: _r.queue),
new NavIsolateMenuElement(_isolate, _events, queue: _r.queue),
new NavClassMenuElement(_isolate, _cls, queue: _r.queue),
- new NavRefreshElement(label: 'Refresh Allocation Profile',
- queue: _r.queue)
- ..onRefresh.listen((e) {
- e.element.disabled = true;
- _loadProfile = true;
- _r.dirty();
- }),
+ new NavRefreshElement(
+ label: 'Refresh Allocation Profile', queue: _r.queue)
+ ..onRefresh.listen((e) {
+ e.element.disabled = true;
+ _loadProfile = true;
+ _r.dirty();
+ }),
new NavRefreshElement(queue: _r.queue)
- ..onRefresh.listen((e) {
- e.element.disabled = true;
- _common = null;
- _classInstances = null;
- _fieldsExpanded = null;
- _functionsExpanded = null;
- _refresh();
- }),
+ ..onRefresh.listen((e) {
+ e.element.disabled = true;
+ _common = null;
+ _classInstances = null;
+ _fieldsExpanded = null;
+ _functionsExpanded = null;
+ _refresh();
+ }),
new NavNotifyElement(_notifications, queue: _r.queue)
]),
- new DivElement()..classes = ['content-centered-big']
+ new DivElement()
+ ..classes = ['content-centered-big']
..children = [
new HeadingElement.h2()..text = '$header class ${_cls.name}',
new HRElement(),
_common,
new BRElement(),
- new DivElement()..classes = ['memberList']
+ new DivElement()
+ ..classes = ['memberList']
..children = _createMembers(),
new DivElement()
..children = _cls.error == null
- ? const []
- : [
- new HRElement(),
- new ErrorRefElement(_cls.error, queue: _r.queue)
- ],
+ ? const []
+ : [
+ new HRElement(),
+ new ErrorRefElement(_cls.error, queue: _r.queue)
+ ],
new HRElement(),
new EvalBoxElement(_isolate, _cls, _instances, _eval,
- queue: _r.queue),
+ queue: _r.queue),
new HRElement(),
new HeadingElement.h2()..text = 'Fields & Functions',
- new DivElement()..classes = ['memberList']
+ new DivElement()
+ ..classes = ['memberList']
..children = _createElements(),
new HRElement(),
new HeadingElement.h2()..text = 'Instances',
new DivElement()
- ..children = _cls.hasAllocations
- ? [_classInstances]
- : const [],
+ ..children = _cls.hasAllocations ? [_classInstances] : const [],
new HRElement(),
new HeadingElement.h2()..text = 'Allocations',
- new DivElement()..classes = ['memberList']
+ new DivElement()
+ ..classes = ['memberList']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'Tracing allocations? ',
- new DivElement()..classes = ['memberValue']
+ new DivElement()
+ ..classes = ['memberValue']
..children = _cls.traceAllocations
- ? [
- new SpanElement()..text = 'Yes ',
- new ButtonElement()..text = 'disable'
- ..onClick.listen((e) async {
- e.target.disabled = true;
- await _profiles.disable(_isolate, _cls);
- _loadProfile = true;
- _refresh();
- })
- ]
- : [
- new SpanElement()..text = 'No ',
- new ButtonElement()..text = 'enable'
- ..onClick.listen((e) async {
- e.target.disabled = true;
- await _profiles.enable(_isolate, _cls);
- _refresh();
- })
- ]
+ ? [
+ new SpanElement()..text = 'Yes ',
+ new ButtonElement()
+ ..text = 'disable'
+ ..onClick.listen((e) async {
+ e.target.disabled = true;
+ await _profiles.disable(_isolate, _cls);
+ _loadProfile = true;
+ _refresh();
+ })
+ ]
+ : [
+ new SpanElement()..text = 'No ',
+ new ButtonElement()
+ ..text = 'enable'
+ ..onClick.listen((e) async {
+ e.target.disabled = true;
+ await _profiles.enable(_isolate, _cls);
+ _refresh();
+ })
+ ]
],
new DivElement()
..children = _loadProfile
- ? [new ClassAllocationProfileElement(_isolate, _cls, _profiles,
- queue: _r.queue)]
- : const [],
+ ? [
+ new ClassAllocationProfileElement(_isolate, _cls, _profiles,
+ queue: _r.queue)
+ ]
+ : const [],
new DivElement()
..children = _cls.location != null
- ? [new HRElement(),
- new SourceInsetElement(_isolate, _cls.location, _scripts,
- _instances, _events, queue: _r.queue)]
- : const [],
+ ? [
+ new HRElement(),
+ new SourceInsetElement(
+ _isolate, _cls.location, _scripts, _instances, _events,
+ queue: _r.queue)
+ ]
+ : const [],
new HRElement(),
new ViewFooterElement(queue: _r.queue)
]
@@ -277,115 +298,127 @@
List<Element> _createMembers() {
final members = <Element>[];
if (_cls.library != null) {
- members.add(
- new DivElement()..classes = ['memberItem']
- ..children = [
- new DivElement()..classes = ['memberName']
- ..text = 'library',
- new DivElement()..classes = ['memberValue']
- ..children = [
- new LibraryRefElement(_isolate, _cls.library, queue: _r.queue)
- ]
- ]
- );
+ members.add(new DivElement()
+ ..classes = ['memberItem']
+ ..children = [
+ new DivElement()
+ ..classes = ['memberName']
+ ..text = 'library',
+ new DivElement()
+ ..classes = ['memberValue']
+ ..children = [
+ new LibraryRefElement(_isolate, _cls.library, queue: _r.queue)
+ ]
+ ]);
}
if (_cls.location != null) {
- members.add(
- new DivElement()..classes = ['memberItem']
- ..children = [
- new DivElement()..classes = ['memberName']
- ..text = 'script',
- new DivElement()..classes = ['memberValue']
- ..children = [
- new SourceLinkElement(_isolate, _cls.location, _scripts,
- queue: _r.queue)
- ]
- ]
- );
+ members.add(new DivElement()
+ ..classes = ['memberItem']
+ ..children = [
+ new DivElement()
+ ..classes = ['memberName']
+ ..text = 'script',
+ new DivElement()
+ ..classes = ['memberValue']
+ ..children = [
+ new SourceLinkElement(_isolate, _cls.location, _scripts,
+ queue: _r.queue)
+ ]
+ ]);
}
if (_cls.superclass != null) {
- members.add(
- new DivElement()..classes = ['memberItem']
- ..children = [
- new DivElement()..classes = ['memberName']
- ..text = 'superclass',
- new DivElement()..classes = ['memberValue']
- ..children = [
- new ClassRefElement(_isolate, _cls.superclass, queue: _r.queue)
- ]
- ]
- );
+ members.add(new DivElement()
+ ..classes = ['memberItem']
+ ..children = [
+ new DivElement()
+ ..classes = ['memberName']
+ ..text = 'superclass',
+ new DivElement()
+ ..classes = ['memberValue']
+ ..children = [
+ new ClassRefElement(_isolate, _cls.superclass, queue: _r.queue)
+ ]
+ ]);
}
if (_cls.superType != null) {
- members.add(
- new DivElement()..classes = ['memberItem']
- ..children = [
- new DivElement()..classes = ['memberName']
- ..text = 'supertype',
- new DivElement()..classes = ['memberValue']
- ..children = [
- new InstanceRefElement(_isolate, _cls.superType, _instances,
- queue: _r.queue)
- ]
- ]
- );
+ members.add(new DivElement()
+ ..classes = ['memberItem']
+ ..children = [
+ new DivElement()
+ ..classes = ['memberName']
+ ..text = 'supertype',
+ new DivElement()
+ ..classes = ['memberValue']
+ ..children = [
+ new InstanceRefElement(_isolate, _cls.superType, _instances,
+ queue: _r.queue)
+ ]
+ ]);
}
if (cls.mixin != null) {
- members.add(
- new DivElement()..classes = ['memberItem']
- ..children = [
- new DivElement()..classes = ['memberName']
- ..text = 'mixin',
- new DivElement()..classes = ['memberValue']
- ..children = [
- new InstanceRefElement(_isolate, _cls.mixin, _instances,
- queue: _r.queue)
- ]
- ]
- );
+ members.add(new DivElement()
+ ..classes = ['memberItem']
+ ..children = [
+ new DivElement()
+ ..classes = ['memberName']
+ ..text = 'mixin',
+ new DivElement()
+ ..classes = ['memberValue']
+ ..children = [
+ new InstanceRefElement(_isolate, _cls.mixin, _instances,
+ queue: _r.queue)
+ ]
+ ]);
}
if (_cls.subclasses.length > 0) {
- members.add(
- new DivElement()..classes = ['memberItem']
- ..children = [
- new DivElement()..classes = ['memberName']
- ..text = 'extended by',
- new DivElement()..classes = ['memberValue']
- ..children = (_cls.subclasses.expand((subcls) => [
- new ClassRefElement(_isolate, subcls, queue: _r.queue),
- new SpanElement()..text = ', '
- ]).toList()..removeLast())
- ]
- );
+ members.add(new DivElement()
+ ..classes = ['memberItem']
+ ..children = [
+ new DivElement()
+ ..classes = ['memberName']
+ ..text = 'extended by',
+ new DivElement()
+ ..classes = ['memberValue']
+ ..children = (_cls.subclasses
+ .expand((subcls) => [
+ new ClassRefElement(_isolate, subcls, queue: _r.queue),
+ new SpanElement()..text = ', '
+ ])
+ .toList()..removeLast())
+ ]);
}
members.add(new BRElement());
if (_cls.interfaces.length > 0) {
- members.add(
- new DivElement()..classes = ['memberItem']
- ..children = [
- new DivElement()..classes = ['memberName']
- ..text = 'implements',
- new DivElement()..classes = ['memberValue']
- ..children = (_cls.interfaces.expand((interf) => [
- new InstanceRefElement(_isolate, interf, _instances,
- queue: _r.queue),
- new SpanElement()..text = ', '
- ]).toList()..removeLast())
- ]
- );
+ members.add(new DivElement()
+ ..classes = ['memberItem']
+ ..children = [
+ new DivElement()
+ ..classes = ['memberName']
+ ..text = 'implements',
+ new DivElement()
+ ..classes = ['memberValue']
+ ..children = (_cls.interfaces
+ .expand((interf) => [
+ new InstanceRefElement(_isolate, interf, _instances,
+ queue: _r.queue),
+ new SpanElement()..text = ', '
+ ])
+ .toList()..removeLast())
+ ]);
}
if (_cls.name != _cls.vmName) {
- members.add(
- new DivElement()..classes = ['memberItem']
- ..children = [
- new DivElement()..classes = ['memberName']
- ..text = 'vm name',
- new DivElement()..classes = ['memberValue']
- ..text = '${_cls.vmName}'
- ]
- );
+ members.add(new DivElement()
+ ..classes = ['memberItem']
+ ..children = [
+ new DivElement()
+ ..classes = ['memberName']
+ ..text = 'vm name',
+ new DivElement()
+ ..classes = ['memberValue']
+ ..text = '${_cls.vmName}'
+ ]);
}
return members;
}
@@ -395,62 +428,70 @@
if (_classFields != null && _classFields.isNotEmpty) {
final fields = _classFields.toList();
_fieldsExpanded = _fieldsExpanded ?? (fields.length <= 8);
- members.add(
- new DivElement()..classes = ['memberItem']
- ..children = [
- new DivElement()..classes = ['memberName']
- ..text = 'fields ${fields.length}',
- new DivElement()..classes = ['memberValue']
- ..children =[
- new CurlyBlockElement(expanded: _fieldsExpanded)
- ..onToggle.listen((e) => _fieldsExpanded = e.control.expanded)
- ..content = [
- new DivElement()..classes = ['memberList']
- ..children = (fields.map((f) =>
- new DivElement()..classes = ['memberItem']
+ members.add(new DivElement()
+ ..classes = ['memberItem']
+ ..children = [
+ new DivElement()
+ ..classes = ['memberName']
+ ..text = 'fields ${fields.length}',
+ new DivElement()
+ ..classes = ['memberValue']
+ ..children = [
+ new CurlyBlockElement(expanded: _fieldsExpanded)
+ ..onToggle.listen((e) => _fieldsExpanded = e.control.expanded)
+ ..content = [
+ new DivElement()
+ ..classes = ['memberList']
+ ..children = (fields
+ .map((f) => new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
- ..children =[
+ new DivElement()
+ ..classes = ['memberName']
+ ..children = [
new FieldRefElement(_isolate, f, _instances,
- queue: _r.queue)
+ queue: _r.queue)
],
- new DivElement()..classes = ['memberValue']
+ new DivElement()
+ ..classes = ['memberValue']
..children = f.staticValue == null
- ? const []
- : [
- anyRef(_isolate, f.staticValue, _instances,
- queue: _r.queue)
- ]
- ]
- ).toList())
- ]
- ]
- ]
- );
+ ? const []
+ : [
+ anyRef(
+ _isolate, f.staticValue, _instances,
+ queue: _r.queue)
+ ]
+ ])
+ .toList())
+ ]
+ ]
+ ]);
}
if (_cls.functions.isNotEmpty) {
final functions = _cls.functions.toList();
_functionsExpanded = _functionsExpanded ?? (functions.length <= 8);
- members.add(
- new DivElement()..classes = ['memberItem']
- ..children = [
- new DivElement()..classes = ['memberName']
- ..text = 'functions (${functions.length})',
- new DivElement()..classes = ['memberValue']
- ..children =[
- new CurlyBlockElement(expanded: _functionsExpanded)
- ..onToggle.listen((e) =>
- _functionsExpanded = e.control.expanded)
- ..content = (functions.map((f) =>
- new DivElement()..classes = ['indent']
+ members.add(new DivElement()
+ ..classes = ['memberItem']
+ ..children = [
+ new DivElement()
+ ..classes = ['memberName']
+ ..text = 'functions (${functions.length})',
+ new DivElement()
+ ..classes = ['memberValue']
+ ..children = [
+ new CurlyBlockElement(expanded: _functionsExpanded)
+ ..onToggle
+ .listen((e) => _functionsExpanded = e.control.expanded)
+ ..content = (functions
+ .map((f) => new DivElement()
+ ..classes = ['indent']
..children = [
new FunctionRefElement(_isolate, f, queue: _r.queue)
- ]
- ).toList())
- ]
- ]
- );
+ ])
+ .toList())
+ ]
+ ]);
}
return members;
}
@@ -462,8 +503,8 @@
}
Future _loadAdditionalData() async {
- _classFields = await Future.wait(_cls.fields.map((f)
- => _fields.get(_isolate, f.id)));
+ _classFields =
+ await Future.wait(_cls.fields.map((f) => _fields.get(_isolate, f.id)));
_r.dirty();
}
}
diff --git a/runtime/observatory/lib/src/elements/code_ref.dart b/runtime/observatory/lib/src/elements/code_ref.dart
index c25f6c3..14b783b 100644
--- a/runtime/observatory/lib/src/elements/code_ref.dart
+++ b/runtime/observatory/lib/src/elements/code_ref.dart
@@ -7,7 +7,7 @@
import 'dart:html';
import 'dart:async';
import 'package:observatory/models.dart' as M
- show IsolateRef, CodeRef, isSyntheticCode;
+ show IsolateRef, CodeRef, isSyntheticCode;
import 'package:observatory/src/elements/helpers/rendering_scheduler.dart';
import 'package:observatory/src/elements/helpers/tag.dart';
import 'package:observatory/src/elements/helpers/uris.dart';
@@ -54,9 +54,10 @@
void render() {
final name = (_code.isOptimized ? '*' : '') + _code.name;
children = [
- new AnchorElement(href: M.isSyntheticCode(_code.kind) ? null
- : Uris.inspect(_isolate, object: _code))
- ..text = name
+ new AnchorElement(
+ href: M.isSyntheticCode(_code.kind)
+ ? null
+ : Uris.inspect(_isolate, object: _code))..text = name
];
}
}
diff --git a/runtime/observatory/lib/src/elements/code_view.dart b/runtime/observatory/lib/src/elements/code_view.dart
index e342941..702ad53 100644
--- a/runtime/observatory/lib/src/elements/code_view.dart
+++ b/runtime/observatory/lib/src/elements/code_view.dart
@@ -10,7 +10,7 @@
import 'package:observatory/service.dart' as S;
import 'package:observatory/models.dart' as M;
import 'package:observatory/app.dart'
- show SortedTable, SortedTableColumn, SortedTableRow;
+ show SortedTable, SortedTableColumn, SortedTableRow;
import 'package:observatory/src/elements/curly_block.dart';
import 'package:observatory/src/elements/function_ref.dart';
import 'package:observatory/src/elements/helpers/any_ref.dart';
@@ -37,19 +37,19 @@
}
class CodeViewElement extends HtmlElement implements Renderable {
- static const tag = const Tag<CodeViewElement>('code-view',
- dependencies: const [
- CurlyBlockElement.tag,
- FunctionRefElement.tag,
- NavClassMenuElement.tag,
- NavTopMenuElement.tag,
- NavVMMenuElement.tag,
- NavIsolateMenuElement.tag,
- NavRefreshElement.tag,
- NavNotifyElement.tag,
- ObjectCommonElement.tag,
- ObjectPoolRefElement.tag,
- ]);
+ static const tag =
+ const Tag<CodeViewElement>('code-view', dependencies: const [
+ CurlyBlockElement.tag,
+ FunctionRefElement.tag,
+ NavClassMenuElement.tag,
+ NavTopMenuElement.tag,
+ NavVMMenuElement.tag,
+ NavIsolateMenuElement.tag,
+ NavRefreshElement.tag,
+ NavNotifyElement.tag,
+ ObjectCommonElement.tag,
+ ObjectPoolRefElement.tag,
+ ]);
RenderingScheduler<CodeViewElement> _r;
@@ -70,21 +70,23 @@
static const kDisassemblyColumnIndex = 3;
-
M.VMRef get vm => _vm;
M.IsolateRef get isolate => _isolate;
M.NotificationRepository get notifications => _notifications;
M.Code get context => _code;
- factory CodeViewElement(M.VM vm, M.IsolateRef isolate, M.Code code,
- M.EventRepository events,
- M.NotificationRepository notifications,
- M.RetainedSizeRepository retainedSizes,
- M.ReachableSizeRepository reachableSizes,
- M.InboundReferencesRepository references,
- M.RetainingPathRepository retainingPaths,
- M.InstanceRepository instances,
- {RenderingQueue queue}) {
+ factory CodeViewElement(
+ M.VM vm,
+ M.IsolateRef isolate,
+ M.Code code,
+ M.EventRepository events,
+ M.NotificationRepository notifications,
+ M.RetainedSizeRepository retainedSizes,
+ M.ReachableSizeRepository reachableSizes,
+ M.InboundReferencesRepository references,
+ M.RetainingPathRepository retainingPaths,
+ M.InstanceRepository instances,
+ {RenderingQueue queue}) {
assert(vm != null);
assert(isolate != null);
assert(events != null);
@@ -112,18 +114,18 @@
CodeViewElement.created() : super.created() {
var columns = [
- new SortedTableColumn('Address'),
- new SortedTableColumn('Inclusive'),
- new SortedTableColumn('Exclusive'),
- new SortedTableColumn('Disassembly'),
- new SortedTableColumn('Objects'),
+ new SortedTableColumn('Address'),
+ new SortedTableColumn('Inclusive'),
+ new SortedTableColumn('Exclusive'),
+ new SortedTableColumn('Disassembly'),
+ new SortedTableColumn('Objects'),
];
disassemblyTable = new DisassemblyTable(columns);
columns = [
- new SortedTableColumn('Address'),
- new SortedTableColumn('Inclusive'),
- new SortedTableColumn('Exclusive'),
- new SortedTableColumn('Functions'),
+ new SortedTableColumn('Address'),
+ new SortedTableColumn('Inclusive'),
+ new SortedTableColumn('Exclusive'),
+ new SortedTableColumn('Functions'),
];
inlineTable = new InlineTable(columns);
}
@@ -149,43 +151,48 @@
void render() {
if (_inlineRangeTable == null) {
_inlineRangeTable = new TableElement()..classes = ['table'];
- _inlineRangeTable.createTHead()
- .children = [
- new TableRowElement()
- ..children = [
- document.createElement('th')..classes = ['address']
- ..text = 'Address Range',
- document.createElement('th')..classes = ['tick']
- ..text = 'Inclusive',
- document.createElement('th')..classes = ['tick']
- ..text = 'Exclusive',
- document.createElement('th')
- ..text = 'Functions',
- ]
- ];
+ _inlineRangeTable.createTHead().children = [
+ new TableRowElement()
+ ..children = [
+ document.createElement('th')
+ ..classes = ['address']
+ ..text = 'Address Range',
+ document.createElement('th')
+ ..classes = ['tick']
+ ..text = 'Inclusive',
+ document.createElement('th')
+ ..classes = ['tick']
+ ..text = 'Exclusive',
+ document.createElement('th')..text = 'Functions',
+ ]
+ ];
_inlineRangeTableBody = _inlineRangeTable.createTBody();
_inlineRangeTableBody.classes = ['monospace'];
}
if (_disassemblyTable == null) {
_disassemblyTable = new TableElement()..classes = ['table'];
- _disassemblyTable.createTHead()
- .children = [
- new TableRowElement()
- ..children = [
- document.createElement('th')..classes = ['address']
- ..text = 'Address Range',
- document.createElement('th')..classes = ['tick']
- ..title = 'Ticks with PC on the stack'
- ..text = 'Inclusive',
- document.createElement('th')..classes = ['tick']
- ..title = 'Ticks with PC at top of stack'
- ..text = 'Exclusive',
- document.createElement('th')..classes = ['disassembly']
- ..text = 'Disassembly',
- document.createElement('th')..classes = ['object']
- ..text = 'Object',
- ]
- ];
+ _disassemblyTable.createTHead().children = [
+ new TableRowElement()
+ ..children = [
+ document.createElement('th')
+ ..classes = ['address']
+ ..text = 'Address Range',
+ document.createElement('th')
+ ..classes = ['tick']
+ ..title = 'Ticks with PC on the stack'
+ ..text = 'Inclusive',
+ document.createElement('th')
+ ..classes = ['tick']
+ ..title = 'Ticks with PC at top of stack'
+ ..text = 'Exclusive',
+ document.createElement('th')
+ ..classes = ['disassembly']
+ ..text = 'Disassembly',
+ document.createElement('th')
+ ..classes = ['object']
+ ..text = 'Object',
+ ]
+ ];
_disassemblyTableBody = _disassemblyTable.createTBody();
_disassemblyTableBody.classes = ['monospace'];
}
@@ -198,100 +205,126 @@
new NavIsolateMenuElement(_isolate, _events, queue: _r.queue),
navMenu(_code.name),
new NavRefreshElement(queue: _r.queue)
- ..onRefresh.listen((e) async {
- e.element.disabled = true;
- _refresh();
- }),
+ ..onRefresh.listen((e) async {
+ e.element.disabled = true;
+ _refresh();
+ }),
new NavRefreshElement(label: 'refresh ticks', queue: _r.queue)
- ..onRefresh.listen((e) async {
- e.element.disabled = true;
- _refreshTicks();
- }),
+ ..onRefresh.listen((e) async {
+ e.element.disabled = true;
+ _refreshTicks();
+ }),
new NavNotifyElement(_notifications, queue: _r.queue)
]),
- new DivElement()..classes = ['content-centered-big']
+ new DivElement()
+ ..classes = ['content-centered-big']
..children = [
new HeadingElement.h1()
..text = (M.isDartCode(_code.kind) && _code.isOptimized)
- ? 'Optimized code for ${_code.name}'
- : 'Code for ${_code.name}',
+ ? 'Optimized code for ${_code.name}'
+ : 'Code for ${_code.name}',
new HRElement(),
new ObjectCommonElement(_isolate, _code, _retainedSizes,
- _reachableSizes, _references, _retainingPaths,
- _instances, queue: _r.queue),
+ _reachableSizes, _references, _retainingPaths, _instances,
+ queue: _r.queue),
new BRElement(),
- new DivElement()..classes = ['memberList']
+ new DivElement()
+ ..classes = ['memberList']
..children = [
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
- ..text = 'Kind',
- new DivElement()..classes = ['memberValue']
- ..text = _codeKindToString(_code.kind)
+ new DivElement()
+ ..classes = ['memberName']
+ ..text = 'Kind',
+ new DivElement()
+ ..classes = ['memberValue']
+ ..text = _codeKindToString(_code.kind)
],
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..children = M.isDartCode(_code.kind)
- ? const []
- : [
- new DivElement()..classes = ['memberName']
- ..text = 'Optimized',
- new DivElement()..classes = ['memberValue']
- ..text = _code.isOptimized ? 'Yes' : 'No'
- ],
- new DivElement()..classes = ['memberItem']
+ ? const []
+ : [
+ new DivElement()
+ ..classes = ['memberName']
+ ..text = 'Optimized',
+ new DivElement()
+ ..classes = ['memberValue']
+ ..text = _code.isOptimized ? 'Yes' : 'No'
+ ],
+ new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
- ..text = 'Function',
- new DivElement()..classes = ['memberValue']
- ..children = [
- new FunctionRefElement(_isolate, _code.function,
- queue: _r.queue)
- ]
+ new DivElement()
+ ..classes = ['memberName']
+ ..text = 'Function',
+ new DivElement()
+ ..classes = ['memberValue']
+ ..children = [
+ new FunctionRefElement(_isolate, _code.function,
+ queue: _r.queue)
+ ]
],
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..children = code.profile == null
- ? const []
- : [
- new DivElement()..classes = ['memberName']
- ..text = 'Inclusive',
- new DivElement()..classes = ['memberValue']
- ..text = '${code.profile.formattedInclusiveTicks}'
- ],
- new DivElement()..classes = ['memberItem']
+ ? const []
+ : [
+ new DivElement()
+ ..classes = ['memberName']
+ ..text = 'Inclusive',
+ new DivElement()
+ ..classes = ['memberValue']
+ ..text = '${code.profile.formattedInclusiveTicks}'
+ ],
+ new DivElement()
+ ..classes = ['memberItem']
..children = code.profile == null
- ? const []
- : [
- new DivElement()..classes = ['memberName']
- ..text = 'Exclusive',
- new DivElement()..classes = ['memberValue']
- ..text = '${code.profile.formattedExclusiveTicks}'
- ],
- new DivElement()..classes = ['memberItem']
+ ? const []
+ : [
+ new DivElement()
+ ..classes = ['memberName']
+ ..text = 'Exclusive',
+ new DivElement()
+ ..classes = ['memberValue']
+ ..text = '${code.profile.formattedExclusiveTicks}'
+ ],
+ new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
- ..text = 'Object pool',
- new DivElement()..classes = ['memberValue']
- ..children = [
- new ObjectPoolRefElement(_isolate, _code.objectPool,
- queue: _r.queue)
- ]
+ new DivElement()
+ ..classes = ['memberName']
+ ..text = 'Object pool',
+ new DivElement()
+ ..classes = ['memberValue']
+ ..children = [
+ new ObjectPoolRefElement(_isolate, _code.objectPool,
+ queue: _r.queue)
+ ]
],
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..children = inlinedFunctions.isNotEmpty
- ? const []
- : [
- new DivElement()..classes = ['memberName']
- ..text = 'inlined functions (${inlinedFunctions.length})',
- new DivElement()..classes = ['memberValue']
- ..children = [
- new CurlyBlockElement(
- expanded: inlinedFunctions.length < 8,
- queue: _r.queue)
- ..content = inlinedFunctions.map((f) =>
- new FunctionRefElement(_isolate, f, queue: _r.queue)
- ).toList()
+ ? const []
+ : [
+ new DivElement()
+ ..classes = ['memberName']
+ ..text =
+ 'inlined functions (${inlinedFunctions.length})',
+ new DivElement()
+ ..classes = ['memberValue']
+ ..children = [
+ new CurlyBlockElement(
+ expanded: inlinedFunctions.length < 8,
+ queue: _r.queue)
+ ..content = inlinedFunctions
+ .map((f) => new FunctionRefElement(
+ _isolate, f,
+ queue: _r.queue))
+ .toList()
+ ]
]
- ]
],
new HRElement(),
_inlineRangeTable,
@@ -312,8 +345,8 @@
Future _refreshTicks() async {
S.Code code = _code as S.Code;
final isolate = code.isolate;
- S.ServiceMap response = await isolate.invokeRpc('_getCpuProfile',
- { 'tags': 'None' });
+ S.ServiceMap response =
+ await isolate.invokeRpc('_getCpuProfile', {'tags': 'None'});
final cpuProfile = new CpuProfile();
await cpuProfile.load(isolate, response);
_r.dirty();
@@ -345,8 +378,8 @@
if (intervalTick.inclusiveTicks == intervalTick.exclusiveTicks) {
return '';
}
- var pcent = Utils.formatPercent(intervalTick.inclusiveTicks,
- code.profile.profile.sampleCount);
+ var pcent = Utils.formatPercent(
+ intervalTick.inclusiveTicks, code.profile.profile.sampleCount);
return '$pcent (${intervalTick.inclusiveTicks})';
}
@@ -359,12 +392,11 @@
if (intervalTick == null) {
return '';
}
- var pcent = Utils.formatPercent(intervalTick.exclusiveTicks,
- code.profile.profile.sampleCount);
+ var pcent = Utils.formatPercent(
+ intervalTick.exclusiveTicks, code.profile.profile.sampleCount);
return '$pcent (${intervalTick.exclusiveTicks})';
}
-
String _formattedInclusive(S.CodeInstruction instruction) {
S.Code code = _code as S.Code;
if (code.profile == null) {
@@ -378,8 +410,8 @@
if (tick.inclusiveTicks == tick.exclusiveTicks) {
return '';
}
- var pcent = Utils.formatPercent(tick.inclusiveTicks,
- code.profile.profile.sampleCount);
+ var pcent = Utils.formatPercent(
+ tick.inclusiveTicks, code.profile.profile.sampleCount);
return '$pcent (${tick.inclusiveTicks})';
}
@@ -392,8 +424,8 @@
if (tick == null) {
return '';
}
- var pcent = Utils.formatPercent(tick.exclusiveTicks,
- code.profile.profile.sampleCount);
+ var pcent = Utils.formatPercent(
+ tick.exclusiveTicks, code.profile.profile.sampleCount);
return '$pcent (${tick.exclusiveTicks})';
}
@@ -404,11 +436,13 @@
return;
}
for (S.CodeInstruction instruction in code.instructions) {
- var row = [_formattedAddress(instruction),
- _formattedInclusive(instruction),
- _formattedExclusive(instruction),
- instruction.human,
- instruction.object];
+ var row = [
+ _formattedAddress(instruction),
+ _formattedInclusive(instruction),
+ _formattedExclusive(instruction),
+ instruction.human,
+ instruction.object
+ ];
disassemblyTable.addRow(new SortedTableRow(row));
}
}
@@ -442,7 +476,6 @@
final cell = tr.children[i];
final content = row.values[i];
if (content is S.HeapObject) {
- print(content.runtimeType);
cell.children = [
anyRef(_isolate, content, _instances, queue: _r.queue)
];
@@ -472,7 +505,7 @@
if (tableBody.children.length > disassemblyTable.sortedRows.length) {
// Shrink the table.
var deadRows =
- tableBody.children.length - disassemblyTable.sortedRows.length;
+ tableBody.children.length - disassemblyTable.sortedRows.length;
for (var i = 0; i < deadRows; i++) {
tableBody.children.removeLast();
}
@@ -505,10 +538,12 @@
inlineTable.clearRows();
S.Code code = _code as S.Code;
for (S.CodeInlineInterval interval in code.inlineIntervals) {
- var row = [interval,
- _formattedInclusiveInterval(interval),
- _formattedExclusiveInterval(interval),
- interval.functions];
+ var row = [
+ interval,
+ _formattedInclusiveInterval(interval),
+ _formattedExclusiveInterval(interval),
+ interval.functions
+ ];
inlineTable.addRow(new SortedTableRow(row));
}
}
@@ -557,8 +592,8 @@
var functionsCell = tr.children[functionsColumn];
functionsCell.children.clear();
for (var func in functions) {
- functionsCell.children.add(
- new FunctionRefElement(_isolate, func, queue: _r.queue));
+ functionsCell.children
+ .add(new FunctionRefElement(_isolate, func, queue: _r.queue));
var gap = new SpanElement();
gap.style.minWidth = '1em';
gap.text = ' ';
@@ -571,8 +606,7 @@
// Resize DOM table.
if (tableBody.children.length > inlineTable.sortedRows.length) {
// Shrink the table.
- var deadRows =
- tableBody.children.length - inlineTable.sortedRows.length;
+ var deadRows = tableBody.children.length - inlineTable.sortedRows.length;
for (var i = 0; i < deadRows; i++) {
tableBody.children.removeLast();
}
@@ -599,11 +633,16 @@
static String _codeKindToString(M.CodeKind kind) {
switch (kind) {
- case M.CodeKind.dart: return 'dart';
- case M.CodeKind.native: return 'native';
- case M.CodeKind.stub: return 'stub';
- case M.CodeKind.tag: return 'tag';
- case M.CodeKind.collected: return 'collected';
+ case M.CodeKind.dart:
+ return 'dart';
+ case M.CodeKind.native:
+ return 'native';
+ case M.CodeKind.stub:
+ return 'stub';
+ case M.CodeKind.tag:
+ return 'tag';
+ case M.CodeKind.collected:
+ return 'collected';
}
throw new Exception('Unkown CodeKind ($kind)');
}
diff --git a/runtime/observatory/lib/src/elements/containers/virtual_collection.dart b/runtime/observatory/lib/src/elements/containers/virtual_collection.dart
index d8d6e16..4747539 100644
--- a/runtime/observatory/lib/src/elements/containers/virtual_collection.dart
+++ b/runtime/observatory/lib/src/elements/containers/virtual_collection.dart
@@ -8,12 +8,11 @@
import 'package:observatory/src/elements/helpers/tag.dart';
typedef HtmlElement VirtualCollectionCreateCallback();
-typedef void VirtualCollectionUpdateCallback(HtmlElement el, dynamic item,
- int index);
+typedef void VirtualCollectionUpdateCallback(
+ HtmlElement el, dynamic item, int index);
class VirtualCollectionElement extends HtmlElement implements Renderable {
- static const tag =
- const Tag<VirtualCollectionElement>('virtual-collection');
+ static const tag = const Tag<VirtualCollectionElement>('virtual-collection');
RenderingScheduler<VirtualCollectionElement> _r;
@@ -39,9 +38,9 @@
_r.dirty();
}
-
factory VirtualCollectionElement(VirtualCollectionCreateCallback create,
- VirtualCollectionUpdateCallback update, {Iterable items: const [],
+ VirtualCollectionUpdateCallback update,
+ {Iterable items: const [],
VirtualCollectionCreateCallback createHeader,
RenderingQueue queue}) {
assert(create != null);
@@ -68,7 +67,7 @@
_onResizeSubscription = window.onResize.listen(_onResize);
}
- @override
+ @override
detached() {
super.detached();
_r.disable(notify: true);
@@ -87,7 +86,7 @@
return null;
}
final item_index =
- _top + el_index - (_shifter.children.length * _inverse_preload).floor();
+ _top + el_index - (_shifter.children.length * _inverse_preload).floor();
if (0 <= item_index && item_index < items.length) {
return _items[item_index];
}
@@ -98,6 +97,7 @@
/// 1/preload_size of the number of items in the visble area.
/// See shared.css for the "top:-25%;".
static const int _preload = 2;
+
/// L = length of all the elements loaded
/// l = length of the visible area
///
@@ -119,8 +119,7 @@
children = [
_scroller
..children = [
- _shifter
- ..children = [_create()]
+ _shifter..children = [_create()]
],
];
if (_createHeader != null) {
diff --git a/runtime/observatory/lib/src/elements/containers/virtual_tree.dart b/runtime/observatory/lib/src/elements/containers/virtual_tree.dart
index 4df0dd7..4597248 100644
--- a/runtime/observatory/lib/src/elements/containers/virtual_tree.dart
+++ b/runtime/observatory/lib/src/elements/containers/virtual_tree.dart
@@ -25,10 +25,8 @@
}
class VirtualTreeElement extends HtmlElement implements Renderable {
- static const tag =
- const Tag<VirtualTreeElement>('virtual-tree', dependencies: const [
- VirtualCollectionElement.tag
- ]);
+ static const tag = const Tag<VirtualTreeElement>('virtual-tree',
+ dependencies: const [VirtualCollectionElement.tag]);
RenderingScheduler<VirtualTreeElement> _r;
@@ -59,14 +57,17 @@
e._children = children;
e._collection = new VirtualCollectionElement(() {
var element;
- return element = create(({bool autoToggleSingleChildNodes: false,
+ return element = create((
+ {bool autoToggleSingleChildNodes: false,
bool autoToggleWholeTree: false}) {
var item = e._collection.getItemFromElement(element);
if (e.isExpanded(item)) {
- e.collapse(item, autoCollapseWholeTree: autoToggleWholeTree,
+ e.collapse(item,
+ autoCollapseWholeTree: autoToggleWholeTree,
autoCollapseSingleChildNodes: autoToggleSingleChildNodes);
} else {
- e.expand(item, autoExpandWholeTree: autoToggleWholeTree,
+ e.expand(item,
+ autoExpandWholeTree: autoToggleWholeTree,
autoExpandSingleChildNodes: autoToggleSingleChildNodes);
}
});
@@ -83,7 +84,8 @@
return _expanded.contains(item);
}
- void expand(item, {bool autoExpandSingleChildNodes : false,
+ void expand(item,
+ {bool autoExpandSingleChildNodes: false,
bool autoExpandWholeTree: false}) {
if (_expanded.add(item)) _r.dirty();
if (autoExpandWholeTree) {
@@ -99,7 +101,8 @@
}
}
- void collapse(item, {bool autoCollapseSingleChildNodes : false,
+ void collapse(item,
+ {bool autoCollapseSingleChildNodes: false,
bool autoCollapseWholeTree: false}) {
if (_expanded.remove(item)) _r.dirty();
if (autoCollapseWholeTree) {
@@ -121,9 +124,10 @@
_r.enable();
}
- @override
+ @override
detached() {
- super.detached(); _r.disable(notify: true);
+ super.detached();
+ _r.disable(notify: true);
children = const [];
}
@@ -142,6 +146,7 @@
}
return [item];
}
+
_collection.items = _items.expand(_toList);
var depth = 0;
Iterable _toDepth(item) {
@@ -149,12 +154,12 @@
Iterable children = _children(item);
if (children.isNotEmpty) {
depth++;
- return children.expand(_toDepth).toList()
- ..insert(0, --depth);
+ return children.expand(_toDepth).toList()..insert(0, --depth);
}
}
return [depth];
}
+
_depths = _items.expand(_toDepth).toList();
}
}
diff --git a/runtime/observatory/lib/src/elements/context_ref.dart b/runtime/observatory/lib/src/elements/context_ref.dart
index 90138bb..7628396 100644
--- a/runtime/observatory/lib/src/elements/context_ref.dart
+++ b/runtime/observatory/lib/src/elements/context_ref.dart
@@ -4,8 +4,7 @@
import 'dart:html';
import 'dart:async';
-import 'package:observatory/models.dart' as M
- show IsolateRef, ContextRef;
+import 'package:observatory/models.dart' as M show IsolateRef, ContextRef;
import 'package:observatory/src/elements/helpers/rendering_scheduler.dart';
import 'package:observatory/src/elements/helpers/tag.dart';
import 'package:observatory/src/elements/helpers/uris.dart';
@@ -53,7 +52,9 @@
children = [
new AnchorElement(href: Uris.inspect(_isolate, object: _context))
..children = [
- new SpanElement()..classes = ['emphasize']..text = 'Context',
+ new SpanElement()
+ ..classes = ['emphasize']
+ ..text = 'Context',
new SpanElement()..text = ' (${_context.length})'
]
];
diff --git a/runtime/observatory/lib/src/elements/context_view.dart b/runtime/observatory/lib/src/elements/context_view.dart
index c3afef5..69036ad 100644
--- a/runtime/observatory/lib/src/elements/context_view.dart
+++ b/runtime/observatory/lib/src/elements/context_view.dart
@@ -22,19 +22,19 @@
import 'package:observatory/src/elements/view_footer.dart';
class ContextViewElement extends HtmlElement implements Renderable {
- static const tag = const Tag<ContextViewElement>('context-view',
- dependencies: const [
- ContextRefElement.tag,
- CurlyBlockElement.tag,
- NavClassMenuElement.tag,
- NavTopMenuElement.tag,
- NavVMMenuElement.tag,
- NavIsolateMenuElement.tag,
- NavRefreshElement.tag,
- NavNotifyElement.tag,
- ObjectCommonElement.tag,
- ViewFooterElement.tag
- ]);
+ static const tag =
+ const Tag<ContextViewElement>('context-view', dependencies: const [
+ ContextRefElement.tag,
+ CurlyBlockElement.tag,
+ NavClassMenuElement.tag,
+ NavTopMenuElement.tag,
+ NavVMMenuElement.tag,
+ NavIsolateMenuElement.tag,
+ NavRefreshElement.tag,
+ NavNotifyElement.tag,
+ ObjectCommonElement.tag,
+ ViewFooterElement.tag
+ ]);
RenderingScheduler<ContextViewElement> _r;
@@ -52,22 +52,24 @@
M.RetainingPathRepository _retainingPaths;
M.InstanceRepository _instances;
-
M.VMRef get vm => _vm;
M.IsolateRef get isolate => _isolate;
M.NotificationRepository get notifications => _notifications;
M.Context get context => _context;
- factory ContextViewElement(M.VM vm, M.IsolateRef isolate, M.Context context,
- M.EventRepository events,
- M.NotificationRepository notifications,
- M.ContextRepository contexts,
- M.RetainedSizeRepository retainedSizes,
- M.ReachableSizeRepository reachableSizes,
- M.InboundReferencesRepository references,
- M.RetainingPathRepository retainingPaths,
- M.InstanceRepository instances,
- {RenderingQueue queue}) {
+ factory ContextViewElement(
+ M.VM vm,
+ M.IsolateRef isolate,
+ M.Context context,
+ M.EventRepository events,
+ M.NotificationRepository notifications,
+ M.ContextRepository contexts,
+ M.RetainedSizeRepository retainedSizes,
+ M.ReachableSizeRepository reachableSizes,
+ M.InboundReferencesRepository references,
+ M.RetainingPathRepository retainingPaths,
+ M.InstanceRepository instances,
+ {RenderingQueue queue}) {
assert(vm != null);
assert(isolate != null);
assert(events != null);
@@ -119,37 +121,43 @@
new NavClassMenuElement(_isolate, _context.clazz, queue: _r.queue),
navMenu('instance'),
new NavRefreshElement(queue: _r.queue)
- ..onRefresh.listen((e) async {
- e.element.disabled = true;
- _context = await _contexts.get(_isolate, _context.id);
- _r.dirty();
- }),
+ ..onRefresh.listen((e) async {
+ e.element.disabled = true;
+ _context = await _contexts.get(_isolate, _context.id);
+ _r.dirty();
+ }),
new NavNotifyElement(_notifications, queue: _r.queue)
]),
- new DivElement()..classes = ['content-centered-big']
+ new DivElement()
+ ..classes = ['content-centered-big']
..children = [
new HeadingElement.h2()..text = 'Context',
new HRElement(),
new ObjectCommonElement(_isolate, _context, _retainedSizes,
- _reachableSizes, _references, _retainingPaths,
- _instances, queue: _r.queue)
+ _reachableSizes, _references, _retainingPaths, _instances,
+ queue: _r.queue)
]
];
if (_context.parentContext != null) {
content.addAll([
new BRElement(),
- new DivElement()..classes = ['content-centered-big']
+ new DivElement()
+ ..classes = ['content-centered-big']
..children = [
- new DivElement()..classes = ['memberList']
+ new DivElement()
+ ..classes = ['memberList']
..children = [
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'parent context',
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..children = [
new ContextRefElement(_isolate, _context.parentContext,
- queue: _r.queue)
+ queue: _r.queue)
]
]
]
@@ -160,29 +168,36 @@
if (_context.variables.isNotEmpty) {
int index = 0;
content.addAll([
- new DivElement()..classes = ['content-centered-big']
+ new DivElement()
+ ..classes = ['content-centered-big']
..children = [
new SpanElement()..text = 'Variables ',
- new CurlyBlockElement(expanded: _context.variables.length > 8,
- queue: _r.queue)
+ new CurlyBlockElement(
+ expanded: _context.variables.length > 8, queue: _r.queue)
..content = [
- new DivElement()..classes = ['memberList']
- ..children = _context.variables.map((variable)
- => new DivElement()..classes = ['memberItem']
- ..children = [
- new DivElement()..classes = ['memberName']
- ..text = '[ ${++index} ]',
- new DivElement()..classes = ['memberName']
- ..children = [
- anyRef(_isolate, variable.value, _instances,
- queue: _r.queue)
- ]
- ]).toList()
+ new DivElement()
+ ..classes = ['memberList']
+ ..children = _context.variables
+ .map((variable) => new DivElement()
+ ..classes = ['memberItem']
+ ..children = [
+ new DivElement()
+ ..classes = ['memberName']
+ ..text = '[ ${++index} ]',
+ new DivElement()
+ ..classes = ['memberName']
+ ..children = [
+ anyRef(_isolate, variable.value, _instances,
+ queue: _r.queue)
+ ]
+ ])
+ .toList()
]
]
]);
}
- content.add(new DivElement()..classes = ['content-centered-big']
+ content.add(new DivElement()
+ ..classes = ['content-centered-big']
..children = [new ViewFooterElement(queue: _r.queue)]);
children = content;
}
diff --git a/runtime/observatory/lib/src/elements/cpu_profile.dart b/runtime/observatory/lib/src/elements/cpu_profile.dart
index 606c817..68fba8a 100644
--- a/runtime/observatory/lib/src/elements/cpu_profile.dart
+++ b/runtime/observatory/lib/src/elements/cpu_profile.dart
@@ -21,18 +21,18 @@
import 'package:observatory/src/elements/sample_buffer_control.dart';
import 'package:observatory/src/elements/stack_trace_tree_config.dart';
-class CpuProfileElement extends HtmlElement implements Renderable {
- static const tag = const Tag<CpuProfileElement>('cpu-profile',
- dependencies: const [
- NavTopMenuElement.tag,
- NavVMMenuElement.tag,
- NavIsolateMenuElement.tag,
- NavRefreshElement.tag,
- NavNotifyElement.tag,
- SampleBufferControlElement.tag,
- StackTraceTreeConfigElement.tag,
- CpuProfileVirtualTreeElement.tag,
- ]);
+class CpuProfileElement extends HtmlElement implements Renderable {
+ static const tag =
+ const Tag<CpuProfileElement>('cpu-profile', dependencies: const [
+ NavTopMenuElement.tag,
+ NavVMMenuElement.tag,
+ NavIsolateMenuElement.tag,
+ NavRefreshElement.tag,
+ NavNotifyElement.tag,
+ SampleBufferControlElement.tag,
+ StackTraceTreeConfigElement.tag,
+ CpuProfileVirtualTreeElement.tag,
+ ]);
RenderingScheduler<CpuProfileElement> _r;
@@ -50,17 +50,18 @@
M.ProfileTreeDirection _direction = M.ProfileTreeDirection.exclusive;
String _filter = '';
-
M.IsolateRef get isolate => _isolate;
M.NotificationRepository get notifications => _notifications;
M.IsolateSampleProfileRepository get profiles => _profiles;
M.VMRef get vm => _vm;
- factory CpuProfileElement(M.VM vm, M.IsolateRef isolate,
- M.EventRepository events,
- M.NotificationRepository notifications,
- M.IsolateSampleProfileRepository profiles,
- {RenderingQueue queue}) {
+ factory CpuProfileElement(
+ M.VM vm,
+ M.IsolateRef isolate,
+ M.EventRepository events,
+ M.NotificationRepository notifications,
+ M.IsolateSampleProfileRepository profiles,
+ {RenderingQueue queue}) {
assert(vm != null);
assert(isolate != null);
assert(events != null);
@@ -99,10 +100,9 @@
new NavVMMenuElement(_vm, _events, queue: _r.queue),
new NavIsolateMenuElement(_isolate, _events, queue: _r.queue),
navMenu('cpu profile', link: Uris.cpuProfiler(_isolate)),
- new NavRefreshElement(queue: _r.queue)
- ..onRefresh.listen(_refresh),
+ new NavRefreshElement(queue: _r.queue)..onRefresh.listen(_refresh),
new NavRefreshElement(label: 'Clear', queue: _r.queue)
- ..onRefresh.listen(_clearCpuProfile),
+ ..onRefresh.listen(_clearCpuProfile),
new NavNotifyElement(_notifications, queue: _r.queue)
]),
];
@@ -111,29 +111,36 @@
return;
}
content.add(new SampleBufferControlElement(_progress, _progressStream,
- selectedTag: _tag, queue: _r.queue)
+ selectedTag: _tag, queue: _r.queue)
..onTagChange.listen((e) {
_tag = e.element.selectedTag;
_request();
- }));
+ }));
if (_progress.status == M.SampleProfileLoadingStatus.loaded) {
CpuProfileVirtualTreeElement tree;
content.addAll([
new BRElement(),
- new StackTraceTreeConfigElement(mode: _mode, direction: _direction,
- filter: _filter, queue: _r.queue)
- ..onModeChange.listen((e) {
- _mode = tree.mode = e.element.mode;
- })
- ..onFilterChange.listen((e) {
- _filter = e.element.filter.trim();
- tree.filters = _filter.isNotEmpty
- ? [(node) { return node.name.contains(_filter); }]
+ new StackTraceTreeConfigElement(
+ mode: _mode,
+ direction: _direction,
+ filter: _filter,
+ queue: _r.queue)
+ ..onModeChange.listen((e) {
+ _mode = tree.mode = e.element.mode;
+ })
+ ..onFilterChange.listen((e) {
+ _filter = e.element.filter.trim();
+ tree.filters = _filter.isNotEmpty
+ ? [
+ (node) {
+ return node.name.contains(_filter);
+ }
+ ]
: const [];
- })
- ..onDirectionChange.listen((e) {
- _direction = tree.direction = e.element.direction;
- }),
+ })
+ ..onDirectionChange.listen((e) {
+ _direction = tree.direction = e.element.direction;
+ }),
new BRElement(),
tree = new CpuProfileVirtualTreeElement(_isolate, _progress.profile,
queue: _r.queue)
@@ -144,8 +151,8 @@
Future _request({bool clear: false, bool forceFetch: false}) async {
_progress = null;
- _progressStream = _profiles.get(isolate, _tag, clear: clear,
- forceFetch: forceFetch);
+ _progressStream =
+ _profiles.get(isolate, _tag, clear: clear, forceFetch: forceFetch);
_r.dirty();
_progress = (await _progressStream.first).progress;
_r.dirty();
diff --git a/runtime/observatory/lib/src/elements/cpu_profile/virtual_tree.dart b/runtime/observatory/lib/src/elements/cpu_profile/virtual_tree.dart
index 6c4b257..7617a20 100644
--- a/runtime/observatory/lib/src/elements/cpu_profile/virtual_tree.dart
+++ b/runtime/observatory/lib/src/elements/cpu_profile/virtual_tree.dart
@@ -7,7 +7,7 @@
import 'dart:math' as Math;
import 'package:observatory/models.dart' as M;
import 'package:observatory/src/elements/stack_trace_tree_config.dart'
- show ProfileTreeMode;
+ show ProfileTreeMode;
import 'package:observatory/src/elements/code_ref.dart';
import 'package:observatory/src/elements/containers/virtual_tree.dart';
import 'package:observatory/src/elements/function_ref.dart';
@@ -16,7 +16,7 @@
import 'package:observatory/utils.dart';
export 'package:observatory/src/elements/stack_trace_tree_config.dart'
- show ProfileTreeMode;
+ show ProfileTreeMode;
class CpuProfileVirtualTreeElement extends HtmlElement implements Renderable {
static const tag =
@@ -25,7 +25,7 @@
RenderingScheduler<CpuProfileVirtualTreeElement> _r;
Stream<RenderedEvent<CpuProfileVirtualTreeElement>> get onRendered =>
- _r.onRendered;
+ _r.onRendered;
M.ProfileTreeDirection _direction;
ProfileTreeMode _mode;
@@ -47,8 +47,9 @@
_r.dirty();
}
- factory CpuProfileVirtualTreeElement(M.IsolateRef isolate,
- M.SampleProfile profile, {ProfileTreeMode mode: ProfileTreeMode.function,
+ factory CpuProfileVirtualTreeElement(
+ M.IsolateRef isolate, M.SampleProfile profile,
+ {ProfileTreeMode mode: ProfileTreeMode.function,
M.ProfileTreeDirection direction: M.ProfileTreeDirection.exclusive,
RenderingQueue queue}) {
assert(isolate != null);
@@ -72,7 +73,7 @@
_r.enable();
}
- @override
+ @override
detached() {
super.detached();
_r.disable(notify: true);
@@ -102,13 +103,11 @@
});
}
if (tree == null) {
- children = [
- new HeadingElement.h1()..text = 'No Results'
- ];
+ children = [new HeadingElement.h1()..text = 'No Results'];
return;
}
_tree = new VirtualTreeElement(_createRow, update, _getChildren,
- items: tree.root.children, queue: _r.queue);
+ items: tree.root.children, queue: _r.queue);
if (tree.root.children.length == 1) {
_tree.expand(tree.root.children.first, autoExpandSingleChildNodes: true);
}
@@ -119,14 +118,18 @@
return new DivElement()
..classes = ['tree-item']
..children = [
- new SpanElement()..classes = ['inclusive']
+ new SpanElement()
+ ..classes = ['inclusive']
..title = 'global % on stack',
- new SpanElement()..classes = ['exclusive']
+ new SpanElement()
+ ..classes = ['exclusive']
..title = 'global % executing',
new SpanElement()..classes = ['lines'],
- new ButtonElement()..classes = ['expander']
+ new ButtonElement()
+ ..classes = ['expander']
..onClick.listen((_) => toggle(autoToggleSingleChildNodes: true)),
- new SpanElement()..classes = ['percentage']
+ new SpanElement()
+ ..classes = ['percentage']
..title = 'tree node %',
new SpanElement()..classes = ['name']
];
@@ -134,41 +137,38 @@
static _getChildren(M.CallTreeNode node) => node.children;
- void _updateFunctionRow(HtmlElement element, M.FunctionCallTreeNode item,
- int depth) {
- element.children[0].text = Utils.formatPercentNormalized(
- item.profileFunction.normalizedInclusiveTicks);
- element.children[1].text = Utils.formatPercentNormalized(
- item.profileFunction.normalizedExclusiveTicks);
+ void _updateFunctionRow(
+ HtmlElement element, M.FunctionCallTreeNode item, int depth) {
+ element.children[0].text = Utils
+ .formatPercentNormalized(item.profileFunction.normalizedInclusiveTicks);
+ element.children[1].text = Utils
+ .formatPercentNormalized(item.profileFunction.normalizedExclusiveTicks);
_updateLines(element.children[2].children, depth);
if (item.children.isNotEmpty) {
element.children[3].text = _tree.isExpanded(item) ? '▼' : '►';
} else {
element.children[3].text = '';
}
- element.children[4].text = Utils.formatPercentNormalized(
- item.percentage);
- element.children[5] = new FunctionRefElement(_isolate,
- item.profileFunction.function, queue: _r.queue)
- ..classes = ['name'];
+ element.children[4].text = Utils.formatPercentNormalized(item.percentage);
+ element.children[5] = new FunctionRefElement(
+ _isolate, item.profileFunction.function, queue: _r.queue)
+ ..classes = ['name'];
}
void _updateCodeRow(HtmlElement element, M.CodeCallTreeNode item, int depth) {
- element.children[0].text = Utils.formatPercentNormalized(
- item.profileCode.normalizedInclusiveTicks);
- element.children[1].text = Utils.formatPercentNormalized(
- item.profileCode.normalizedExclusiveTicks);
+ element.children[0].text = Utils
+ .formatPercentNormalized(item.profileCode.normalizedInclusiveTicks);
+ element.children[1].text = Utils
+ .formatPercentNormalized(item.profileCode.normalizedExclusiveTicks);
_updateLines(element.children[2].children, depth);
if (item.children.isNotEmpty) {
element.children[3].text = _tree.isExpanded(item) ? '▼' : '►';
} else {
element.children[3].text = '';
}
- element.children[4].text = Utils.formatPercentNormalized(
- item.percentage);
- element.children[5] = new CodeRefElement(_isolate,
- item.profileCode.code, queue: _r.queue)
- ..classes = ['name'];
+ element.children[4].text = Utils.formatPercentNormalized(item.percentage);
+ element.children[5] = new CodeRefElement(_isolate, item.profileCode.code,
+ queue: _r.queue)..classes = ['name'];
}
static _updateLines(List<Element> lines, int n) {
diff --git a/runtime/observatory/lib/src/elements/cpu_profile_table.dart b/runtime/observatory/lib/src/elements/cpu_profile_table.dart
index 72be839..68d7f60 100644
--- a/runtime/observatory/lib/src/elements/cpu_profile_table.dart
+++ b/runtime/observatory/lib/src/elements/cpu_profile_table.dart
@@ -23,39 +23,26 @@
import 'package:observatory/src/elements/stack_trace_tree_config.dart';
import 'package:observatory/utils.dart';
-enum _Table {
- functions,
- caller,
- callee
-}
+enum _Table { functions, caller, callee }
-enum _SortingField {
- exclusive,
- inclusive,
- caller,
- callee,
- method
-}
+enum _SortingField { exclusive, inclusive, caller, callee, method }
-enum _SortingDirection {
- ascending,
- descending
-}
+enum _SortingDirection { ascending, descending }
-class CpuProfileTableElement extends HtmlElement implements Renderable {
+class CpuProfileTableElement extends HtmlElement implements Renderable {
static const tag = const Tag<CpuProfileTableElement>('cpu-profile-table',
- dependencies: const [
- FunctionRefElement.tag,
- NavTopMenuElement.tag,
- NavVMMenuElement.tag,
- NavIsolateMenuElement.tag,
- NavRefreshElement.tag,
- NavNotifyElement.tag,
- SampleBufferControlElement.tag,
- StackTraceTreeConfigElement.tag,
- CpuProfileVirtualTreeElement.tag,
- VirtualCollectionElement.tag
- ]);
+ dependencies: const [
+ FunctionRefElement.tag,
+ NavTopMenuElement.tag,
+ NavVMMenuElement.tag,
+ NavIsolateMenuElement.tag,
+ NavRefreshElement.tag,
+ NavNotifyElement.tag,
+ SampleBufferControlElement.tag,
+ StackTraceTreeConfigElement.tag,
+ CpuProfileVirtualTreeElement.tag,
+ VirtualCollectionElement.tag
+ ]);
RenderingScheduler<CpuProfileTableElement> _r;
@@ -69,28 +56,29 @@
Stream<M.SampleProfileLoadingProgressEvent> _progressStream;
M.SampleProfileLoadingProgress _progress;
final _sortingField = <_Table, _SortingField>{
- _Table.functions : _SortingField.exclusive,
- _Table.caller : _SortingField.caller,
- _Table.callee : _SortingField.callee,
+ _Table.functions: _SortingField.exclusive,
+ _Table.caller: _SortingField.caller,
+ _Table.callee: _SortingField.callee,
};
final _sortingDirection = <_Table, _SortingDirection>{
- _Table.functions : _SortingDirection.descending,
- _Table.caller : _SortingDirection.descending,
- _Table.callee : _SortingDirection.descending,
+ _Table.functions: _SortingDirection.descending,
+ _Table.caller: _SortingDirection.descending,
+ _Table.callee: _SortingDirection.descending,
};
String _filter = '';
-
M.IsolateRef get isolate => _isolate;
M.NotificationRepository get notifications => _notifications;
M.IsolateSampleProfileRepository get profiles => _profiles;
M.VMRef get vm => _vm;
- factory CpuProfileTableElement(M.VM vm, M.IsolateRef isolate,
- M.EventRepository events,
- M.NotificationRepository notifications,
- M.IsolateSampleProfileRepository profiles,
- {RenderingQueue queue}) {
+ factory CpuProfileTableElement(
+ M.VM vm,
+ M.IsolateRef isolate,
+ M.EventRepository events,
+ M.NotificationRepository notifications,
+ M.IsolateSampleProfileRepository profiles,
+ {RenderingQueue queue}) {
assert(vm != null);
assert(isolate != null);
assert(events != null);
@@ -129,10 +117,9 @@
new NavVMMenuElement(_vm, _events, queue: _r.queue),
new NavIsolateMenuElement(_isolate, _events, queue: _r.queue),
navMenu('cpu profile (table)'),
- new NavRefreshElement(queue: _r.queue)
- ..onRefresh.listen(_refresh),
+ new NavRefreshElement(queue: _r.queue)..onRefresh.listen(_refresh),
new NavRefreshElement(label: 'Clear', queue: _r.queue)
- ..onRefresh.listen(_clearCpuProfile),
+ ..onRefresh.listen(_clearCpuProfile),
new NavNotifyElement(_notifications, queue: _r.queue)
]),
];
@@ -141,7 +128,7 @@
return;
}
content.add(new SampleBufferControlElement(_progress, _progressStream,
- showTag: false, queue: _r.queue));
+ showTag: false, queue: _r.queue));
if (_progress.status == M.SampleProfileLoadingStatus.loaded) {
content.add(new BRElement());
content.addAll(_createTables());
@@ -157,51 +144,50 @@
VirtualCollectionElement _callees;
List<Element> _createTables() {
- _functions = _functions ?? new VirtualCollectionElement(
- _createFunction,
- _updateFunction,
- createHeader: _createFunctionHeader,
- queue: _r.queue
- );
+ _functions = _functions ??
+ new VirtualCollectionElement(_createFunction, _updateFunction,
+ createHeader: _createFunctionHeader, queue: _r.queue);
_functions.items = _progress.profile.functions.toList()
- ..sort(_createSorter(_Table.functions));
+ ..sort(_createSorter(_Table.functions));
_functions.takeIntoView(_selected);
- _callers = _callers ?? new VirtualCollectionElement(
- _createCaller,
- _updateCaller,
- createHeader: _createCallerHeader,
- queue: _r.queue
- );
- _callees = _callees ?? new VirtualCollectionElement(
- _createCallee,
- _updateCallee,
- createHeader: _createCalleeHeader,
- queue: _r.queue
- );
+ _callers = _callers ??
+ new VirtualCollectionElement(_createCaller, _updateCaller,
+ createHeader: _createCallerHeader, queue: _r.queue);
+ _callees = _callees ??
+ new VirtualCollectionElement(_createCallee, _updateCallee,
+ createHeader: _createCalleeHeader, queue: _r.queue);
if (_selected != null) {
_callers.items = _selected.callers.keys.toList()
- ..sort(_createSorter(_Table.caller));
+ ..sort(_createSorter(_Table.caller));
_callees.items = _selected.callees.keys.toList()
- ..sort(_createSorter(_Table.callee));
+ ..sort(_createSorter(_Table.callee));
} else {
_callers.items = const [];
_callees.items = const [];
}
return [
- new DivElement()..classes = ['profile-trees']
+ new DivElement()
+ ..classes = ['profile-trees']
..children = [
- new DivElement()..classes = ['profile-trees-all']
+ new DivElement()
+ ..classes = ['profile-trees-all']
..children = [_functions],
- new DivElement()..classes = ['profile-trees-current']
+ new DivElement()
+ ..classes = ['profile-trees-current']
..children = [
- new DivElement()..classes = ['profile-trees-caller']
+ new DivElement()
+ ..classes = ['profile-trees-caller']
..children = [_callers],
- new DivElement()..classes = ['profile-trees-selected']
+ new DivElement()
+ ..classes = ['profile-trees-selected']
..children = _selected == null
? [new SpanElement()..text = 'No element selected']
- : [new FunctionRefElement(_isolate, _selected.function,
- queue : _r.queue)],
- new DivElement()..classes = ['profile-trees-callee']
+ : [
+ new FunctionRefElement(_isolate, _selected.function,
+ queue: _r.queue)
+ ],
+ new DivElement()
+ ..classes = ['profile-trees-callee']
..children = [_callees]
]
]
@@ -212,9 +198,11 @@
final element = new DivElement()
..classes = ['function-item']
..children = [
- new SpanElement()..classes = ['exclusive']
+ new SpanElement()
+ ..classes = ['exclusive']
..text = '0%',
- new SpanElement()..classes = ['inclusive']
+ new SpanElement()
+ ..classes = ['inclusive']
..text = '0%',
new SpanElement()..classes = ['name']
];
@@ -240,48 +228,41 @@
queue: _r.queue)..classes = ['name'];
}
- Element _createFunctionHeader() =>
- new DivElement()
- ..classes = ['function-item']
- ..children = [
- _createHeaderButton(const ['exclusive'], 'Execution(%)',
- _Table.functions,
- _SortingField.exclusive,
- _SortingDirection.descending),
- _createHeaderButton(const ['inclusive'], 'Stack(%)',
- _Table.functions,
- _SortingField.inclusive,
- _SortingDirection.descending),
- _createHeaderButton(const ['name'], 'Method',
- _Table.functions,
- _SortingField.method,
- _SortingDirection.ascending),
- ];
+ Element _createFunctionHeader() => new DivElement()
+ ..classes = ['function-item']
+ ..children = [
+ _createHeaderButton(const ['exclusive'], 'Execution(%)', _Table.functions,
+ _SortingField.exclusive, _SortingDirection.descending),
+ _createHeaderButton(const ['inclusive'], 'Stack(%)', _Table.functions,
+ _SortingField.inclusive, _SortingDirection.descending),
+ _createHeaderButton(const ['name'], 'Method', _Table.functions,
+ _SortingField.method, _SortingDirection.ascending),
+ ];
- void _setSorting(_Table table,
- _SortingField field,
- _SortingDirection defaultDirection) {
- if (_sortingField[table] == field) {
- switch (_sortingDirection[table]) {
- case _SortingDirection.descending:
- _sortingDirection[table] = _SortingDirection.ascending;
- break;
- case _SortingDirection.ascending:
- _sortingDirection[table] = _SortingDirection.descending;
- break;
- }
- } else {
- _sortingDirection[table] = defaultDirection;
- _sortingField[table] = field;
+ void _setSorting(
+ _Table table, _SortingField field, _SortingDirection defaultDirection) {
+ if (_sortingField[table] == field) {
+ switch (_sortingDirection[table]) {
+ case _SortingDirection.descending:
+ _sortingDirection[table] = _SortingDirection.ascending;
+ break;
+ case _SortingDirection.ascending:
+ _sortingDirection[table] = _SortingDirection.descending;
+ break;
}
- _r.dirty();
+ } else {
+ _sortingDirection[table] = defaultDirection;
+ _sortingField[table] = field;
}
+ _r.dirty();
+ }
Element _createCallee() {
final element = new DivElement()
..classes = ['function-item']
..children = [
- new SpanElement()..classes = ['inclusive']
+ new SpanElement()
+ ..classes = ['inclusive']
..text = '0%',
new SpanElement()..classes = ['name']
];
@@ -301,25 +282,21 @@
queue: _r.queue)..classes = ['name'];
}
- Element _createCalleeHeader() =>
- new DivElement()
- ..classes = ['function-item']
- ..children = [
- _createHeaderButton(const ['inclusive'], 'Callees(%)',
- _Table.callee,
- _SortingField.callee,
- _SortingDirection.descending),
- _createHeaderButton(const ['name'], 'Method',
- _Table.callee,
- _SortingField.method,
- _SortingDirection.ascending),
- ];
+ Element _createCalleeHeader() => new DivElement()
+ ..classes = ['function-item']
+ ..children = [
+ _createHeaderButton(const ['inclusive'], 'Callees(%)', _Table.callee,
+ _SortingField.callee, _SortingDirection.descending),
+ _createHeaderButton(const ['name'], 'Method', _Table.callee,
+ _SortingField.method, _SortingDirection.ascending),
+ ];
Element _createCaller() {
final element = new DivElement()
..classes = ['function-item']
..children = [
- new SpanElement()..classes = ['inclusive']
+ new SpanElement()
+ ..classes = ['inclusive']
..text = '0%',
new SpanElement()..classes = ['name']
];
@@ -339,51 +316,59 @@
queue: _r.queue)..classes = ['name'];
}
- Element _createCallerHeader() =>
- new DivElement()
- ..classes = ['function-item']
- ..children = [
- _createHeaderButton(const ['inclusive'], 'Callers(%)',
- _Table.caller,
- _SortingField.caller,
- _SortingDirection.descending),
- _createHeaderButton(const ['name'], 'Method',
- _Table.caller,
- _SortingField.method,
- _SortingDirection.ascending),
- ];
+ Element _createCallerHeader() => new DivElement()
+ ..classes = ['function-item']
+ ..children = [
+ _createHeaderButton(const ['inclusive'], 'Callers(%)', _Table.caller,
+ _SortingField.caller, _SortingDirection.descending),
+ _createHeaderButton(const ['name'], 'Method', _Table.caller,
+ _SortingField.method, _SortingDirection.ascending),
+ ];
- ButtonElement _createHeaderButton(List<String> classes,
- String text,
- _Table table,
- _SortingField field,
- _SortingDirection direction) =>
- new ButtonElement()..classes = classes
- ..text = _sortingField[table] != field ? text :
- _sortingDirection[table] == _SortingDirection.ascending
- ? '$text▼' : '$text▲'
- ..onClick.listen((_) => _setSorting(table, field, direction));
+ ButtonElement _createHeaderButton(List<String> classes, String text,
+ _Table table, _SortingField field, _SortingDirection direction) =>
+ new ButtonElement()
+ ..classes = classes
+ ..text = _sortingField[table] != field
+ ? text
+ : _sortingDirection[table] == _SortingDirection.ascending
+ ? '$text▼'
+ : '$text▲'
+ ..onClick.listen((_) => _setSorting(table, field, direction));
List<Element> _createTree() {
CpuProfileVirtualTreeElement tree;
return [
- new StackTraceTreeConfigElement(showMode: false,
- showDirection: false, mode: ProfileTreeMode.function,
- direction: M.ProfileTreeDirection.exclusive, filter: _filter,
- queue: _r.queue)
+ new StackTraceTreeConfigElement(
+ showMode: false,
+ showDirection: false,
+ mode: ProfileTreeMode.function,
+ direction: M.ProfileTreeDirection.exclusive,
+ filter: _filter,
+ queue: _r.queue)
..onFilterChange.listen((e) {
_filter = e.element.filter.trim();
tree.filters = _filter.isNotEmpty
- ? [_filterTree, (node) { return node.name.contains(_filter); }]
- : [_filterTree];
+ ? [
+ _filterTree,
+ (node) {
+ return node.name.contains(_filter);
+ }
+ ]
+ : [_filterTree];
}),
new BRElement(),
tree = new CpuProfileVirtualTreeElement(_isolate, _progress.profile,
- mode: ProfileTreeMode.function,
- direction: M.ProfileTreeDirection.exclusive,
- queue: _r.queue)
- ..filters = _filter.isNotEmpty
- ? [_filterTree, (node) { return node.name.contains(_filter); }]
+ mode: ProfileTreeMode.function,
+ direction: M.ProfileTreeDirection.exclusive,
+ queue: _r.queue)
+ ..filters = _filter.isNotEmpty
+ ? [
+ _filterTree,
+ (node) {
+ return node.name.contains(_filter);
+ }
+ ]
: [_filterTree]
];
}
@@ -432,8 +417,7 @@
getter = _getCallerT;
break;
case _SortingField.method:
- getter = (M.ProfileFunction s) =>
- M.getFunctionFullName(s.function);
+ getter = (M.ProfileFunction s) => M.getFunctionFullName(s.function);
break;
}
switch (_sortingDirection[table]) {
diff --git a/runtime/observatory/lib/src/elements/curly_block.dart b/runtime/observatory/lib/src/elements/curly_block.dart
index 54e0d3f..b320a9a 100644
--- a/runtime/observatory/lib/src/elements/curly_block.dart
+++ b/runtime/observatory/lib/src/elements/curly_block.dart
@@ -37,14 +37,15 @@
if (_expanded != value) _onToggle.add(new CurlyBlockToggleEvent(this));
_expanded = _r.checkAndReact(_expanded, value);
}
+
set disabled(bool value) => _disabled = _r.checkAndReact(_disabled, value);
set content(Iterable<Element> value) {
_content = value.toList();
_r.dirty();
}
- factory CurlyBlockElement({bool expanded: false, bool disabled: false,
- RenderingQueue queue}) {
+ factory CurlyBlockElement(
+ {bool expanded: false, bool disabled: false, RenderingQueue queue}) {
assert(expanded != null);
assert(disabled != null);
CurlyBlockElement e = document.createElement(tag.name);
@@ -58,11 +59,15 @@
CurlyBlockElement.created() : super.created();
@override
- void attached() { super.attached(); _r.enable(); }
+ void attached() {
+ super.attached();
+ _r.enable();
+ }
@override
void detached() {
- super.detached(); _r.disable(notify: true);
+ super.detached();
+ _r.disable(notify: true);
children = [];
}
@@ -75,18 +80,19 @@
}
void render() {
- List<Element> content = [
- new SpanElement()..text = '{'
- ];
+ List<Element> content = [new SpanElement()..text = '{'];
SpanElement label = new SpanElement()
..classes = disabled ? ['curly-block', 'disabled'] : ['curly-block']
- ..innerHtml = expanded ?
- ' ⊟ ' : ' ⊞ ';
+ ..innerHtml = expanded
+ ? ' ⊟ '
+ : ' ⊞ ';
if (disabled) {
content.add(label);
} else {
content.add(new AnchorElement()
- ..onClick.listen((_) { toggle(); })
+ ..onClick.listen((_) {
+ toggle();
+ })
..children = [label]);
}
if (expanded) {
diff --git a/runtime/observatory/lib/src/elements/debugger.dart b/runtime/observatory/lib/src/elements/debugger.dart
index dc5f443..8b91eff 100644
--- a/runtime/observatory/lib/src/elements/debugger.dart
+++ b/runtime/observatory/lib/src/elements/debugger.dart
@@ -34,8 +34,7 @@
abstract class DebuggerCommand extends Command {
ObservatoryDebugger debugger;
- DebuggerCommand(this.debugger, name, children)
- : super(name, children);
+ DebuggerCommand(this.debugger, name, children) : super(name, children);
String get helpShort;
String get helpLong;
@@ -44,9 +43,10 @@
// TODO(turnidge): Rewrite HelpCommand so that it is a general utility
// provided by the cli library.
class HelpCommand extends DebuggerCommand {
- HelpCommand(Debugger debugger) : super(debugger, 'help', [
- new HelpHotkeysCommand(debugger),
- ]);
+ HelpCommand(Debugger debugger)
+ : super(debugger, 'help', [
+ new HelpHotkeysCommand(debugger),
+ ]);
String _nameAndAlias(Command cmd) {
if (cmd.alias == null) {
@@ -65,7 +65,7 @@
con.print('List of commands:\n');
for (var command in commands) {
con.print('${_nameAndAlias(command).padRight(12)} '
- '- ${command.helpShort}');
+ '- ${command.helpShort}');
}
con.print(
"\nFor more information on a specific command type 'help <command>'\n"
@@ -101,7 +101,7 @@
con.print('Subcommands:\n');
for (var subCommand in subCommands) {
con.print(' ${subCommand.fullName.padRight(16)} '
- '- ${subCommand.helpShort}');
+ '- ${subCommand.helpShort}');
}
con.print('');
}
@@ -116,7 +116,8 @@
return new Future.value(result);
}
- String helpShort = 'List commands or provide details about a specific command';
+ String helpShort =
+ 'List commands or provide details about a specific command';
String helpLong =
'List commands or provide details about a specific command.\n'
@@ -131,28 +132,27 @@
Future run(List<String> args) {
var con = debugger.console;
con.print("List of hotkeys:\n"
- "\n"
- "[TAB] - complete a command\n"
- "[Up Arrow] - history previous\n"
- "[Down Arrow] - history next\n"
- "\n"
- "[Page Up] - move up one frame\n"
- "[Page Down] - move down one frame\n"
- "\n"
- "[F7] - continue execution of the current isolate\n"
- "[Ctrl ;] - pause execution of the current isolate\n"
- "\n"
- "[F8] - toggle breakpoint at current location\n"
- "[F9] - next\n"
- "[F10] - step\n"
- "\n");
+ "\n"
+ "[TAB] - complete a command\n"
+ "[Up Arrow] - history previous\n"
+ "[Down Arrow] - history next\n"
+ "\n"
+ "[Page Up] - move up one frame\n"
+ "[Page Down] - move down one frame\n"
+ "\n"
+ "[F7] - continue execution of the current isolate\n"
+ "[Ctrl ;] - pause execution of the current isolate\n"
+ "\n"
+ "[F8] - toggle breakpoint at current location\n"
+ "[F9] - next\n"
+ "[F10] - step\n"
+ "\n");
return new Future.value(null);
}
String helpShort = 'Provide a list of hotkeys';
- String helpLong =
- 'Provide a list of key hotkeys.\n'
+ String helpLong = 'Provide a list of key hotkeys.\n'
'\n'
'Syntax: help hotkeys\n';
}
@@ -172,20 +172,19 @@
return;
}
var expression = args.join('');
- var response = await debugger.isolate.evalFrame(debugger.currentFrame,
- expression);
+ var response =
+ await debugger.isolate.evalFrame(debugger.currentFrame, expression);
if (response is S.DartError) {
debugger.console.print(response.message);
} else {
- debugger.console.print('= ', newline:false);
+ debugger.console.print('= ', newline: false);
debugger.console.printRef(debugger.isolate, response, debugger.instances);
}
}
String helpShort = 'Evaluate and print an expression in the current frame';
- String helpLong =
- 'Evaluate and print an expression in the current frame.\n'
+ String helpLong = 'Evaluate and print an expression in the current frame.\n'
'\n'
'Syntax: print <expression>\n'
' p <expression>\n';
@@ -217,8 +216,7 @@
String helpShort = 'Move down one or more frames (hotkey: [Page Down])';
- String helpLong =
- 'Move down one or more frames.\n'
+ String helpLong = 'Move down one or more frames.\n'
'\n'
'Hotkey: [Page Down]\n'
'\n'
@@ -252,8 +250,7 @@
String helpShort = 'Move up one or more frames (hotkey: [Page Up])';
- String helpLong =
- 'Move up one or more frames.\n'
+ String helpLong = 'Move up one or more frames.\n'
'\n'
'Hotkey: [Page Up]\n'
'\n'
@@ -289,8 +286,7 @@
String helpShort = 'Set the current frame';
- String helpLong =
- 'Set the current frame.\n'
+ String helpLong = 'Set the current frame.\n'
'\n'
'Syntax: frame <number>\n'
' f <count>\n';
@@ -305,8 +301,7 @@
String helpShort = 'Pause the isolate (hotkey: [Ctrl ;])';
- String helpLong =
- 'Pause the isolate.\n'
+ String helpLong = 'Pause the isolate.\n'
'\n'
'Hotkey: [Ctrl ;]\n'
'\n'
@@ -324,8 +319,7 @@
String helpShort = 'Resume execution of the isolate (hotkey: [F7])';
- String helpLong =
- 'Continue running the isolate.\n'
+ String helpLong = 'Continue running the isolate.\n'
'\n'
'Hotkey: [F7]\n'
'\n'
@@ -362,8 +356,7 @@
return debugger.syncNext();
}
- String helpShort =
- 'Run until return/unwind to current activation.';
+ String helpShort = 'Run until return/unwind to current activation.';
String helpLong =
'Continue running the isolate until control returns to the current '
@@ -379,8 +372,7 @@
return debugger.asyncNext();
}
- String helpShort =
- 'Step over await or yield';
+ String helpShort = 'Step over await or yield';
String helpLong =
'Continue running the isolate until control returns to the current '
@@ -422,8 +414,7 @@
String helpShort = 'Clear the console';
- String helpLong =
- 'Clear the console.\n'
+ String helpLong = 'Clear the console.\n'
'\n'
'Syntax: cls\n';
}
@@ -433,8 +424,7 @@
Future run(List<String> args) async {
if (args.length == 0) {
- debugger.console.print(
- 'Current log level: '
+ debugger.console.print('Current log level: '
'${debugger._consolePrinter._minimumLogLevel.name}');
return new Future.value(null);
}
@@ -476,8 +466,7 @@
return new Future.value(result);
}
- String helpShort =
- 'Control which log messages are displayed';
+ String helpShort = 'Control which log messages are displayed';
String helpLong =
'Get or set the minimum log level that should be displayed.\n'
@@ -504,11 +493,11 @@
if (debugger.isolatePaused()) {
var event = debugger.isolate.pauseEvent;
if (event is M.PauseStartEvent) {
- debugger.console.print(
- "Type 'continue' [F7] or 'step' [F10] to start the isolate");
+ debugger.console
+ .print("Type 'continue' [F7] or 'step' [F10] to start the isolate");
return new Future.value(null);
}
- if (event is M.PauseExitEvent) {
+ if (event is M.PauseExitEvent) {
debugger.console.print("Type 'continue' [F7] to exit the isolate");
return new Future.value(null);
}
@@ -529,19 +518,22 @@
}
class SetCommand extends DebuggerCommand {
- SetCommand(Debugger debugger)
- : super(debugger, 'set', []);
+ SetCommand(Debugger debugger) : super(debugger, 'set', []);
static var _boeValues = ['All', 'None', 'Unhandled'];
static var _boolValues = ['false', 'true'];
static var _options = {
- 'break-on-exception': [_boeValues,
- _setBreakOnException,
- (debugger, _) => debugger.breakOnException],
- 'up-is-down': [_boolValues,
- _setUpIsDown,
- (debugger, _) => debugger.upIsDown],
+ 'break-on-exception': [
+ _boeValues,
+ _setBreakOnException,
+ (debugger, _) => debugger.breakOnException
+ ],
+ 'up-is-down': [
+ _boolValues,
+ _setUpIsDown,
+ (debugger, _) => debugger.upIsDown
+ ],
};
static Future _setBreakOnException(debugger, name, value) async {
@@ -630,11 +622,9 @@
return new Future.value(result);
}
- String helpShort =
- 'Set a debugger option';
+ String helpShort = 'Set a debugger option';
- String helpLong =
- 'Set a debugger option.\n'
+ String helpLong = 'Set a debugger option.\n'
'\n'
'Known options:\n'
' break-on-exception # Should the debugger break on exceptions?\n'
@@ -661,7 +651,7 @@
if (loc.function != null) {
try {
await debugger.isolate.addBreakpointAtEntry(loc.function);
- } on S.ServerRpcException catch(e) {
+ } on S.ServerRpcException catch (e) {
if (e.code == S.ServerRpcException.kCannotAddBreakpoint) {
debugger.console.print('Unable to set breakpoint at ${loc}');
} else {
@@ -673,13 +663,13 @@
var script = loc.script;
await script.load();
if (loc.line < 1 || loc.line > script.lines.length) {
- debugger.console.print(
- 'line number must be in range [1,${script.lines.length}]');
+ debugger.console
+ .print('line number must be in range [1,${script.lines.length}]');
return;
}
try {
await debugger.isolate.addBreakpoint(script, loc.line, loc.col);
- } on S.ServerRpcException catch(e) {
+ } on S.ServerRpcException catch (e) {
if (e.code == S.ServerRpcException.kCannotAddBreakpoint) {
debugger.console.print('Unable to set breakpoint at ${loc}');
} else {
@@ -703,8 +693,7 @@
String helpShort = 'Add a breakpoint by source location or function name'
' (hotkey: [F8])';
- String helpLong =
- 'Add a breakpoint by source location or function name.\n'
+ String helpLong = 'Add a breakpoint by source location or function name.\n'
'\n'
'Hotkey: [F8]\n'
'\n'
@@ -747,16 +736,15 @@
return;
}
if (loc.function != null) {
- debugger.console.print(
- 'Ignoring breakpoint at $loc: '
+ debugger.console.print('Ignoring breakpoint at $loc: '
'Clearing function breakpoints not yet implemented');
return;
}
var script = loc.script;
if (loc.line < 1 || loc.line > script.lines.length) {
- debugger.console.print(
- 'line number must be in range [1,${script.lines.length}]');
+ debugger.console
+ .print('line number must be in range [1,${script.lines.length}]');
return;
}
var lineInfo = script.getLine(loc.line);
@@ -791,8 +779,7 @@
String helpShort = 'Remove a breakpoint by source location or function name'
' (hotkey: [F8])';
- String helpLong =
- 'Remove a breakpoint by source location or function name.\n'
+ String helpLong = 'Remove a breakpoint by source location or function name.\n'
'\n'
'Hotkey: [F8]\n'
'\n'
@@ -854,8 +841,7 @@
String helpShort = 'Remove a breakpoint by breakpoint id';
- String helpLong =
- 'Remove a breakpoint by breakpoint id.\n'
+ String helpLong = 'Remove a breakpoint by breakpoint id.\n'
'\n'
'Syntax: delete <bp-id>\n'
' delete <bp-id> <bp-id> ...\n';
@@ -875,19 +861,16 @@
var bpId = bpt.number;
var locString = await bpt.location.toUserString();
if (!bpt.resolved) {
- debugger.console.print(
- 'Future breakpoint ${bpId} at ${locString}');
+ debugger.console.print('Future breakpoint ${bpId} at ${locString}');
} else {
- debugger.console.print(
- 'Breakpoint ${bpId} at ${locString}');
+ debugger.console.print('Breakpoint ${bpId} at ${locString}');
}
}
}
String helpShort = 'List all breakpoints';
- String helpLong =
- 'List all breakpoints.\n'
+ String helpLong = 'List all breakpoints.\n'
'\n'
'Syntax: info breakpoints\n';
}
@@ -906,18 +889,18 @@
String helpShort = 'Show current frame';
- String helpLong =
- 'Show current frame.\n'
+ String helpLong = 'Show current frame.\n'
'\n'
'Syntax: info frame\n';
}
class IsolateCommand extends DebuggerCommand {
- IsolateCommand(Debugger debugger) : super(debugger, 'isolate', [
- new IsolateListCommand(debugger),
- new IsolateNameCommand(debugger),
- new IsolateReloadCommand(debugger),
- ]) {
+ IsolateCommand(Debugger debugger)
+ : super(debugger, 'isolate', [
+ new IsolateListCommand(debugger),
+ new IsolateNameCommand(debugger),
+ new IsolateReloadCommand(debugger),
+ ]) {
alias = 'i';
}
@@ -927,7 +910,7 @@
return new Future.value(null);
}
var arg = args[0].trim();
- var num = int.parse(arg, onError:(_) => null);
+ var num = int.parse(arg, onError: (_) => null);
var candidate;
for (var isolate in debugger.vm.isolates) {
@@ -936,8 +919,7 @@
break;
} else if (arg == isolate.name) {
if (candidate != null) {
- debugger.console.print(
- "Isolate identifier '${arg}' is ambiguous: "
+ debugger.console.print("Isolate identifier '${arg}' is ambiguous: "
'use the isolate number instead');
return new Future.value(null);
}
@@ -975,10 +957,10 @@
}
return new Future.value(result);
}
+
String helpShort = 'Switch, list, rename, or reload isolates';
- String helpLong =
- 'Switch the current isolate.\n'
+ String helpLong = 'Switch the current isolate.\n'
'\n'
'Syntax: isolate <number>\n'
' isolate <name>\n';
@@ -1001,8 +983,7 @@
Future run(List<String> args) async {
if (debugger.vm == null) {
- debugger.console.print(
- "Internal error: vm has not been set");
+ debugger.console.print("Internal error: vm has not been set");
return;
}
@@ -1020,26 +1001,25 @@
maxNameLen = max(maxNameLen, isolate.name.length);
}
debugger.console.print("${'ID'.padLeft(maxIdLen, ' ')} "
- "${'ORIGIN'.padLeft(maxIdLen, ' ')} "
- "${'NAME'.padRight(maxNameLen, ' ')} "
- "${'STATE'.padRight(maxRunStateLen, ' ')} "
- "CURRENT");
+ "${'ORIGIN'.padLeft(maxIdLen, ' ')} "
+ "${'NAME'.padRight(maxNameLen, ' ')} "
+ "${'STATE'.padRight(maxRunStateLen, ' ')} "
+ "CURRENT");
for (var isolate in debugger.vm.isolates) {
String current = (isolate == debugger.isolate ? '*' : '');
- debugger.console.print(
- "${isolate.number.toString().padLeft(maxIdLen, ' ')} "
- "${isolate.originNumber.toString().padLeft(maxIdLen, ' ')} "
- "${isolate.name.padRight(maxNameLen, ' ')} "
- "${_isolateRunState(isolate).padRight(maxRunStateLen, ' ')} "
- "${current}");
+ debugger.console
+ .print("${isolate.number.toString().padLeft(maxIdLen, ' ')} "
+ "${isolate.originNumber.toString().padLeft(maxIdLen, ' ')} "
+ "${isolate.name.padRight(maxNameLen, ' ')} "
+ "${_isolateRunState(isolate).padRight(maxRunStateLen, ' ')} "
+ "${current}");
}
debugger.console.newline();
}
String helpShort = 'List all isolates';
- String helpLong =
- 'List all isolates.\n'
+ String helpLong = 'List all isolates.\n'
'\n'
'Syntax: isolate list\n';
}
@@ -1057,8 +1037,7 @@
String helpShort = 'Rename the current isolate';
- String helpLong =
- 'Rename the current isolate.\n'
+ String helpLong = 'Rename the current isolate.\n'
'\n'
'Syntax: isolate name <name>\n';
}
@@ -1079,16 +1058,17 @@
String helpShort = 'Reload the sources for the current isolate.';
- String helpLong =
- 'Reload the sources for the current isolate.\n'
+ String helpLong = 'Reload the sources for the current isolate.\n'
'\n'
'Syntax: reload\n';
}
class InfoCommand extends DebuggerCommand {
- InfoCommand(Debugger debugger) : super(debugger, 'info', [
- new InfoBreakpointsCommand(debugger),
- new InfoFrameCommand(debugger)]);
+ InfoCommand(Debugger debugger)
+ : super(debugger, 'info', [
+ new InfoBreakpointsCommand(debugger),
+ new InfoFrameCommand(debugger)
+ ]);
Future run(List<String> args) {
debugger.console.print("'info' expects a subcommand (see 'help info')");
@@ -1097,8 +1077,7 @@
String helpShort = 'Show information on a variety of topics';
- String helpLong =
- 'Show information on a variety of topics.\n'
+ String helpLong = 'Show information on a variety of topics.\n'
'\n'
'Syntax: info <subcommand>\n';
}
@@ -1112,26 +1091,26 @@
String helpShort = 'Refresh isolate stack';
- String helpLong =
- 'Refresh isolate stack.\n'
+ String helpLong = 'Refresh isolate stack.\n'
'\n'
'Syntax: refresh stack\n';
}
class RefreshCommand extends DebuggerCommand {
- RefreshCommand(Debugger debugger) : super(debugger, 'refresh', [
- new RefreshStackCommand(debugger),
- ]);
+ RefreshCommand(Debugger debugger)
+ : super(debugger, 'refresh', [
+ new RefreshStackCommand(debugger),
+ ]);
Future run(List<String> args) {
- debugger.console.print("'refresh' expects a subcommand (see 'help refresh')");
+ debugger.console
+ .print("'refresh' expects a subcommand (see 'help refresh')");
return new Future.value(null);
}
String helpShort = 'Refresh debugging information of various sorts';
- String helpLong =
- 'Refresh debugging information of various sorts.\n'
+ String helpLong = 'Refresh debugging information of various sorts.\n'
'\n'
'Syntax: refresh <subcommand>\n';
}
@@ -1160,21 +1139,20 @@
}
debugger.console.print("${'ADDRESS'.padRight(maxAddrLen, ' ')} "
- "${'NAME'.padRight(maxNameLen, ' ')} "
- "CURRENT");
+ "${'NAME'.padRight(maxNameLen, ' ')} "
+ "CURRENT");
for (var vm in vmList) {
String current = (vm == debugger.vm ? '*' : '');
- debugger.console.print(
- "${vm.target.networkAddress.padRight(maxAddrLen, ' ')} "
- "${vm.name.padRight(maxNameLen, ' ')} "
- "${current}");
+ debugger.console
+ .print("${vm.target.networkAddress.padRight(maxAddrLen, ' ')} "
+ "${vm.name.padRight(maxNameLen, ' ')} "
+ "${current}");
}
}
String helpShort = 'List all connected Dart virtual machines';
- String helpLong =
- 'List all connected Dart virtual machines..\n'
+ String helpLong = 'List all connected Dart virtual machines..\n'
'\n'
'Syntax: vm list\n';
}
@@ -1196,8 +1174,7 @@
String helpShort = 'Rename the current Dart virtual machine';
- String helpLong =
- 'Rename the current Dart virtual machine.\n'
+ String helpLong = 'Rename the current Dart virtual machine.\n'
'\n'
'Syntax: vm name <name>\n';
}
@@ -1224,18 +1201,18 @@
String helpShort = 'Restart a Dart virtual machine';
- String helpLong =
- 'Restart a Dart virtual machine.\n'
+ String helpLong = 'Restart a Dart virtual machine.\n'
'\n'
'Syntax: vm restart\n';
}
class VmCommand extends DebuggerCommand {
- VmCommand(Debugger debugger) : super(debugger, 'vm', [
- new VmListCommand(debugger),
- new VmNameCommand(debugger),
- new VmRestartCommand(debugger),
- ]);
+ VmCommand(Debugger debugger)
+ : super(debugger, 'vm', [
+ new VmListCommand(debugger),
+ new VmNameCommand(debugger),
+ new VmRestartCommand(debugger),
+ ]);
Future run(List<String> args) async {
debugger.console.print("'vm' expects a subcommand (see 'help vm')");
@@ -1243,8 +1220,7 @@
String helpShort = 'Manage a Dart virtual machine';
- String helpLong =
- 'Manage a Dart virtual machine.\n'
+ String helpLong = 'Manage a Dart virtual machine.\n'
'\n'
'Syntax: vm <subcommand>\n';
}
@@ -1271,7 +1247,7 @@
// any pending output, even if it is not newline-terminated.
if ((_savedIsolate != null && isolateName != _savedIsolate) ||
(_savedStream != null && streamName != _savedStream)) {
- flush();
+ flush();
}
String data;
bool hasNewline;
@@ -1283,7 +1259,7 @@
hasNewline = data.endsWith('\n');
}
if (_savedLine != null) {
- data = _savedLine + data;
+ data = _savedLine + data;
_savedIsolate = null;
_savedStream = null;
_savedLine = null;
@@ -1333,7 +1309,7 @@
DebuggerStackElement stackElement;
S.ServiceMap stack;
final S.Isolate isolate;
- String breakOnException = "none"; // Last known setting.
+ String breakOnException = "none"; // Last known setting.
int get currentFrame => _currentFrame;
@@ -1346,6 +1322,7 @@
stackElement.setCurrentFrame(value);
}
}
+
int _currentFrame = null;
bool get upIsDown => _upIsDown;
@@ -1353,6 +1330,7 @@
settings.set('up-is-down', value);
_upIsDown = value;
}
+
bool _upIsDown;
void upFrame(int count) {
@@ -1378,28 +1356,28 @@
ObservatoryDebugger(this.isolate) {
_loadSettings();
cmd = new RootCommand([
- new AsyncNextCommand(this),
- new BreakCommand(this),
- new ClearCommand(this),
- new ClsCommand(this),
- new ContinueCommand(this),
- new DeleteCommand(this),
- new DownCommand(this),
- new FinishCommand(this),
- new FrameCommand(this),
- new HelpCommand(this),
- new InfoCommand(this),
- new IsolateCommand(this),
- new LogCommand(this),
- new PauseCommand(this),
- new PrintCommand(this),
- new RefreshCommand(this),
- new SetCommand(this),
- new SmartNextCommand(this),
- new StepCommand(this),
- new SyncNextCommand(this),
- new UpCommand(this),
- new VmCommand(this),
+ new AsyncNextCommand(this),
+ new BreakCommand(this),
+ new ClearCommand(this),
+ new ClsCommand(this),
+ new ContinueCommand(this),
+ new DeleteCommand(this),
+ new DownCommand(this),
+ new FinishCommand(this),
+ new FrameCommand(this),
+ new HelpCommand(this),
+ new InfoCommand(this),
+ new IsolateCommand(this),
+ new LogCommand(this),
+ new PauseCommand(this),
+ new PrintCommand(this),
+ new RefreshCommand(this),
+ new SetCommand(this),
+ new SmartNextCommand(this),
+ new StepCommand(this),
+ new SyncNextCommand(this),
+ new UpCommand(this),
+ new VmCommand(this),
], _history);
_consolePrinter = new _ConsoleStreamPrinter(this);
}
@@ -1412,11 +1390,11 @@
void init() {
console.printBold('Debugging isolate isolate ${isolate.number} '
- '\'${isolate.name}\' ');
+ '\'${isolate.name}\' ');
console.printBold('Type \'h\' for help');
// Wait a bit and if polymer still hasn't set up the isolate,
// report this to the user.
- new Timer(const Duration(seconds:1), () {
+ new Timer(const Duration(seconds: 1), () {
if (isolate == null) {
reportStatus();
}
@@ -1471,7 +1449,7 @@
void warnOutOfDate() {
// Wait a bit, then tell the user that the stack may be out of date.
- new Timer(const Duration(seconds:2), () {
+ new Timer(const Duration(seconds: 2), () {
if (!isolatePaused()) {
stackElement.isSampled = true;
}
@@ -1528,18 +1506,18 @@
}
console.print(error.message);
console.newline();
- if (event is M.PauseExceptionEvent &&
+ if (event is M.PauseExceptionEvent &&
(error.exception.isStackOverflowError ||
- error.exception.isOutOfMemoryError)) {
+ error.exception.isOutOfMemoryError)) {
console.printBold(
'When an unhandled stack overflow or OOM exception occurs, the VM '
'has run out of memory and cannot keep the stack alive while '
'paused.');
} else {
console.printBold("Type 'set break-on-exception Unhandled' to pause the"
- " isolate when an unhandled exception occurs.");
+ " isolate when an unhandled exception occurs.");
console.printBold("You can make this the default by running with "
- "--pause-isolates-on-unhandled-exceptions");
+ "--pause-isolates-on-unhandled-exceptions");
}
}
@@ -1547,17 +1525,14 @@
if (event is M.NoneEvent) {
console.print("Paused until embedder makes the isolate runnable.");
} else if (event is M.PauseStartEvent) {
- console.print(
- "Paused at isolate start "
+ console.print("Paused at isolate start "
"(type 'continue' [F7] or 'step' [F10] to start the isolate')");
} else if (event is M.PauseExitEvent) {
- console.print(
- "Paused at isolate exit "
+ console.print("Paused at isolate exit "
"(type 'continue' or [F7] to exit the isolate')");
_reportIsolateError(isolate, event);
} else if (event is M.PauseExceptionEvent) {
- console.print(
- "Paused at an unhandled exception "
+ console.print("Paused at an unhandled exception "
"(type 'continue' or [F7] to exit the isolate')");
_reportIsolateError(isolate, event);
} else if (stack['frames'].length > 0) {
@@ -1566,15 +1541,14 @@
script.load().then((_) {
var line = script.tokenToLine(frame.location.tokenPos);
var col = script.tokenToCol(frame.location.tokenPos);
- if ((event is M.PauseBreakpointEvent) &&
- (event.breakpoint != null)) {
- var bpId = event.breakpoint.number;
- console.print('Paused at breakpoint ${bpId} at '
- '${script.name}:${line}:${col}');
+ if ((event is M.PauseBreakpointEvent) && (event.breakpoint != null)) {
+ var bpId = event.breakpoint.number;
+ console.print('Paused at breakpoint ${bpId} at '
+ '${script.name}:${line}:${col}');
} else if ((event is M.PauseExceptionEvent) &&
- (event.exception != null)) {
+ (event.exception != null)) {
console.print('Paused due to exception at '
- '${script.name}:${line}:${col}');
+ '${script.name}:${line}:${col}');
// This seems to be missing if we are paused-at-exception after
// paused-at-isolate-exit. Maybe we shutdown part of the debugger too
// soon?
@@ -1585,7 +1559,7 @@
});
} else {
console.print("Paused in message loop (type 'continue' or [F7] "
- "to resume processing messages)");
+ "to resume processing messages)");
}
}
@@ -1611,16 +1585,14 @@
var bpId = bpt.number;
var locString = await bpt.location.toUserString();
if (bpt.resolved) {
- console.print(
- 'Breakpoint ${bpId} ${verb} at ${locString}');
+ console.print('Breakpoint ${bpId} ${verb} at ${locString}');
} else {
- console.print(
- 'Future breakpoint ${bpId} ${verb} at ${locString}');
+ console.print('Future breakpoint ${bpId} ${verb} at ${locString}');
}
}
void onEvent(S.ServiceEvent event) {
- switch(event.kind) {
+ switch (event.kind) {
case S.ServiceEvent.kVMUpdate:
var vm = event.owner;
console.print("VM ${vm.target.networkAddress} renamed to '${vm.name}'");
@@ -1629,8 +1601,7 @@
case S.ServiceEvent.kIsolateStart:
{
var iso = event.owner;
- console.print(
- "Isolate ${iso.number} '${iso.name}' has been created");
+ console.print("Isolate ${iso.number} '${iso.name}' has been created");
}
break;
@@ -1639,7 +1610,7 @@
var iso = event.owner;
if (iso == isolate) {
console.print("The current isolate ${iso.number} '${iso.name}' "
- "has exited");
+ "has exited");
var isolates = vm.isolates;
if (isolates.length > 0) {
var newIsolate = isolates.first;
@@ -1648,8 +1619,7 @@
new AnchorElement(href: Uris.vm()).click();
}
} else {
- console.print(
- "Isolate ${iso.number} '${iso.name}' has exited");
+ console.print("Isolate ${iso.number} '${iso.name}' has exited");
}
}
break;
@@ -1790,7 +1760,7 @@
}).catchError((e, s) {
if (e is S.NetworkRpcException) {
console.printRed('Unable to execute command because the connection '
- 'to the VM has been closed');
+ 'to the VM has been closed');
} else {
if (s != null) {
console.printRed('Internal error: $e\n$s');
@@ -1821,8 +1791,8 @@
Future resume() {
if (isolatePaused()) {
return isolate.resume().then((_) {
- warnOutOfDate();
- });
+ warnOutOfDate();
+ });
} else {
console.print('The program must be paused');
return new Future.value(null);
@@ -1851,7 +1821,6 @@
return new Future.value(null);
}
-
Future smartNext() async {
if (isolatePaused()) {
var event = isolate.pauseEvent;
@@ -1882,7 +1851,8 @@
if (isolatePaused()) {
var event = isolate.pauseEvent;
if (event is M.PauseStartEvent) {
- console.print("Type 'continue' [F7] or 'step' [F10] to start the isolate");
+ console
+ .print("Type 'continue' [F7] or 'step' [F10] to start the isolate");
return null;
}
if (event is M.PauseExitEvent) {
@@ -1911,14 +1881,14 @@
}
}
-class DebuggerPageElement extends HtmlElement implements Renderable {
- static const tag = const Tag<DebuggerPageElement>('debugger-page',
- dependencies: const [
- NavTopMenuElement.tag,
- NavVMMenuElement.tag,
- NavIsolateMenuElement.tag,
- NavNotifyElement.tag,
- ]);
+class DebuggerPageElement extends HtmlElement implements Renderable {
+ static const tag =
+ const Tag<DebuggerPageElement>('debugger-page', dependencies: const [
+ NavTopMenuElement.tag,
+ NavVMMenuElement.tag,
+ NavIsolateMenuElement.tag,
+ NavNotifyElement.tag,
+ ]);
S.Isolate _isolate;
ObservatoryDebugger _debugger;
@@ -1926,10 +1896,8 @@
M.ScriptRepository _scripts;
M.EventRepository _events;
- factory DebuggerPageElement(S.Isolate isolate,
- M.InstanceRepository instances,
- M.ScriptRepository scripts,
- M.EventRepository events) {
+ factory DebuggerPageElement(S.Isolate isolate, M.InstanceRepository instances,
+ M.ScriptRepository scripts, M.EventRepository events) {
assert(isolate != null);
assert(instances != null);
assert(scripts != null);
@@ -1965,14 +1933,15 @@
super.attached();
final stackDiv = new DivElement()..classes = ['stack'];
- final stackElement = new DebuggerStackElement(_isolate, _debugger, stackDiv,
- _instances, _scripts,
- _events);
+ final stackElement = new DebuggerStackElement(
+ _isolate, _debugger, stackDiv, _instances, _scripts, _events);
stackDiv.children = [stackElement];
- final consoleDiv = new DivElement()..classes = ['console']
+ final consoleDiv = new DivElement()
+ ..classes = ['console']
..children = [consoleElement];
final commandElement = new DebuggerInputElement(_isolate, _debugger);
- final commandDiv = new DivElement()..classes = ['commandline']
+ final commandDiv = new DivElement()
+ ..classes = ['commandline']
..children = [commandElement];
children = [
@@ -1981,10 +1950,11 @@
new NavVMMenuElement(app.vm, app.events, queue: app.queue),
new NavIsolateMenuElement(_isolate, app.events, queue: app.queue),
navMenu('debugger'),
- new NavNotifyElement(app.notifications, notifyOnPause: false,
- queue: app.queue)
+ new NavNotifyElement(app.notifications,
+ notifyOnPause: false, queue: app.queue)
]),
- new DivElement()..classes = ['variable']
+ new DivElement()
+ ..classes = ['variable']
..children = [
stackDiv,
new DivElement()
@@ -2032,7 +2002,7 @@
_logSubscriptionFuture =
app.vm.listenEventStream(S.Isolate.kLoggingStream, _debugger.onEvent);
// Turn on the periodic poll timer for this page.
- _timer = new Timer.periodic(const Duration(milliseconds:100), (_) {
+ _timer = new Timer.periodic(const Duration(milliseconds: 100), (_) {
_debugger.flushStdio();
});
@@ -2048,6 +2018,11 @@
}
@override
+ void render() {
+ /* nothing to do */
+ }
+
+ @override
void detached() {
_timer.cancel();
children = const [];
@@ -2082,6 +2057,7 @@
_isSampled.classes.toggle('hidden');
}
}
+
DivElement _hasStack;
bool get hasStack => _hasStack.classes.contains('hidden');
set hasStack(bool value) {
@@ -2089,6 +2065,7 @@
_hasStack.classes.toggle('hidden');
}
}
+
DivElement _hasMessages;
bool get hasMessages => _hasMessages.classes.contains('hidden');
set hasMessages(bool value) {
@@ -2096,17 +2073,19 @@
_hasMessages.classes.toggle('hidden');
}
}
+
UListElement _frameList;
UListElement _messageList;
int currentFrame;
ObservatoryDebugger _debugger;
- factory DebuggerStackElement(S.Isolate isolate,
- ObservatoryDebugger debugger,
- Element scroller,
- M.InstanceRepository instances,
- M.ScriptRepository scripts,
- M.EventRepository events) {
+ factory DebuggerStackElement(
+ S.Isolate isolate,
+ ObservatoryDebugger debugger,
+ Element scroller,
+ M.InstanceRepository instances,
+ M.ScriptRepository scripts,
+ M.EventRepository events) {
assert(isolate != null);
assert(debugger != null);
assert(scroller != null);
@@ -2124,11 +2103,12 @@
var btnPause;
var btnRefresh;
e.children = [
- e._isSampled = new DivElement()..classes = ['sampledMessage', 'hidden']
+ e._isSampled = new DivElement()
+ ..classes = ['sampledMessage', 'hidden']
..children = [
new SpanElement()
..text = 'The program is not paused. '
- 'The stack trace below may be out of date.',
+ 'The stack trace below may be out of date.',
new BRElement(),
new BRElement(),
btnPause = new ButtonElement()
@@ -2137,8 +2117,7 @@
btnPause.disabled = true;
try {
await debugger.isolate.pause();
- }
- finally {
+ } finally {
btnPause.disabled = false;
}
}),
@@ -2148,8 +2127,7 @@
btnRefresh.disabled = true;
try {
await debugger.refreshStack();
- }
- finally {
+ } finally {
btnRefresh.disabled = false;
}
}),
@@ -2157,25 +2135,27 @@
new BRElement(),
new HRElement()..classes = ['splitter']
],
- e._hasStack = new DivElement()..classes = ['noStack', 'hidden']
+ e._hasStack = new DivElement()
+ ..classes = ['noStack', 'hidden']
..text = 'No stack',
e._frameList = new UListElement()..classes = ['list-group'],
new HRElement(),
- e._hasMessages = new DivElement()..classes = ['noMessages', 'hidden']
+ e._hasMessages = new DivElement()
+ ..classes = ['noMessages', 'hidden']
..text = 'No pending messages',
e._messageList = new UListElement()..classes = ['messageList']
];
return e;
}
+ void render() {
+ /* nothing to do */
+ }
+
_addFrame(List frameList, S.Frame frameInfo) {
- final frameElement = new DebuggerFrameElement(_isolate,
- frameInfo,
- _scroller,
- _instances,
- _scripts,
- _events,
- queue: app.queue);
+ final frameElement = new DebuggerFrameElement(
+ _isolate, frameInfo, _scroller, _instances, _scripts, _events,
+ queue: app.queue);
if (frameInfo.index == currentFrame) {
frameElement.setCurrent(true);
@@ -2191,12 +2171,9 @@
}
_addMessage(List messageList, S.ServiceMessage messageInfo) {
- final messageElement = new DebuggerMessageElement(_isolate,
- messageInfo,
- _instances,
- _scripts,
- _events,
- queue: app.queue);
+ final messageElement = new DebuggerMessageElement(
+ _isolate, messageInfo, _instances, _scripts, _events,
+ queue: app.queue);
var li = new LIElement();
li.classes.add('list-group-item');
@@ -2242,7 +2219,7 @@
if (frameElements.length < newFrames.length) {
// Add new frames to the top of stack.
newCount = newFrames.length - frameElements.length;
- for (int i = newCount-1; i >= 0; i--) {
+ for (int i = newCount - 1; i >= 0; i--) {
_addFrame(frameElements, newFrames[i]);
}
}
@@ -2352,13 +2329,14 @@
});
}
- factory DebuggerFrameElement(M.Isolate isolate,
- S.Frame frame,
- Element scroller,
- M.InstanceRepository instances,
- M.ScriptRepository scripts,
- M.EventRepository events,
- {RenderingQueue queue}) {
+ factory DebuggerFrameElement(
+ M.Isolate isolate,
+ S.Frame frame,
+ Element scroller,
+ M.InstanceRepository instances,
+ M.ScriptRepository scripts,
+ M.EventRepository events,
+ {RenderingQueue queue}) {
assert(isolate != null);
assert(frame != null);
assert(scroller != null);
@@ -2412,50 +2390,70 @@
}
ButtonElement collapseButton;
content.addAll([
- new DivElement()..classes = ['frameDetails']
+ new DivElement()
+ ..classes = ['frameDetails']
..children = [
- new DivElement()..classes = ['flex-row-wrap']
+ new DivElement()
+ ..classes = ['flex-row-wrap']
..children = [
- new DivElement()..classes = ['flex-item-script']
- ..children = _frame.function?.location == null ? const []
- : [
- new SourceInsetElement(_isolate,
- _frame.function.location, _scripts, _instances,
- _events, currentPos: _frame.location.tokenPos,
- variables: _frame.variables, inDebuggerContext: true,
- queue: _r.queue)
- ],
- new DivElement()..classes = ['flex-item-vars']
+ new DivElement()
+ ..classes = ['flex-item-script']
+ ..children = _frame.function?.location == null
+ ? const []
+ : [
+ new SourceInsetElement(
+ _isolate,
+ _frame.function.location,
+ _scripts,
+ _instances,
+ _events,
+ currentPos: _frame.location.tokenPos,
+ variables: _frame.variables,
+ inDebuggerContext: true,
+ queue: _r.queue)
+ ],
+ new DivElement()
+ ..classes = ['flex-item-vars']
..children = [
_varsDiv = new DivElement()
..classes = ['memberList', 'frameVars']
..children = ([
- new DivElement()..classes = ['memberItem']
- ..children = homeMethodName == null ? const []
- : [
- new DivElement()..classes = ['memberName']
- ..text = homeMethodName,
- new DivElement()..classes = ['memberName']
- ..children = [
- anyRef(_isolate, homeMethod.dartOwner,
- _instances, queue: _r.queue)
+ new DivElement()
+ ..classes = ['memberItem']
+ ..children = homeMethodName == null
+ ? const []
+ : [
+ new DivElement()
+ ..classes = ['memberName']
+ ..text = homeMethodName,
+ new DivElement()
+ ..classes = ['memberName']
+ ..children = [
+ anyRef(_isolate, homeMethod.dartOwner,
+ _instances,
+ queue: _r.queue)
+ ]
]
- ]
- ]..addAll(_frame.variables.map((v) =>
- new DivElement()..classes = ['memberItem']
- ..children = [
- new DivElement()..classes = ['memberName']
- ..text = v.name,
- new DivElement()..classes = ['memberName']
+ ]
+ ..addAll(_frame.variables
+ .map((v) => new DivElement()
+ ..classes = ['memberItem']
..children = [
- anyRef(_isolate, v['value'], _instances,
- queue: _r.queue)
- ]
- ]
- ).toList()))
+ new DivElement()
+ ..classes = ['memberName']
+ ..text = v.name,
+ new DivElement()
+ ..classes = ['memberName']
+ ..children = [
+ anyRef(_isolate, v['value'], _instances,
+ queue: _r.queue)
+ ]
+ ])
+ .toList()))
]
],
- new DivElement()..classes = ['frameContractor']
+ new DivElement()
+ ..classes = ['frameContractor']
..children = [
collapseButton = new ButtonElement()
..onClick.listen((e) async {
@@ -2463,9 +2461,7 @@
await _toggleExpand();
collapseButton.disabled = false;
})
- ..children = [
- iconExpandLess.clone(true)
- ]
+ ..children = [iconExpandLess.clone(true)]
]
]
]);
@@ -2475,35 +2471,39 @@
List<Element> _createHeader() {
final content = [
- new DivElement()..classes = ['frameSummaryText']
+ new DivElement()
+ ..classes = ['frameSummaryText']
..children = [
- new DivElement()..classes = ['frameId']
+ new DivElement()
+ ..classes = ['frameId']
..text = 'Frame ${_frame.index}',
new SpanElement()
- ..children = _frame.function == null ? const []
- : [
- new FunctionRefElement(_isolate, _frame.function,
- queue: _r.queue)
- ],
+ ..children = _frame.function == null
+ ? const []
+ : [
+ new FunctionRefElement(_isolate, _frame.function,
+ queue: _r.queue)
+ ],
new SpanElement()..text = ' ( ',
new SpanElement()
- ..children = _frame.function?.location == null ? const []
- : [
- new SourceLinkElement(_isolate, _frame.function.location,
- _scripts,
- queue: _r.queue)
- ],
+ ..children = _frame.function?.location == null
+ ? const []
+ : [
+ new SourceLinkElement(
+ _isolate, _frame.function.location, _scripts,
+ queue: _r.queue)
+ ],
new SpanElement()..text = ' )'
]
];
if (!_expanded) {
- content.add(new DivElement()..classes = ['frameExpander']
- ..children = [
- iconExpandMore.clone(true)
- ]);
+ content.add(new DivElement()
+ ..classes = ['frameExpander']
+ ..children = [iconExpandMore.clone(true)]);
}
return [
- new DivElement()..classes = ['frameSummary']
+ new DivElement()
+ ..classes = ['frameSummary']
..children = content
];
}
@@ -2632,12 +2632,13 @@
bool _expanded = false;
- factory DebuggerMessageElement(S.Isolate isolate,
- S.ServiceMessage message,
- M.InstanceRepository instances,
- M.ScriptRepository scripts,
- M.EventRepository events,
- {RenderingQueue queue}) {
+ factory DebuggerMessageElement(
+ S.Isolate isolate,
+ S.ServiceMessage message,
+ M.InstanceRepository instances,
+ M.ScriptRepository scripts,
+ M.EventRepository events,
+ {RenderingQueue queue}) {
assert(isolate != null);
assert(message != null);
assert(instances != null);
@@ -2683,45 +2684,53 @@
ButtonElement collapseButton;
ButtonElement previewButton;
content.addAll([
- new DivElement()..classes = ['messageDetails']
+ new DivElement()
+ ..classes = ['messageDetails']
..children = [
- new DivElement()..classes = ['flex-row-wrap']
+ new DivElement()
+ ..classes = ['flex-row-wrap']
..children = [
- new DivElement()..classes = ['flex-item-script']
- ..children = _message.handler == null ? const []
- : [
- new SourceInsetElement(_isolate,
- _message.handler.location,
- _scripts,
- _instances,
- _events,
- inDebuggerContext: true,
- queue: _r.queue)
- ],
- new DivElement()..classes = ['flex-item-vars']
+ new DivElement()
+ ..classes = ['flex-item-script']
+ ..children = _message.handler == null
+ ? const []
+ : [
+ new SourceInsetElement(
+ _isolate,
+ _message.handler.location,
+ _scripts,
+ _instances,
+ _events,
+ inDebuggerContext: true,
+ queue: _r.queue)
+ ],
+ new DivElement()
+ ..classes = ['flex-item-vars']
..children = [
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..children = [
new DivElement()..classes = ['memberName'],
- new DivElement()..classes = ['memberValue']
+ new DivElement()
+ ..classes = ['memberValue']
..children = ([
previewButton = new ButtonElement()
..text = 'preview'
..onClick.listen((_) {
previewButton.disabled = true;
-
})
- ]..addAll(
- _preview == null ? const []
- : [
- anyRef(_isolate, _preview, _instances,
- queue: _r.queue)
- ]
- ))
+ ]
+ ..addAll(_preview == null
+ ? const []
+ : [
+ anyRef(_isolate, _preview, _instances,
+ queue: _r.queue)
+ ]))
]
]
],
- new DivElement()..classes = ['messageContractor']
+ new DivElement()
+ ..classes = ['messageContractor']
..children = [
collapseButton = new ButtonElement()
..onClick.listen((e) async {
@@ -2729,9 +2738,7 @@
await _toggleExpand();
collapseButton.disabled = false;
})
- ..children = [
- iconExpandLess.clone(true)
- ]
+ ..children = [iconExpandLess.clone(true)]
]
]
]);
@@ -2747,34 +2754,38 @@
List<Element> _createHeader() {
final content = [
- new DivElement()..classes = ['messageSummaryText']
+ new DivElement()
+ ..classes = ['messageSummaryText']
..children = [
- new DivElement()..classes = ['messageId']
+ new DivElement()
+ ..classes = ['messageId']
..text = 'message ${_message.index}',
new SpanElement()
- ..children = _message.handler == null ? const []
- : [
- new FunctionRefElement(_isolate, _message.handler,
- queue: _r.queue)
- ],
+ ..children = _message.handler == null
+ ? const []
+ : [
+ new FunctionRefElement(_isolate, _message.handler,
+ queue: _r.queue)
+ ],
new SpanElement()..text = ' ( ',
new SpanElement()
- ..children = _message.location == null ? const []
- : [
- new SourceLinkElement(_isolate, _message.location, _scripts,
- queue: _r.queue)
- ],
+ ..children = _message.location == null
+ ? const []
+ : [
+ new SourceLinkElement(_isolate, _message.location, _scripts,
+ queue: _r.queue)
+ ],
new SpanElement()..text = ' )'
]
];
if (!_expanded) {
- content.add(new DivElement()..classes = ['messageExpander']
- ..children = [
- iconExpandMore.clone(true)
- ]);
+ content.add(new DivElement()
+ ..classes = ['messageExpander']
+ ..children = [iconExpandMore.clone(true)]);
}
return [
- new DivElement()..classes = ['messageSummary']
+ new DivElement()
+ ..classes = ['messageSummary']
..children = content
];
}
@@ -2826,9 +2837,7 @@
factory DebuggerConsoleElement() {
final DebuggerConsoleElement e = document.createElement(tag.name);
- e.children = [
- new BRElement()
- ];
+ e.children = [new BRElement()];
return e;
}
@@ -2844,7 +2853,7 @@
// scrollTop -> how far is an element scrolled (from 0 to scrollHeight).
final distanceFromBottom =
container.scrollHeight - container.clientHeight - container.scrollTop;
- const threshold = 2; // 2 pixel slop.
+ const threshold = 2; // 2 pixel slop.
return distanceFromBottom <= threshold;
}
@@ -2865,7 +2874,7 @@
}
}
- void print(String line, { bool newline:true }) {
+ void print(String line, {bool newline: true}) {
var span = new SpanElement();
span.classes.add('normal');
span.appendText(line);
@@ -2875,7 +2884,7 @@
_append(span);
}
- void printBold(String line, { bool newline:true }) {
+ void printBold(String line, {bool newline: true}) {
var span = new SpanElement();
span.classes.add('bold');
span.appendText(line);
@@ -2885,7 +2894,7 @@
_append(span);
}
- void printRed(String line, { bool newline:true }) {
+ void printRed(String line, {bool newline: true}) {
var span = new SpanElement();
span.classes.add('red');
span.appendText(line);
@@ -2909,10 +2918,10 @@
}
}
- void printRef(S.Isolate isolate, S.Instance ref,
- M.InstanceRepository instances,{ bool newline:true }) {
- _append(new InstanceRefElement(isolate, ref, instances,
- queue: app.queue));
+ void printRef(
+ S.Isolate isolate, S.Instance ref, M.InstanceRepository instances,
+ {bool newline: true}) {
+ _append(new InstanceRefElement(isolate, ref, instances, queue: app.queue));
if (newline) {
this.newline();
}
@@ -2926,6 +2935,10 @@
children.clear();
}
+ void render() {
+ /* nothing to do */
+ }
+
ObservatoryApplication get app => ObservatoryApplication.app;
}
@@ -2935,11 +2948,10 @@
S.Isolate _isolate;
ObservatoryDebugger _debugger;
bool _busy = false;
- final _modalPromptDiv = new DivElement()
- ..classes = ['modalPrompt', 'hidden'];
+ final _modalPromptDiv = new DivElement()..classes = ['modalPrompt', 'hidden'];
final _textBox = new TextInputElement()
- ..classes = ['textBox']
- ..autofocus = true;
+ ..classes = ['textBox']
+ ..autofocus = true;
String get modalPrompt => _modalPromptDiv.text;
set modalPrompt(String value) {
if (_modalPromptDiv.text == '') {
@@ -2950,17 +2962,15 @@
_modalPromptDiv.classes.add('hidden');
}
}
+
String get text => _textBox.value;
set text(String value) => _textBox.value = value;
var modalCallback = null;
- factory DebuggerInputElement(S.Isolate isolate,
- ObservatoryDebugger debugger) {
+ factory DebuggerInputElement(
+ S.Isolate isolate, ObservatoryDebugger debugger) {
final DebuggerInputElement e = document.createElement(tag.name);
- e.children = [
- e._modalPromptDiv,
- e._textBox
- ];
+ e.children = [e._modalPromptDiv, e._textBox];
e._textBox.select();
e._textBox.onKeyDown.listen(e._onKeyDown);
return e;
@@ -3100,78 +3110,90 @@
void focus() {
_textBox.focus();
}
+
+ void render() {
+ // Nothing to do.
+ }
}
final SvgSvgElement iconExpandLess = new SvgSvgElement()
- ..setAttribute('width', '24')
- ..setAttribute('height', '24')
- ..children = [
- new PolygonElement()
- ..setAttribute('points', '12,8 6,14 7.4,15.4 12,10.8 16.6,15.4 18,14 ')
- ];
+ ..setAttribute('width', '24')
+ ..setAttribute('height', '24')
+ ..children = [
+ new PolygonElement()
+ ..setAttribute('points', '12,8 6,14 7.4,15.4 12,10.8 16.6,15.4 18,14 ')
+ ];
final SvgSvgElement iconExpandMore = new SvgSvgElement()
- ..setAttribute('width', '24')
- ..setAttribute('height', '24')
- ..children = [
- new PolygonElement()
- ..setAttribute('points', '16.6,8.6 12,13.2 7.4,8.6 6,10 12,16 18,10 ')
- ];
+ ..setAttribute('width', '24')
+ ..setAttribute('height', '24')
+ ..children = [
+ new PolygonElement()
+ ..setAttribute('points', '16.6,8.6 12,13.2 7.4,8.6 6,10 12,16 18,10 ')
+ ];
final SvgSvgElement iconChevronRight = new SvgSvgElement()
- ..setAttribute('width', '24')
- ..setAttribute('height', '24')
- ..children = [
- new PathElement()
- ..setAttribute('d', 'M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z')
- ];
+ ..setAttribute('width', '24')
+ ..setAttribute('height', '24')
+ ..children = [
+ new PathElement()
+ ..setAttribute('d', 'M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z')
+ ];
final SvgSvgElement iconChevronLeft = new SvgSvgElement()
- ..setAttribute('width', '24')
- ..setAttribute('height', '24')
- ..children = [
- new PathElement()
- ..setAttribute('d', 'M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z')
- ];
+ ..setAttribute('width', '24')
+ ..setAttribute('height', '24')
+ ..children = [
+ new PathElement()
+ ..setAttribute('d', 'M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z')
+ ];
final SvgSvgElement iconHorizontalThreeDot = new SvgSvgElement()
- ..setAttribute('width', '24')
- ..setAttribute('height', '24')
- ..children = [
- new PathElement()
- ..setAttribute('d', 'M6 10c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 '
- '2-2-.9-2-2-2zm12 0c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 '
- '2-2-.9-2-2-2zm-6 0c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 '
- '2-2-.9-2-2-2z')
- ];
+ ..setAttribute('width', '24')
+ ..setAttribute('height', '24')
+ ..children = [
+ new PathElement()
+ ..setAttribute(
+ 'd',
+ 'M6 10c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 '
+ '2-2-.9-2-2-2zm12 0c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 '
+ '2-2-.9-2-2-2zm-6 0c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 '
+ '2-2-.9-2-2-2z')
+ ];
final SvgSvgElement iconVerticalThreeDot = new SvgSvgElement()
- ..setAttribute('width', '24')
- ..setAttribute('height', '24')
- ..children = [
- new PathElement()
- ..setAttribute('d', 'M12 8c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 '
- '2zm0 2c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 '
- '2-2-.9-2-2-2zm0 6c-1.1 0-2 .9-2 2s.9 2 2 2 '
- '2-.9 2-2-.9-2-2-2z')
- ];
+ ..setAttribute('width', '24')
+ ..setAttribute('height', '24')
+ ..children = [
+ new PathElement()
+ ..setAttribute(
+ 'd',
+ 'M12 8c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 '
+ '2zm0 2c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 '
+ '2-2-.9-2-2-2zm0 6c-1.1 0-2 .9-2 2s.9 2 2 2 '
+ '2-.9 2-2-.9-2-2-2z')
+ ];
final SvgSvgElement iconInfo = new SvgSvgElement()
- ..setAttribute('width', '24')
- ..setAttribute('height', '24')
- ..children = [
- new PathElement()
- ..setAttribute('d', 'M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 '
- '10-10S17.52 2 12 2zm1 15h-2v-6h2v6zm0-8h-2V7h2v2z')
- ];
+ ..setAttribute('width', '24')
+ ..setAttribute('height', '24')
+ ..children = [
+ new PathElement()
+ ..setAttribute(
+ 'd',
+ 'M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 '
+ '10-10S17.52 2 12 2zm1 15h-2v-6h2v6zm0-8h-2V7h2v2z')
+ ];
final SvgSvgElement iconInfoOutline = new SvgSvgElement()
- ..setAttribute('width', '24')
- ..setAttribute('height', '24')
- ..children = [
- new PathElement()
- ..setAttribute('d', 'M11 17h2v-6h-2v6zm1-15C6.48 2 2 6.48 2 12s4.48 10 '
- '10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 '
- '0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zM11 '
- '9h2V7h-2v2z')
- ];
+ ..setAttribute('width', '24')
+ ..setAttribute('height', '24')
+ ..children = [
+ new PathElement()
+ ..setAttribute(
+ 'd',
+ 'M11 17h2v-6h-2v6zm1-15C6.48 2 2 6.48 2 12s4.48 10 '
+ '10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 '
+ '0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zM11 '
+ '9h2V7h-2v2z')
+ ];
diff --git a/runtime/observatory/lib/src/elements/error_ref.dart b/runtime/observatory/lib/src/elements/error_ref.dart
index 8a523d3..20cc4e3 100644
--- a/runtime/observatory/lib/src/elements/error_ref.dart
+++ b/runtime/observatory/lib/src/elements/error_ref.dart
@@ -6,8 +6,7 @@
import 'dart:html';
import 'dart:async';
-import 'package:observatory/models.dart'
- show ErrorRef;
+import 'package:observatory/models.dart' show ErrorRef;
import 'package:observatory/src/elements/helpers/tag.dart';
import 'package:observatory/src/elements/helpers/rendering_scheduler.dart';
@@ -46,8 +45,6 @@
}
void render() {
- children = [
- new PreElement()..text = error.message
- ];
+ children = [new PreElement()..text = error.message];
}
}
diff --git a/runtime/observatory/lib/src/elements/error_view.dart b/runtime/observatory/lib/src/elements/error_view.dart
index 92fee08..7d93637 100644
--- a/runtime/observatory/lib/src/elements/error_view.dart
+++ b/runtime/observatory/lib/src/elements/error_view.dart
@@ -14,25 +14,26 @@
import 'package:observatory/src/elements/nav/top_menu.dart';
import 'package:observatory/src/elements/view_footer.dart';
-class ErrorViewElement extends HtmlElement implements Renderable{
+class ErrorViewElement extends HtmlElement implements Renderable {
static const tag = const Tag<ErrorViewElement>('error-view',
- dependencies: const [NavTopMenuElement.tag,
- NavNotifyElement.tag,
- ViewFooterElement.tag]);
+ dependencies: const [
+ NavTopMenuElement.tag,
+ NavNotifyElement.tag,
+ ViewFooterElement.tag
+ ]);
RenderingScheduler _r;
- Stream<RenderedEvent<ErrorViewElement>> get onRendered =>
- _r.onRendered;
+ Stream<RenderedEvent<ErrorViewElement>> get onRendered => _r.onRendered;
M.Error _error;
M.NotificationRepository _notifications;
M.Error get error => _error;
- factory ErrorViewElement(M.NotificationRepository notifications,
- M.Error error,
- {RenderingQueue queue}) {
+ factory ErrorViewElement(
+ M.NotificationRepository notifications, M.Error error,
+ {RenderingQueue queue}) {
assert(error != null);
assert(notifications != null);
ErrorViewElement e = document.createElement(tag.name);
@@ -69,17 +70,16 @@
new HeadingElement.h1()
..text = 'Error: ${_kindToString(_error.kind)}',
new BRElement(),
- new DivElement()..classes = ['well']
- ..children = [
- new PreElement()..text = error.message
- ]
+ new DivElement()
+ ..classes = ['well']
+ ..children = [new PreElement()..text = error.message]
],
new ViewFooterElement(queue: _r.queue)
];
}
static String _kindToString(M.ErrorKind kind) {
- switch(kind) {
+ switch (kind) {
case M.ErrorKind.unhandledException:
return 'Unhandled Exception';
case M.ErrorKind.languageError:
diff --git a/runtime/observatory/lib/src/elements/eval_box.dart b/runtime/observatory/lib/src/elements/eval_box.dart
index 855cd7a..446c44d 100644
--- a/runtime/observatory/lib/src/elements/eval_box.dart
+++ b/runtime/observatory/lib/src/elements/eval_box.dart
@@ -14,9 +14,7 @@
class EvalBoxElement extends HtmlElement implements Renderable {
static const tag = const Tag<EvalBoxElement>('eval-box',
- dependencies: const [
- InstanceRefElement.tag
- ]);
+ dependencies: const [InstanceRefElement.tag]);
RenderingScheduler<EvalBoxElement> _r;
@@ -35,11 +33,10 @@
M.ObjectRef get context => _context;
factory EvalBoxElement(M.IsolateRef isolate, M.ObjectRef context,
- M.InstanceRepository instances,
- M.EvalRepository eval,
- {bool multiline: false,
- Iterable<String> quickExpressions: const [],
- RenderingQueue queue}) {
+ M.InstanceRepository instances, M.EvalRepository eval,
+ {bool multiline: false,
+ Iterable<String> quickExpressions: const [],
+ RenderingQueue queue}) {
assert(isolate != null);
assert(context != null);
assert(instances != null);
@@ -75,22 +72,23 @@
void render() {
children = [
- new DivElement()..classes = ['quicks']
- ..children = _quickExpressions.map((q) =>
- new ButtonElement()
- ..text = q
- ..onClick.listen((_) {
- _expression = q;
- _run();
- })
- ),
- new DivElement()..classes = ['heading']
+ new DivElement()
+ ..classes = ['quicks']
+ ..children = _quickExpressions.map((q) => new ButtonElement()
+ ..text = q
+ ..onClick.listen((_) {
+ _expression = q;
+ _run();
+ })),
+ new DivElement()
+ ..classes = ['heading']
..children = [
new FormElement()
..autocomplete = 'on'
..children = [
_multiline ? _createEvalTextArea() : _createEvalTextBox(),
- new SpanElement()..classes = ['buttons']
+ new SpanElement()
+ ..classes = ['buttons']
..children = [
_createEvalButton(),
_createMultilineCheckbox(),
@@ -99,33 +97,39 @@
]
],
new TableElement()
- ..children = _results.reversed.map((result) =>
- new TableRowElement()
- ..children = [
- new TableCellElement()..classes = ['historyExpr']
- ..children = [
- new ButtonElement()..text = result.expression
- ..onClick.listen((_) {
- _expression = result.expression;
- _r.dirty();
- })
- ],
- new TableCellElement()..classes = ['historyValue']
- ..children = [
- result.isPending
- ? (new SpanElement()..text = 'Pending...')
- : anyRef(_isolate, result.value, _instances,
- queue: _r.queue)
- ],
- new TableCellElement()..classes = ['historyDelete']
- ..children = [
- new ButtonElement()..text = '✖ Remove'
- ..onClick.listen((_) {
- _results.remove(result);
- _r.dirty();
- })
- ]
- ]).toList()
+ ..children = _results.reversed
+ .map((result) => new TableRowElement()
+ ..children = [
+ new TableCellElement()
+ ..classes = ['historyExpr']
+ ..children = [
+ new ButtonElement()
+ ..text = result.expression
+ ..onClick.listen((_) {
+ _expression = result.expression;
+ _r.dirty();
+ })
+ ],
+ new TableCellElement()
+ ..classes = ['historyValue']
+ ..children = [
+ result.isPending
+ ? (new SpanElement()..text = 'Pending...')
+ : anyRef(_isolate, result.value, _instances,
+ queue: _r.queue)
+ ],
+ new TableCellElement()
+ ..classes = ['historyDelete']
+ ..children = [
+ new ButtonElement()
+ ..text = '✖ Remove'
+ ..onClick.listen((_) {
+ _results.remove(result);
+ _r.dirty();
+ })
+ ]
+ ])
+ .toList()
];
}
@@ -134,12 +138,10 @@
..classes = ['textbox']
..placeholder = 'evaluate an expression'
..value = _expression
- ..onKeyUp
- .where((e) => e.key == '\n')
- .listen((e) {
- e.preventDefault();
- _run();
- });
+ ..onKeyUp.where((e) => e.key == '\n').listen((e) {
+ e.preventDefault();
+ _run();
+ });
area.onInput.listen((e) {
_expression = area.value;
});
@@ -152,12 +154,10 @@
..classes = ['textbox']
..placeholder = 'evaluate an expression'
..value = _expression
- ..onKeyUp
- .where((e) => e.key == '\n')
- .listen((e) {
- e.preventDefault();
- _run();
- });
+ ..onKeyUp.where((e) => e.key == '\n').listen((e) {
+ e.preventDefault();
+ _run();
+ });
textbox.onInput.listen((e) {
_expression = textbox.value;
});
@@ -175,13 +175,12 @@
}
CheckboxInputElement _createMultilineCheckbox() {
- final checkbox = new CheckboxInputElement()
- ..checked = _multiline;
+ final checkbox = new CheckboxInputElement()..checked = _multiline;
checkbox.onClick.listen((e) {
- e.preventDefault();
- _multiline = checkbox.checked;
- _r.dirty();
- });
+ e.preventDefault();
+ _multiline = checkbox.checked;
+ _r.dirty();
+ });
return checkbox;
}
@@ -193,8 +192,8 @@
_results.add(result);
_r.dirty();
final index = _results.indexOf(result);
- _results[index] = new _ExpressionDescription(expression,
- await _eval.evaluate(_isolate, _context, expression));
+ _results[index] = new _ExpressionDescription(
+ expression, await _eval.evaluate(_isolate, _context, expression));
_r.dirty();
}
}
@@ -205,6 +204,5 @@
bool get isPending => value == null;
_ExpressionDescription(this.expression, this.value);
- _ExpressionDescription.pending(this.expression)
- : value = null;
+ _ExpressionDescription.pending(this.expression) : value = null;
}
diff --git a/runtime/observatory/lib/src/elements/field_ref.dart b/runtime/observatory/lib/src/elements/field_ref.dart
index 960cbae..b33749e 100644
--- a/runtime/observatory/lib/src/elements/field_ref.dart
+++ b/runtime/observatory/lib/src/elements/field_ref.dart
@@ -12,9 +12,7 @@
class FieldRefElement extends HtmlElement implements Renderable {
static const tag = const Tag<FieldRefElement>('field-ref',
- dependencies: const [
- InstanceRefElement.tag
- ]);
+ dependencies: const [InstanceRefElement.tag]);
RenderingScheduler<FieldRefElement> _r;
@@ -27,8 +25,9 @@
M.IsolateRef get isolate => _isolate;
M.FieldRef get field => _field;
- factory FieldRefElement(M.IsolateRef isolate, M.FieldRef field,
- M.InstanceRepository instances, {RenderingQueue queue}) {
+ factory FieldRefElement(
+ M.IsolateRef isolate, M.FieldRef field, M.InstanceRepository instances,
+ {RenderingQueue queue}) {
assert(isolate != null);
assert(field != null);
assert(instances != null);
@@ -68,7 +67,7 @@
header += 'final ';
} else if (_field.isConst) {
header += 'const ';
- } else if (_field.declaredType.name == 'dynamic'){
+ } else if (_field.declaredType.name == 'dynamic') {
header += 'var ';
}
if (_field.declaredType.name == 'dynamic') {
@@ -77,7 +76,7 @@
new AnchorElement(href: Uris.inspect(_isolate, object: _field))
..text = _field.name
];
- }else {
+ } else {
children = [
new SpanElement()..text = header,
new InstanceRefElement(_isolate, _field.declaredType, _instances,
diff --git a/runtime/observatory/lib/src/elements/field_view.dart b/runtime/observatory/lib/src/elements/field_view.dart
index 536dc5d..3881d85 100644
--- a/runtime/observatory/lib/src/elements/field_view.dart
+++ b/runtime/observatory/lib/src/elements/field_view.dart
@@ -27,22 +27,22 @@
import 'package:observatory/src/elements/view_footer.dart';
class FieldViewElement extends HtmlElement implements Renderable {
- static const tag = const Tag<FieldViewElement>('field-view',
- dependencies: const [
- ClassRefElement.tag,
- CurlyBlockElement.tag,
- NavClassMenuElement.tag,
- NavLibraryMenuElement.tag,
- NavTopMenuElement.tag,
- NavVMMenuElement.tag,
- NavIsolateMenuElement.tag,
- NavRefreshElement.tag,
- NavNotifyElement.tag,
- ObjectCommonElement.tag,
- ScriptInsetElement.tag,
- SourceLinkElement.tag,
- ViewFooterElement.tag
- ]);
+ static const tag =
+ const Tag<FieldViewElement>('field-view', dependencies: const [
+ ClassRefElement.tag,
+ CurlyBlockElement.tag,
+ NavClassMenuElement.tag,
+ NavLibraryMenuElement.tag,
+ NavTopMenuElement.tag,
+ NavVMMenuElement.tag,
+ NavIsolateMenuElement.tag,
+ NavRefreshElement.tag,
+ NavNotifyElement.tag,
+ ObjectCommonElement.tag,
+ ScriptInsetElement.tag,
+ SourceLinkElement.tag,
+ ViewFooterElement.tag
+ ]);
RenderingScheduler<FieldViewElement> _r;
@@ -63,24 +63,26 @@
M.ScriptRepository _scripts;
M.InstanceRepository _instances;
-
M.VMRef get vm => _vm;
M.IsolateRef get isolate => _isolate;
M.NotificationRepository get notifications => _notifications;
M.Field get field => _field;
- factory FieldViewElement(M.VM vm, M.IsolateRef isolate, M.Field field,
- M.EventRepository events,
- M.NotificationRepository notifications,
- M.FieldRepository fields,
- M.ClassRepository classes,
- M.RetainedSizeRepository retainedSizes,
- M.ReachableSizeRepository reachableSizes,
- M.InboundReferencesRepository references,
- M.RetainingPathRepository retainingPaths,
- M.ScriptRepository scripts,
- M.InstanceRepository instances,
- {RenderingQueue queue}) {
+ factory FieldViewElement(
+ M.VM vm,
+ M.IsolateRef isolate,
+ M.Field field,
+ M.EventRepository events,
+ M.NotificationRepository notifications,
+ M.FieldRepository fields,
+ M.ClassRepository classes,
+ M.RetainedSizeRepository retainedSizes,
+ M.ReachableSizeRepository reachableSizes,
+ M.InboundReferencesRepository references,
+ M.RetainingPathRepository retainingPaths,
+ M.ScriptRepository scripts,
+ M.InstanceRepository instances,
+ {RenderingQueue queue}) {
assert(vm != null);
assert(isolate != null);
assert(events != null);
@@ -145,36 +147,39 @@
} else if (_field.isConst) {
header += 'const ';
}
- if (_field.declaredType.name == 'dynamic'){
+ if (_field.declaredType.name == 'dynamic') {
header += 'var';
} else {
header += _field.declaredType.name;
}
children = [
navBar(_createMenu()),
- new DivElement()..classes = ['content-centered-big']
+ new DivElement()
+ ..classes = ['content-centered-big']
..children = [
new HeadingElement.h2()..text = '$header ${field.name}',
new HRElement(),
new ObjectCommonElement(_isolate, _field, _retainedSizes,
- _reachableSizes, _references, _retainingPaths,
- _instances, queue: _r.queue),
+ _reachableSizes, _references, _retainingPaths, _instances,
+ queue: _r.queue),
new BRElement(),
- new DivElement()..classes = ['memberList']
+ new DivElement()
+ ..classes = ['memberList']
..children = _createMembers(),
new HRElement(),
new DivElement()
- ..children = _field.location == null ? const []
- : [
- new ScriptInsetElement(_isolate, _field.location.script,
- _scripts, _instances, _events,
- startPos: field.location.tokenPos,
- endPos: field.location.tokenPos,
- queue: _r.queue)
- ],
+ ..children = _field.location == null
+ ? const []
+ : [
+ new ScriptInsetElement(_isolate, _field.location.script,
+ _scripts, _instances, _events,
+ startPos: field.location.tokenPos,
+ endPos: field.location.tokenPos,
+ queue: _r.queue)
+ ],
new ViewFooterElement(queue: _r.queue)
]
- ];
+ ];
}
List<Element> _createMenu() {
@@ -185,19 +190,18 @@
];
if (_library != null) {
menu.add(new NavLibraryMenuElement(_isolate, _field.dartOwner,
- queue: _r.queue));
+ queue: _r.queue));
} else if (_field.dartOwner is M.ClassRef) {
menu.add(
- new NavClassMenuElement(_isolate, _field.dartOwner, queue: _r.queue)
- );
+ new NavClassMenuElement(_isolate, _field.dartOwner, queue: _r.queue));
}
menu.addAll([
navMenu(_field.name),
new NavRefreshElement(queue: _r.queue)
- ..onRefresh.listen((e) {
- e.element.disabled = true;
- _refresh();
- }),
+ ..onRefresh.listen((e) {
+ e.element.disabled = true;
+ _refresh();
+ }),
new NavNotifyElement(_notifications, queue: _r.queue)
]);
return menu;
@@ -205,56 +209,63 @@
List<Element> _createMembers() {
final members = <Element>[
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'owner',
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..children = [
_field.dartOwner == null
- ? (new SpanElement()..text = '...')
- : anyRef(_isolate, _field.dartOwner, _instances,
- queue: _r.queue)
+ ? (new SpanElement()..text = '...')
+ : anyRef(_isolate, _field.dartOwner, _instances,
+ queue: _r.queue)
]
],
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'script',
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..children = [
new SourceLinkElement(_isolate, field.location, _scripts,
- queue: _r.queue)
+ queue: _r.queue)
]
]
];
if (!_field.isStatic) {
- members.add(
- new DivElement()..classes = ['memberItem']
- ..title = 'The types observed for this field at runtime. '
- 'Fields that are observed to have a single type at runtime '
- 'or to never be null may allow for additional optimization.'
- ..children = [
- new DivElement()..classes = ['memberName']
- ..text = 'observed types',
- new DivElement()..classes = ['memberName']
- ..children = _createGuard()
- ]
- );
+ members.add(new DivElement()
+ ..classes = ['memberItem']
+ ..title = 'The types observed for this field at runtime. '
+ 'Fields that are observed to have a single type at runtime '
+ 'or to never be null may allow for additional optimization.'
+ ..children = [
+ new DivElement()
+ ..classes = ['memberName']
+ ..text = 'observed types',
+ new DivElement()
+ ..classes = ['memberName']
+ ..children = _createGuard()
+ ]);
}
if (_field.staticValue != null) {
- members.add(
- new DivElement()..classes = ['memberItem']
- ..children = [
- new DivElement()..classes = ['memberName']
- ..text = 'static value',
- new DivElement()..classes = ['memberName']
- ..children = [
- anyRef(_isolate, _field.staticValue, _instances,
- queue: _r.queue)
- ]
- ]
- );
+ members.add(new DivElement()
+ ..classes = ['memberItem']
+ ..children = [
+ new DivElement()
+ ..classes = ['memberName']
+ ..text = 'static value',
+ new DivElement()
+ ..classes = ['memberName']
+ ..children = [
+ anyRef(_isolate, _field.staticValue, _instances, queue: _r.queue)
+ ]
+ ]);
}
return members;
}
@@ -269,13 +280,13 @@
guard.add(new SpanElement()..text = 'various');
break;
case M.GuardClassKind.single:
- guard.add(new ClassRefElement(_isolate, _field.guardClass,
- queue: _r.queue));
+ guard.add(
+ new ClassRefElement(_isolate, _field.guardClass, queue: _r.queue));
break;
}
guard.add(new SpanElement()
- ..text = _field.guardNullable ? '— null observed' : '— null not observed'
- );
+ ..text =
+ _field.guardNullable ? '— null observed' : '— null not observed');
return guard;
}
diff --git a/runtime/observatory/lib/src/elements/flag_list.dart b/runtime/observatory/lib/src/elements/flag_list.dart
index 5405008..ac310c8 100644
--- a/runtime/observatory/lib/src/elements/flag_list.dart
+++ b/runtime/observatory/lib/src/elements/flag_list.dart
@@ -18,12 +18,14 @@
import 'package:observatory/src/elements/view_footer.dart';
class FlagListElement extends HtmlElement implements Renderable {
- static const tag = const Tag<FlagListElement>('flag-list',
- dependencies: const [NavNotifyElement.tag,
- NavRefreshElement.tag,
- NavTopMenuElement.tag,
- NavVMMenuElement.tag,
- ViewFooterElement.tag,]);
+ static const tag =
+ const Tag<FlagListElement>('flag-list', dependencies: const [
+ NavNotifyElement.tag,
+ NavRefreshElement.tag,
+ NavTopMenuElement.tag,
+ NavVMMenuElement.tag,
+ ViewFooterElement.tag,
+ ]);
RenderingScheduler _r;
@@ -37,11 +39,9 @@
M.VMRef get vm => _vm;
- factory FlagListElement(M.VMRef vm,
- M.EventRepository events,
- M.FlagsRepository repository,
- M.NotificationRepository notifications,
- {RenderingQueue queue}) {
+ factory FlagListElement(M.VMRef vm, M.EventRepository events,
+ M.FlagsRepository repository, M.NotificationRepository notifications,
+ {RenderingQueue queue}) {
assert(vm != null);
assert(events != null);
assert(repository != null);
@@ -131,15 +131,19 @@
static List<Element> _renderFlag(M.Flag flag) {
return [
- new SpanElement()..classes = ['comment']
+ new SpanElement()
+ ..classes = ['comment']
..text = '// ${flag.comment}',
- new DivElement()..classes = flag.modified ? ['flag', 'modified']
- : ['flag', 'unmodified']
+ new DivElement()
+ ..classes =
+ flag.modified ? ['flag', 'modified'] : ['flag', 'unmodified']
..children = [
- new SpanElement()..classes = ['name']
+ new SpanElement()
+ ..classes = ['name']
..text = flag.name,
new SpanElement()..text = '=',
- new SpanElement()..classes = ['value']
+ new SpanElement()
+ ..classes = ['value']
..text = flag.valueAsString ?? 'NULL'
],
new BRElement(),
diff --git a/runtime/observatory/lib/src/elements/function_ref.dart b/runtime/observatory/lib/src/elements/function_ref.dart
index 9b2aebd..e5ace69 100644
--- a/runtime/observatory/lib/src/elements/function_ref.dart
+++ b/runtime/observatory/lib/src/elements/function_ref.dart
@@ -7,8 +7,13 @@
import 'dart:html';
import 'dart:async';
import 'package:observatory/models.dart' as M
- show IsolateRef, FunctionRef, isSyntheticFunction, ClassRef, ObjectRef,
- getFunctionFullName;
+ show
+ IsolateRef,
+ FunctionRef,
+ isSyntheticFunction,
+ ClassRef,
+ ObjectRef,
+ getFunctionFullName;
import 'package:observatory/src/elements/class_ref.dart';
import 'package:observatory/src/elements/helpers/rendering_scheduler.dart';
import 'package:observatory/src/elements/helpers/tag.dart';
@@ -60,8 +65,10 @@
void render() {
var content = <Element>[
- new AnchorElement(href: M.isSyntheticFunction(_function.kind) ? null
- : Uris.inspect(_isolate, object: _function))
+ new AnchorElement(
+ href: M.isSyntheticFunction(_function.kind)
+ ? null
+ : Uris.inspect(_isolate, object: _function))
..text = _function.name
];
if (qualified) {
@@ -70,8 +77,10 @@
M.FunctionRef function = (owner as M.FunctionRef);
content.addAll([
new SpanElement()..text = '.',
- new AnchorElement(href: M.isSyntheticFunction(function.kind) ? null
- : Uris.inspect(_isolate, object: function))
+ new AnchorElement(
+ href: M.isSyntheticFunction(function.kind)
+ ? null
+ : Uris.inspect(_isolate, object: function))
..text = function.name
]);
owner = function.dartOwner;
diff --git a/runtime/observatory/lib/src/elements/function_view.dart b/runtime/observatory/lib/src/elements/function_view.dart
index a0f3111..0654fac 100644
--- a/runtime/observatory/lib/src/elements/function_view.dart
+++ b/runtime/observatory/lib/src/elements/function_view.dart
@@ -30,25 +30,25 @@
import 'package:observatory/src/elements/view_footer.dart';
class FunctionViewElement extends HtmlElement implements Renderable {
- static const tag = const Tag<FunctionViewElement>('function-view',
- dependencies: const [
- ClassRefElement.tag,
- CodeRefElement.tag,
- CurlyBlockElement.tag,
- FieldRefElement.tag,
- InstanceRefElement.tag,
- NavClassMenuElement.tag,
- NavLibraryMenuElement.tag,
- NavTopMenuElement.tag,
- NavVMMenuElement.tag,
- NavIsolateMenuElement.tag,
- NavRefreshElement.tag,
- NavNotifyElement.tag,
- ObjectCommonElement.tag,
- SourceLinkElement.tag,
- SourceInsetElement.tag,
- ViewFooterElement.tag
- ]);
+ static const tag =
+ const Tag<FunctionViewElement>('function-view', dependencies: const [
+ ClassRefElement.tag,
+ CodeRefElement.tag,
+ CurlyBlockElement.tag,
+ FieldRefElement.tag,
+ InstanceRefElement.tag,
+ NavClassMenuElement.tag,
+ NavLibraryMenuElement.tag,
+ NavTopMenuElement.tag,
+ NavVMMenuElement.tag,
+ NavIsolateMenuElement.tag,
+ NavRefreshElement.tag,
+ NavNotifyElement.tag,
+ ObjectCommonElement.tag,
+ SourceLinkElement.tag,
+ SourceInsetElement.tag,
+ ViewFooterElement.tag
+ ]);
RenderingScheduler<FunctionViewElement> _r;
@@ -69,24 +69,26 @@
M.ScriptRepository _scripts;
M.InstanceRepository _instances;
-
M.VMRef get vm => _vm;
M.IsolateRef get isolate => _isolate;
M.NotificationRepository get notifications => _notifications;
M.Function get function => _function;
- factory FunctionViewElement(M.VM vm, M.IsolateRef isolate, M.Function function,
- M.EventRepository events,
- M.NotificationRepository notifications,
- M.FunctionRepository functions,
- M.ClassRepository classes,
- M.RetainedSizeRepository retainedSizes,
- M.ReachableSizeRepository reachableSizes,
- M.InboundReferencesRepository references,
- M.RetainingPathRepository retainingPaths,
- M.ScriptRepository scripts,
- M.InstanceRepository instances,
- {RenderingQueue queue}) {
+ factory FunctionViewElement(
+ M.VM vm,
+ M.IsolateRef isolate,
+ M.Function function,
+ M.EventRepository events,
+ M.NotificationRepository notifications,
+ M.FunctionRepository functions,
+ M.ClassRepository classes,
+ M.RetainedSizeRepository retainedSizes,
+ M.ReachableSizeRepository reachableSizes,
+ M.InboundReferencesRepository references,
+ M.RetainingPathRepository retainingPaths,
+ M.ScriptRepository scripts,
+ M.InstanceRepository instances,
+ {RenderingQueue queue}) {
assert(vm != null);
assert(isolate != null);
assert(events != null);
@@ -140,26 +142,30 @@
void render() {
children = [
navBar(_createMenu()),
- new DivElement()..classes = ['content-centered-big']
+ new DivElement()
+ ..classes = ['content-centered-big']
..children = [
new HeadingElement.h2()..text = 'Function ${_function.name}',
new HRElement(),
new ObjectCommonElement(_isolate, _function, _retainedSizes,
- _reachableSizes, _references, _retainingPaths,
- _instances, queue: _r.queue),
+ _reachableSizes, _references, _retainingPaths, _instances,
+ queue: _r.queue),
new BRElement(),
- new DivElement()..classes = ['memberList']
+ new DivElement()
+ ..classes = ['memberList']
..children = _createMembers(),
new HRElement(),
new DivElement()
- ..children = _function.location == null ? const []
- : [
- new SourceInsetElement(_isolate, _function.location, _scripts,
- _instances, _events, queue: _r.queue)
- ],
+ ..children = _function.location == null
+ ? const []
+ : [
+ new SourceInsetElement(_isolate, _function.location,
+ _scripts, _instances, _events,
+ queue: _r.queue)
+ ],
new ViewFooterElement(queue: _r.queue)
]
- ];
+ ];
}
List<Element> _createMenu() {
@@ -170,19 +176,18 @@
];
if (_library != null) {
menu.add(new NavLibraryMenuElement(_isolate, _function.dartOwner,
- queue: _r.queue));
+ queue: _r.queue));
} else if (_function.dartOwner is M.ClassRef) {
- menu.add(
- new NavClassMenuElement(_isolate, _function.dartOwner, queue: _r.queue)
- );
+ menu.add(new NavClassMenuElement(_isolate, _function.dartOwner,
+ queue: _r.queue));
}
menu.addAll([
navMenu(_function.name),
new NavRefreshElement(queue: _r.queue)
- ..onRefresh.listen((e) {
- e.element.disabled = true;
- _refresh();
- }),
+ ..onRefresh.listen((e) {
+ e.element.disabled = true;
+ _refresh();
+ }),
new NavNotifyElement(_notifications, queue: _r.queue)
]);
return menu;
@@ -190,149 +195,189 @@
List<Element> _createMembers() {
final members = <Element>[
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'kind',
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..children = [
new SpanElement()
..text = '${_function.isStatic ? "static ": ""}'
- '${_function.isConst ? "const ": ""}'
- '${_functionKindToString(_function.kind)}'
+ '${_function.isConst ? "const ": ""}'
+ '${_functionKindToString(_function.kind)}'
]
],
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'owner',
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..children = [
_function.dartOwner == null
- ? (new SpanElement()..text = '...')
- : anyRef(_isolate, _function.dartOwner, _instances,
- queue: _r.queue)
+ ? (new SpanElement()..text = '...')
+ : anyRef(_isolate, _function.dartOwner, _instances,
+ queue: _r.queue)
]
]
];
if (_function.field != null) {
- members.add(
- new DivElement()..classes = ['memberItem']
- ..children = [
- new DivElement()..classes = ['memberName']
- ..text = 'script',
- new DivElement()..classes = ['memberName']
- ..children = [
- new FieldRefElement(_isolate, _function.field, _instances,
- queue: _r.queue)
- ]
- ]
- );
- }
- members.add(
- new DivElement()..classes = ['memberItem']
+ members.add(new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'script',
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..children = [
- new SourceLinkElement(_isolate, _function.location, _scripts,
- queue: _r.queue)
+ new FieldRefElement(_isolate, _function.field, _instances,
+ queue: _r.queue)
]
- ]
- );
- if (_function.code != null) {
- members.add(
- new DivElement()..classes = ['memberItem']
+ ]);
+ }
+ members.add(new DivElement()
+ ..classes = ['memberItem']
+ ..children = [
+ new DivElement()
+ ..classes = ['memberName']
+ ..text = 'script',
+ new DivElement()
+ ..classes = ['memberName']
..children = [
- new DivElement()..classes = ['memberName']
- ..text = 'current code',
- new DivElement()..classes = ['memberName']
- ..children = [
- new CodeRefElement(_isolate, _function.code, queue: _r.queue)
- ]
+ new SourceLinkElement(_isolate, _function.location, _scripts,
+ queue: _r.queue)
]
- );
+ ]);
+ if (_function.code != null) {
+ members.add(new DivElement()
+ ..classes = ['memberItem']
+ ..children = [
+ new DivElement()
+ ..classes = ['memberName']
+ ..text = 'current code',
+ new DivElement()
+ ..classes = ['memberName']
+ ..children = [
+ new CodeRefElement(_isolate, _function.code, queue: _r.queue)
+ ]
+ ]);
}
if (_function.unoptimizedCode != null) {
- members.add(
- new DivElement()..classes = ['memberItem']
- ..children = [
- new DivElement()..classes = ['memberName']
- ..text = 'unoptimized code',
- new DivElement()..classes = ['memberName']
- ..children = [
- new CodeRefElement(_isolate, _function.unoptimizedCode,
- queue: _r.queue),
- new SpanElement()
- ..title = 'This count is used to determine when a function '
- 'will be optimized. It is a combination of call '
- 'counts and other factors.'
- ..text = ' (usage count: ${function.usageCounter })'
- ]
- ]
- );
- }
- members.addAll([
- new DivElement()..classes = ['memberItem']
- ..text = ' ',
- new DivElement()..classes = ['memberItem']
+ members.add(new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
- ..text = 'ic data array',
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
+ ..text = 'unoptimized code',
+ new DivElement()
+ ..classes = ['memberName']
..children = [
- new InstanceRefElement(_isolate, _function.icDataArray,
- _instances, queue: _r.queue)
+ new CodeRefElement(_isolate, _function.unoptimizedCode,
+ queue: _r.queue),
+ new SpanElement()
+ ..title = 'This count is used to determine when a function '
+ 'will be optimized. It is a combination of call '
+ 'counts and other factors.'
+ ..text = ' (usage count: ${function.usageCounter })'
]
- ],
- new DivElement()..classes = ['memberItem']
+ ]);
+ }
+ members.add(new DivElement()
+ ..classes = ['memberItem']
+ ..text = ' ');
+
+ if (_function.icDataArray != null) {
+ members.add(new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
+ ..text = 'ic data array',
+ new DivElement()
+ ..classes = ['memberName']
+ ..children = [
+ new InstanceRefElement(
+ _isolate, _function.icDataArray, _instances,
+ queue: _r.queue)
+ ]
+ ]);
+ }
+
+ members.addAll([
+ new DivElement()
+ ..classes = ['memberItem']
+ ..children = [
+ new DivElement()
+ ..classes = ['memberName']
..text = 'deoptimizations',
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = '${_function.deoptimizations}'
],
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'optimizable',
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = _function.isOptimizable ? 'yes' : 'no'
],
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'inlinable',
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = _function.isInlinable ? 'yes' : 'no'
],
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'intrinsic',
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = _function.hasIntrinsic ? 'yes' : 'no'
],
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'recognized',
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = _function.isRecognized ? 'yes' : 'no'
],
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'native',
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = _function.isNative ? 'yes' : 'no'
],
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'vm name',
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = _function.vmName
]
]);
@@ -350,7 +395,7 @@
}
static String _functionKindToString(M.FunctionKind kind) {
- switch(kind) {
+ switch (kind) {
case M.FunctionKind.regular:
return 'regular';
case M.FunctionKind.closure:
diff --git a/runtime/observatory/lib/src/elements/general_error.dart b/runtime/observatory/lib/src/elements/general_error.dart
index 473e724..f902da8 100644
--- a/runtime/observatory/lib/src/elements/general_error.dart
+++ b/runtime/observatory/lib/src/elements/general_error.dart
@@ -15,8 +15,7 @@
class GeneralErrorElement extends HtmlElement implements Renderable {
static const tag = const Tag<GeneralErrorElement>('general-error',
- dependencies: const [NavTopMenuElement.tag,
- NavNotifyElement.tag]);
+ dependencies: const [NavTopMenuElement.tag, NavNotifyElement.tag]);
RenderingScheduler _r;
@@ -29,9 +28,8 @@
set message(String value) => _message = _r.checkAndReact(_message, value);
-
factory GeneralErrorElement(M.NotificationRepository notifications,
- {String message: '', RenderingQueue queue}) {
+ {String message: '', RenderingQueue queue}) {
assert(notifications != null);
assert(message != null);
GeneralErrorElement e = document.createElement(tag.name);
@@ -62,11 +60,13 @@
new NavTopMenuElement(queue: _r.queue),
new NavNotifyElement(_notifications, queue: _r.queue)
]),
- new DivElement()..classes = ['content-centered']
+ new DivElement()
+ ..classes = ['content-centered']
..children = [
new HeadingElement.h1()..text = 'Error',
new BRElement(),
- new DivElement()..classes = ['well']
+ new DivElement()
+ ..classes = ['well']
..text = message
]
];
diff --git a/runtime/observatory/lib/src/elements/heap_map.dart b/runtime/observatory/lib/src/elements/heap_map.dart
index 85b97c8..bd43b45 100644
--- a/runtime/observatory/lib/src/elements/heap_map.dart
+++ b/runtime/observatory/lib/src/elements/heap_map.dart
@@ -19,20 +19,19 @@
import 'package:observatory/src/elements/nav/refresh.dart';
import 'package:observatory/src/elements/nav/top_menu.dart';
import 'package:observatory/src/elements/nav/vm_menu.dart';
-class HeapMapElement extends HtmlElement implements Renderable {
- static const tag = const Tag<HeapMapElement>('heap-map',
- dependencies: const [
- NavTopMenuElement.tag,
- NavVMMenuElement.tag,
- NavIsolateMenuElement.tag,
- NavRefreshElement.tag,
- NavNotifyElement.tag,
- ]);
+
+class HeapMapElement extends HtmlElement implements Renderable {
+ static const tag = const Tag<HeapMapElement>('heap-map', dependencies: const [
+ NavTopMenuElement.tag,
+ NavVMMenuElement.tag,
+ NavIsolateMenuElement.tag,
+ NavRefreshElement.tag,
+ NavNotifyElement.tag,
+ ]);
RenderingScheduler<HeapMapElement> _r;
- Stream<RenderedEvent<HeapMapElement>> get onRendered =>
- _r.onRendered;
+ Stream<RenderedEvent<HeapMapElement>> get onRendered => _r.onRendered;
M.VM _vm;
M.IsolateRef _isolate;
@@ -43,9 +42,8 @@
M.NotificationRepository get notifications => _notifications;
factory HeapMapElement(M.VM vm, M.IsolateRef isolate,
- M.EventRepository events,
- M.NotificationRepository notifications,
- {RenderingQueue queue}) {
+ M.EventRepository events, M.NotificationRepository notifications,
+ {RenderingQueue queue}) {
assert(vm != null);
assert(isolate != null);
assert(events != null);
@@ -95,10 +93,10 @@
void render() {
if (_canvas == null) {
_canvas = new CanvasElement()
- ..width = 1
- ..height= 1
- ..onMouseMove.listen(_handleMouseMove)
- ..onMouseDown.listen(_handleClick);
+ ..width = 1
+ ..height = 1
+ ..onMouseMove.listen(_handleMouseMove)
+ ..onMouseDown.listen(_handleClick);
}
children = [
navBar([
@@ -110,13 +108,15 @@
..onRefresh.listen((_) => _refresh()),
new NavNotifyElement(_notifications, queue: _r.queue)
]),
- new DivElement()..classes = ['content-centered-big']
+ new DivElement()
+ ..classes = ['content-centered-big']
..children = [
new HeadingElement.h2()..text = _status,
new HRElement(),
],
- new DivElement()..classes = ['flex-row']
- ..children = [_canvas]
+ new DivElement()
+ ..classes = ['flex-row']
+ ..children = [_canvas]
];
}
@@ -189,8 +189,9 @@
break;
}
}
- return new ObjectInfo(int.parse(page['objectStart']) +
- pageOffset * _fragmentation['unitSizeBytes'],
+ return new ObjectInfo(
+ int.parse(page['objectStart']) +
+ pageOffset * _fragmentation['unitSizeBytes'],
size * _fragmentation['unitSizeBytes']);
}
@@ -213,8 +214,8 @@
isolate.getObjectByAddress(address).then((result) {
if (result.type != 'Sentinel') {
new AnchorElement(
- href: Uris.inspect(_isolate, object: result as S.HeapObject)
- ).click();
+ href: Uris.inspect(_isolate, object: result as S.HeapObject))
+ .click();
}
});
}
@@ -229,10 +230,10 @@
var width = max(_canvas.parent.client.width, 1);
_pageHeight = _PAGE_SEPARATION_HEIGHT +
_fragmentation['pageSizeBytes'] ~/
- _fragmentation['unitSizeBytes'] ~/ width;
+ _fragmentation['unitSizeBytes'] ~/
+ width;
var height = min(_pageHeight * pages.length, _MAX_CANVAS_HEIGHT);
- _fragmentationData =
- _canvas.context2D.createImageData(width, height);
+ _fragmentationData = _canvas.context2D.createImageData(width, height);
_canvas.width = _fragmentationData.width;
_canvas.height = _fragmentationData.height;
_renderPages(0);
@@ -294,12 +295,10 @@
PixelReference._fromDataIndex(this._data, this._dataIndex);
- Point<int> get point =>
- new Point(index % _data.width, index ~/ _data.width);
+ Point<int> get point => new Point(index % _data.width, index ~/ _data.width);
void set color(Iterable<int> color) {
- _data.data.setRange(
- _dataIndex, _dataIndex + NUM_COLOR_COMPONENTS, color);
+ _data.data.setRange(_dataIndex, _dataIndex + NUM_COLOR_COMPONENTS, color);
}
Iterable<int> get color =>
diff --git a/runtime/observatory/lib/src/elements/heap_snapshot.dart b/runtime/observatory/lib/src/elements/heap_snapshot.dart
index 51c451e..2fd6e78 100644
--- a/runtime/observatory/lib/src/elements/heap_snapshot.dart
+++ b/runtime/observatory/lib/src/elements/heap_snapshot.dart
@@ -24,22 +24,19 @@
import 'package:observatory/src/elements/nav/vm_menu.dart';
import 'package:observatory/utils.dart';
-enum HeapSnapshotTreeMode {
- dominatorTree,
- groupByClass
-}
+enum HeapSnapshotTreeMode { dominatorTree, groupByClass }
-class HeapSnapshotElement extends HtmlElement implements Renderable {
- static const tag = const Tag<HeapSnapshotElement>('heap-snapshot',
- dependencies: const [
- ClassRefElement.tag,
- NavTopMenuElement.tag,
- NavVMMenuElement.tag,
- NavIsolateMenuElement.tag,
- NavRefreshElement.tag,
- NavNotifyElement.tag,
- VirtualTreeElement.tag,
- ]);
+class HeapSnapshotElement extends HtmlElement implements Renderable {
+ static const tag =
+ const Tag<HeapSnapshotElement>('heap-snapshot', dependencies: const [
+ ClassRefElement.tag,
+ NavTopMenuElement.tag,
+ NavVMMenuElement.tag,
+ NavIsolateMenuElement.tag,
+ NavRefreshElement.tag,
+ NavNotifyElement.tag,
+ VirtualTreeElement.tag,
+ ]);
RenderingScheduler<HeapSnapshotElement> _r;
@@ -56,18 +53,19 @@
M.HeapSnapshotLoadingProgress _progress;
HeapSnapshotTreeMode _mode = HeapSnapshotTreeMode.dominatorTree;
-
M.IsolateRef get isolate => _isolate;
M.NotificationRepository get notifications => _notifications;
M.HeapSnapshotRepository get profiles => _snapshots;
M.VMRef get vm => _vm;
- factory HeapSnapshotElement(M.VM vm, M.IsolateRef isolate,
- M.EventRepository events,
- M.NotificationRepository notifications,
- M.HeapSnapshotRepository snapshots,
- M.InstanceRepository instances,
- {RenderingQueue queue}) {
+ factory HeapSnapshotElement(
+ M.VM vm,
+ M.IsolateRef isolate,
+ M.EventRepository events,
+ M.NotificationRepository notifications,
+ M.HeapSnapshotRepository snapshots,
+ M.InstanceRepository instances,
+ {RenderingQueue queue}) {
assert(vm != null);
assert(isolate != null);
assert(events != null);
@@ -109,10 +107,10 @@
new NavIsolateMenuElement(_isolate, _events, queue: _r.queue),
navMenu('heap snapshot'),
new NavRefreshElement(queue: _r.queue)
- ..disabled = M.isHeapSnapshotProgressRunning(_progress?.status)
- ..onRefresh.listen((e) {
- _refresh();
- }),
+ ..disabled = M.isHeapSnapshotProgressRunning(_progress?.status)
+ ..onRefresh.listen((e) {
+ _refresh();
+ }),
new NavNotifyElement(_notifications, queue: _r.queue)
]),
];
@@ -121,12 +119,12 @@
return;
}
switch (_progress.status) {
- case M.HeapSnapshotLoadingStatus.fetching :
+ case M.HeapSnapshotLoadingStatus.fetching:
content.addAll(_createStatusMessage('Fetching snapshot from VM...',
description: _progress.stepDescription,
progress: _progress.progress));
break;
- case M.HeapSnapshotLoadingStatus.loading :
+ case M.HeapSnapshotLoadingStatus.loading:
content.addAll(_createStatusMessage('Loading snapshot...',
description: _progress.stepDescription,
progress: _progress.progress));
@@ -158,15 +156,20 @@
static List<Element> _createStatusMessage(String message,
{String description: '', double progress: 0.0}) {
return [
- new DivElement()..classes = ['content-centered-big']
+ new DivElement()
+ ..classes = ['content-centered-big']
..children = [
- new DivElement()..classes = ['statusBox', 'shadow', 'center']
+ new DivElement()
+ ..classes = ['statusBox', 'shadow', 'center']
..children = [
- new DivElement()..classes = ['statusMessage']
+ new DivElement()
+ ..classes = ['statusMessage']
..text = message,
- new DivElement()..classes = ['statusDescription']
+ new DivElement()
+ ..classes = ['statusDescription']
..text = description,
- new DivElement()..style.background = '#0489c3'
+ new DivElement()
+ ..style.background = '#0489c3'
..style.width = '$progress%'
..style.height = '15px'
..style.borderRadius = '4px'
@@ -179,43 +182,60 @@
List<Element> _createReport() {
var report = [
- new DivElement()..classes = ['content-centered-big']
+ new DivElement()
+ ..classes = ['content-centered-big']
..children = [
- new DivElement()..classes = ['memberList']
+ new DivElement()
+ ..classes = ['memberList']
..children = [
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'Refreshed ',
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = Utils.formatDateTime(_snapshot.timestamp)
],
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'Objects ',
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = '${_snapshot.objects}'
],
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'References ',
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = '${_snapshot.references}'
],
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'Size ',
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = Utils.formatSize(_snapshot.size)
],
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'Analysis ',
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..children = _createModeSelect()
]
]
@@ -223,23 +243,24 @@
];
switch (_mode) {
case HeapSnapshotTreeMode.dominatorTree:
- _tree = new VirtualTreeElement(_createDominator, _updateDominator,
- _getChildrenDominator,
+ _tree = new VirtualTreeElement(
+ _createDominator, _updateDominator, _getChildrenDominator,
items: _getChildrenDominator(_snapshot.dominatorTree),
queue: _r.queue);
_tree.expand(_snapshot.dominatorTree);
final text = 'In a heap dominator tree, an object X is a parent of '
- 'object Y if every path from the root to Y goes through '
- 'X. This allows you to find "choke points" that are '
- 'holding onto a lot of memory. If an object becomes '
- 'garbage, all its children in the dominator tree become '
- 'garbage as well. '
- 'The retained size of an object is the sum of the '
- 'retained sizes of its children in the dominator tree '
- 'plus its own shallow size, and is the amount of memory '
- 'that would be freed if the object became garbage.';
+ 'object Y if every path from the root to Y goes through '
+ 'X. This allows you to find "choke points" that are '
+ 'holding onto a lot of memory. If an object becomes '
+ 'garbage, all its children in the dominator tree become '
+ 'garbage as well. '
+ 'The retained size of an object is the sum of the '
+ 'retained sizes of its children in the dominator tree '
+ 'plus its own shallow size, and is the amount of memory '
+ 'that would be freed if the object became garbage.';
report.addAll([
- new DivElement()..classes = ['content-centered-big', 'explanation']
+ new DivElement()
+ ..classes = ['content-centered-big', 'explanation']
..text = text
..title = text,
_tree
@@ -248,8 +269,9 @@
case HeapSnapshotTreeMode.groupByClass:
final items = _snapshot.classReferences.toList();
items.sort((a, b) => b.shallowSize - a.shallowSize);
- _tree = new VirtualTreeElement(_createGroup, _updateGroup,
- _getChildrenGroup, items: items, queue: _r.queue);
+ _tree = new VirtualTreeElement(
+ _createGroup, _updateGroup, _getChildrenGroup,
+ items: items, queue: _r.queue);
_tree.expand(_snapshot.dominatorTree);
report.add(_tree);
break;
@@ -263,12 +285,15 @@
return new DivElement()
..classes = ['tree-item']
..children = [
- new SpanElement()..classes = ['size']
+ new SpanElement()
+ ..classes = ['size']
..title = 'retained size',
new SpanElement()..classes = ['lines'],
- new ButtonElement()..classes = ['expander']
+ new ButtonElement()
+ ..classes = ['expander']
..onClick.listen((_) => toggle(autoToggleSingleChildNodes: true)),
- new SpanElement()..classes = ['percentage']
+ new SpanElement()
+ ..classes = ['percentage']
..title = 'percentage of heap being retained',
new SpanElement()..classes = ['name']
];
@@ -278,12 +303,15 @@
return new DivElement()
..classes = ['tree-item']
..children = [
- new SpanElement()..classes = ['size']
+ new SpanElement()
+ ..classes = ['size']
..title = 'shallow size',
new SpanElement()..classes = ['lines'],
- new ButtonElement()..classes = ['expander']
+ new ButtonElement()
+ ..classes = ['expander']
..onClick.listen((_) => toggle(autoToggleSingleChildNodes: true)),
- new SpanElement()..classes = ['count']
+ new SpanElement()
+ ..classes = ['count']
..title = 'shallow size',
new SpanElement()..classes = ['name']
];
@@ -295,8 +323,9 @@
static _getChildrenDominator(M.HeapSnapshotDominatorNode node) {
final list = node.children.toList();
list.sort((a, b) => b.retainedSize - a.retainedSize);
- return list.where((child) => child.retainedSize >= kMinRetainedSize)
- .take(kMaxChildren);
+ return list
+ .where((child) => child.retainedSize >= kMinRetainedSize)
+ .take(kMaxChildren);
}
static _getChildrenGroup(item) {
@@ -310,8 +339,8 @@
return const [];
}
- void _updateDominator(HtmlElement element, M.HeapSnapshotDominatorNode node,
- int depth) {
+ void _updateDominator(
+ HtmlElement element, M.HeapSnapshotDominatorNode node, int depth) {
element.children[0].text = Utils.formatSize(node.retainedSize);
_updateLines(element.children[1].children, depth);
if (_getChildrenDominator(node).isNotEmpty) {
@@ -319,13 +348,15 @@
} else {
element.children[2].text = '';
}
- element.children[3].text = Utils.formatPercentNormalized(
- node.retainedSize * 1.0 / _snapshot.size);
- final wrapper = new SpanElement()..classes = ['name']
- ..text = 'Loading...';
+ element.children[3].text =
+ Utils.formatPercentNormalized(node.retainedSize * 1.0 / _snapshot.size);
+ final wrapper = new SpanElement()
+ ..classes = ['name']
+ ..text = 'Loading...';
element.children[4] = wrapper;
node.object.then((object) {
- wrapper..text = ''
+ wrapper
+ ..text = ''
..children = [anyRef(_isolate, object, _instances, queue: _r.queue)];
});
}
@@ -346,30 +377,34 @@
element.children[2].text = '';
}
element.children[3].text = '';
+ int references = 0;
+ for (var referenceGroup in item) {
+ references += referenceGroup.count;
+ }
if (item is Iterable<M.HeapSnapshotClassInbound>) {
- element.children[4] = new SpanElement()..classes = ['name']
- ..text = '${item.length} Incoming references';
+ element.children[4] = new SpanElement()
+ ..classes = ['name']
+ ..text = '$references incoming references';
} else {
- element.children[4] = new SpanElement()..classes = ['name']
- ..text = '${item.length} Outgoing references';
+ element.children[4] = new SpanElement()
+ ..classes = ['name']
+ ..text = '$references outgoing references';
}
} else {
element.children[0].text = '';
element.children[2].text = '';
element.children[3].text = '';
element.children[4] = new SpanElement()..classes = ['name'];
- if (item is M.HeapSnapshotClassInbound){
+ if (item is M.HeapSnapshotClassInbound) {
element.children[3].text =
'${item.count} references from instances of ';
element.children[4].children = [
- new ClassRefElement(_isolate, item.source,
- queue: _r.queue)
+ new ClassRefElement(_isolate, item.source, queue: _r.queue)
];
- } else if (item is M.HeapSnapshotClassOutbound){
+ } else if (item is M.HeapSnapshotClassOutbound) {
element.children[3]..text = '${item.count} references to instances of ';
element.children[4].children = [
- new ClassRefElement(_isolate, item.target,
- queue: _r.queue)
+ new ClassRefElement(_isolate, item.target, queue: _r.queue)
];
}
}
@@ -387,8 +422,10 @@
static String modeToString(HeapSnapshotTreeMode mode) {
switch (mode) {
- case HeapSnapshotTreeMode.dominatorTree: return 'Dominator tree';
- case HeapSnapshotTreeMode.groupByClass: return 'Group by class';
+ case HeapSnapshotTreeMode.dominatorTree:
+ return 'Dominator tree';
+ case HeapSnapshotTreeMode.groupByClass:
+ return 'Group by class';
}
throw new Exception('Unknown ProfileTreeMode');
}
@@ -396,17 +433,18 @@
List<Element> _createModeSelect() {
var s;
return [
- s = new SelectElement()..classes = ['analysis-select']
+ s = new SelectElement()
+ ..classes = ['analysis-select']
..value = modeToString(_mode)
..children = HeapSnapshotTreeMode.values.map((mode) {
- return new OptionElement(value: modeToString(mode),
- selected: _mode == mode)
- ..text = modeToString(mode);
- }).toList(growable: false)
+ return new OptionElement(
+ value: modeToString(mode),
+ selected: _mode == mode)..text = modeToString(mode);
+ }).toList(growable: false)
..onChange.listen((_) {
- _mode = HeapSnapshotTreeMode.values[s.selectedIndex];
- _r.dirty();
- })
+ _mode = HeapSnapshotTreeMode.values[s.selectedIndex];
+ _r.dirty();
+ })
];
}
}
diff --git a/runtime/observatory/lib/src/elements/helpers/any_ref.dart b/runtime/observatory/lib/src/elements/helpers/any_ref.dart
index 704e1a5..47d3877 100644
--- a/runtime/observatory/lib/src/elements/helpers/any_ref.dart
+++ b/runtime/observatory/lib/src/elements/helpers/any_ref.dart
@@ -25,11 +25,14 @@
import 'package:observatory/src/elements/token_stream_ref.dart';
import 'package:observatory/src/elements/unknown_ref.dart';
-Element anyRef(M.IsolateRef isolate, ref,
- M.InstanceRepository instances, {RenderingQueue queue}) {
+Element anyRef(M.IsolateRef isolate, ref, M.InstanceRepository instances,
+ {RenderingQueue queue}) {
if (ref is M.Guarded) {
- return anyRef(isolate, ref.asSentinel ?? ref.asValue, instances,
- queue: queue);
+ if (ref.isSentinel) {
+ return anyRef(isolate, ref.asSentinel, instances, queue: queue);
+ } else {
+ return anyRef(isolate, ref.asValue, instances, queue: queue);
+ }
} else if (ref is M.ObjectRef) {
if (ref is M.ClassRef) {
return new ClassRefElement(isolate, ref, queue: queue);
@@ -37,11 +40,11 @@
return new CodeRefElement(isolate, ref, queue: queue);
} else if (ref is M.ContextRef) {
return new ContextRefElement(isolate, ref, queue: queue);
- } else if (ref is M.Error ) {
+ } else if (ref is M.Error) {
return new ErrorRefElement(ref, queue: queue);
} else if (ref is M.FieldRef) {
return new FieldRefElement(isolate, ref, instances, queue: queue);
- } else if (ref is M.FunctionRef) {
+ } else if (ref is M.FunctionRef) {
return new FunctionRefElement(isolate, ref, queue: queue);
} else if (ref is M.ICDataRef) {
return new ICDataRefElement(isolate, ref, queue: queue);
@@ -72,5 +75,5 @@
} else if (ref is M.Sentinel) {
return new SentinelValueElement(ref, queue: queue);
}
- throw new Exception('Unknown runtimeType (${ref.runtimeType})');
+ throw new Exception('Unknown ref type (${ref.runtimeType})');
}
diff --git a/runtime/observatory/lib/src/elements/helpers/nav_bar.dart b/runtime/observatory/lib/src/elements/helpers/nav_bar.dart
index 5c1c272..f15acfa 100644
--- a/runtime/observatory/lib/src/elements/helpers/nav_bar.dart
+++ b/runtime/observatory/lib/src/elements/helpers/nav_bar.dart
@@ -9,7 +9,6 @@
return document.createElement('nav')
..classes = ['nav-bar']
..children = [
- new UListElement()
- ..children = content,
+ new UListElement()..children = content,
];
}
diff --git a/runtime/observatory/lib/src/elements/helpers/nav_menu.dart b/runtime/observatory/lib/src/elements/helpers/nav_menu.dart
index 1e8940e..d1fd791 100644
--- a/runtime/observatory/lib/src/elements/helpers/nav_menu.dart
+++ b/runtime/observatory/lib/src/elements/helpers/nav_menu.dart
@@ -8,14 +8,14 @@
assert(label != null);
assert(content != null);
assert(link != null);
- return new LIElement()..classes = ['nav-menu']
+ return new LIElement()
+ ..classes = ['nav-menu']
..children = [
- new SpanElement()..classes = ['nav-menu_label']
+ new SpanElement()
+ ..classes = ['nav-menu_label']
..children = [
- new AnchorElement(href: link)
- ..text = label,
- new UListElement()
- ..children = content
+ new AnchorElement(href: link)..text = label,
+ new UListElement()..children = content
]
];
}
diff --git a/runtime/observatory/lib/src/elements/helpers/rendering_scheduler.dart b/runtime/observatory/lib/src/elements/helpers/rendering_scheduler.dart
index d5ba83d..b0f280a 100644
--- a/runtime/observatory/lib/src/elements/helpers/rendering_scheduler.dart
+++ b/runtime/observatory/lib/src/elements/helpers/rendering_scheduler.dart
@@ -16,6 +16,7 @@
class RenderedEvent<T> {
/// Renderable to which the event is related
final T element;
+
/// Is another rendering scheduled for this element.
final bool otherRenderScheduled;
@@ -31,12 +32,16 @@
bool _dirty = false;
bool _renderingScheduled = false;
bool _notificationScheduled = false;
+
/// Element managed by this scheduler.
final T element;
+
/// Queue used for rendering operations.
final RenderingQueue queue;
+
/// Does the element need a new rendering cycle.
bool get isDirty => _dirty;
+
/// Is the scheduler enabled.
bool get isEnabled => _enabled;
@@ -48,7 +53,9 @@
/// If no queue is provided it will create a new default configured queue.
factory RenderingScheduler(T element, {RenderingQueue queue}) {
assert(element != null);
- if (queue == null) { queue = new RenderingQueue(); }
+ if (queue == null) {
+ queue = new RenderingQueue();
+ }
return new RenderingScheduler<T>._(element, queue);
}
@@ -83,8 +90,10 @@
/// If value changes a new rendering is scheduled.
/// set attr(T v) => _attr = _r.checkAndReact(_attr, v);
dynamic checkAndReact(dynamic oldValue, dynamic newValue) {
- if (oldValue != newValue) dirty();
- else scheduleNotification();
+ if (oldValue != newValue)
+ dirty();
+ else
+ scheduleNotification();
return newValue;
}
diff --git a/runtime/observatory/lib/src/elements/helpers/tag.dart b/runtime/observatory/lib/src/elements/helpers/tag.dart
index 177e238..d5b1e55 100644
--- a/runtime/observatory/lib/src/elements/helpers/tag.dart
+++ b/runtime/observatory/lib/src/elements/helpers/tag.dart
@@ -8,10 +8,11 @@
class Tag<T extends HtmlElement> {
/// Tag name.
final String name;
+
/// Dependend tags that need to be registred for this tag to work properly.
final Iterable<Tag> dependencies;
- const Tag(this.name, {this.dependencies : const []});
+ const Tag(this.name, {this.dependencies: const []});
static final Map<Type, String> _tagByClass = <Type, String>{};
static final Map<String, Type> _classByTag = <String, Type>{};
diff --git a/runtime/observatory/lib/src/elements/helpers/uris.dart b/runtime/observatory/lib/src/elements/helpers/uris.dart
index 3033171..defa2b0 100644
--- a/runtime/observatory/lib/src/elements/helpers/uris.dart
+++ b/runtime/observatory/lib/src/elements/helpers/uris.dart
@@ -8,42 +8,42 @@
abstract class Uris {
static String _isolatePage(String path, M.IsolateRef isolate,
{M.ObjectRef object}) {
- final parameters = { 'isolateId': isolate.id };
+ final parameters = {'isolateId': isolate.id};
if (object != null) parameters['objectId'] = object.id;
return '#' + new Uri(path: path, queryParameters: parameters).toString();
}
- static String allocationProfiler(M.IsolateRef isolate)
- => _isolatePage('/allocation-profiler', isolate);
- static String classTree(M.IsolateRef isolate)
- => _isolatePage('/class-tree', isolate);
- static String cpuProfiler(M.IsolateRef isolate)
- => _isolatePage('/profiler', isolate);
- static String cpuProfilerTable(M.IsolateRef isolate)
- => _isolatePage('/profiler-table', isolate);
- static String debugger(M.IsolateRef isolate)
- => _isolatePage('/debugger', isolate);
+ static String allocationProfiler(M.IsolateRef isolate) =>
+ _isolatePage('/allocation-profiler', isolate);
+ static String classTree(M.IsolateRef isolate) =>
+ _isolatePage('/class-tree', isolate);
+ static String cpuProfiler(M.IsolateRef isolate) =>
+ _isolatePage('/profiler', isolate);
+ static String cpuProfilerTable(M.IsolateRef isolate) =>
+ _isolatePage('/profiler-table', isolate);
+ static String debugger(M.IsolateRef isolate) =>
+ _isolatePage('/debugger', isolate);
static String flags() => '#/flags';
- static String heapMap(M.IsolateRef isolate)
- => _isolatePage('/heap-map', isolate);
- static String heapSnapshot(M.IsolateRef isolate)
- => _isolatePage('/heap-snapshot', isolate);
+ static String heapMap(M.IsolateRef isolate) =>
+ _isolatePage('/heap-map', isolate);
+ static String heapSnapshot(M.IsolateRef isolate) =>
+ _isolatePage('/heap-snapshot', isolate);
static String inspect(M.IsolateRef isolate, {M.ObjectRef object, int pos}) {
if (pos == null) {
return _isolatePage('/inspect', isolate, object: object);
}
return _isolatePage('/inspect', isolate, object: object) + '---pos=${pos}';
}
- static String logging(M.IsolateRef isolate)
- => _isolatePage('/logging', isolate);
- static String metrics(M.IsolateRef isolate)
- => _isolatePage('/metrics', isolate);
- static String objectStore(M.IsolateRef isolate)
- => _isolatePage('/object-store', isolate);
- static String persistentHandles(M.IsolateRef isolate)
- => _isolatePage('/persistent-handles', isolate);
- static String ports(M.IsolateRef isolate)
- => _isolatePage('/ports', isolate);
+
+ static String logging(M.IsolateRef isolate) =>
+ _isolatePage('/logging', isolate);
+ static String metrics(M.IsolateRef isolate) =>
+ _isolatePage('/metrics', isolate);
+ static String objectStore(M.IsolateRef isolate) =>
+ _isolatePage('/object-store', isolate);
+ static String persistentHandles(M.IsolateRef isolate) =>
+ _isolatePage('/persistent-handles', isolate);
+ static String ports(M.IsolateRef isolate) => _isolatePage('/ports', isolate);
static String timeline() => '#/timeline';
static String vm() => '#/vm';
static String vmConnect() => '#/vm-connect';
diff --git a/runtime/observatory/lib/src/elements/icdata_ref.dart b/runtime/observatory/lib/src/elements/icdata_ref.dart
index 704109e..613118c 100644
--- a/runtime/observatory/lib/src/elements/icdata_ref.dart
+++ b/runtime/observatory/lib/src/elements/icdata_ref.dart
@@ -4,8 +4,7 @@
import 'dart:html';
import 'dart:async';
-import 'package:observatory/models.dart' as M
- show IsolateRef, ICDataRef;
+import 'package:observatory/models.dart' as M show IsolateRef, ICDataRef;
import 'package:observatory/src/elements/helpers/rendering_scheduler.dart';
import 'package:observatory/src/elements/helpers/tag.dart';
import 'package:observatory/src/elements/helpers/uris.dart';
@@ -53,7 +52,8 @@
children = [
new AnchorElement(href: Uris.inspect(_isolate, object: _icdata))
..children = [
- new SpanElement()..classes = ['emphasize']
+ new SpanElement()
+ ..classes = ['emphasize']
..text = 'ICData',
new SpanElement()..text = ' (${_icdata.selector})'
]
diff --git a/runtime/observatory/lib/src/elements/icdata_view.dart b/runtime/observatory/lib/src/elements/icdata_view.dart
index d21c164..87c3b6c 100644
--- a/runtime/observatory/lib/src/elements/icdata_view.dart
+++ b/runtime/observatory/lib/src/elements/icdata_view.dart
@@ -19,18 +19,18 @@
import 'package:observatory/src/elements/object_common.dart';
import 'package:observatory/src/elements/view_footer.dart';
-class ICDataViewElement extends HtmlElement implements Renderable {
- static const tag = const Tag<ICDataViewElement>('icdata-view',
- dependencies: const [
- CurlyBlockElement.tag,
- NavTopMenuElement.tag,
- NavVMMenuElement.tag,
- NavIsolateMenuElement.tag,
- NavRefreshElement.tag,
- NavNotifyElement.tag,
- ObjectCommonElement.tag,
- ViewFooterElement.tag
- ]);
+class ICDataViewElement extends HtmlElement implements Renderable {
+ static const tag =
+ const Tag<ICDataViewElement>('icdata-view', dependencies: const [
+ CurlyBlockElement.tag,
+ NavTopMenuElement.tag,
+ NavVMMenuElement.tag,
+ NavIsolateMenuElement.tag,
+ NavRefreshElement.tag,
+ NavNotifyElement.tag,
+ ObjectCommonElement.tag,
+ ViewFooterElement.tag
+ ]);
RenderingScheduler<ICDataViewElement> _r;
@@ -48,22 +48,24 @@
M.RetainingPathRepository _retainingPaths;
M.InstanceRepository _instances;
-
M.VMRef get vm => _vm;
M.IsolateRef get isolate => _isolate;
M.NotificationRepository get notifications => _notifications;
M.ICData get icdata => _icdata;
- factory ICDataViewElement(M.VM vm, M.IsolateRef isolate, M.ICData icdata,
- M.EventRepository events,
- M.NotificationRepository notifications,
- M.ICDataRepository icdatas,
- M.RetainedSizeRepository retainedSizes,
- M.ReachableSizeRepository reachableSizes,
- M.InboundReferencesRepository references,
- M.RetainingPathRepository retainingPaths,
- M.InstanceRepository instances,
- {RenderingQueue queue}) {
+ factory ICDataViewElement(
+ M.VM vm,
+ M.IsolateRef isolate,
+ M.ICData icdata,
+ M.EventRepository events,
+ M.NotificationRepository notifications,
+ M.ICDataRepository icdatas,
+ M.RetainedSizeRepository retainedSizes,
+ M.ReachableSizeRepository reachableSizes,
+ M.InboundReferencesRepository references,
+ M.RetainingPathRepository retainingPaths,
+ M.InstanceRepository instances,
+ {RenderingQueue queue}) {
assert(vm != null);
assert(isolate != null);
assert(events != null);
@@ -114,68 +116,83 @@
new NavIsolateMenuElement(_isolate, _events, queue: _r.queue),
navMenu('icdata'),
new NavRefreshElement(queue: _r.queue)
- ..onRefresh.listen((e) async {
- e.element.disabled = true;
- _icdata = await _icdatas.get(_isolate, _icdata.id);
- _r.dirty();
- }),
+ ..onRefresh.listen((e) async {
+ e.element.disabled = true;
+ _icdata = await _icdatas.get(_isolate, _icdata.id);
+ _r.dirty();
+ }),
new NavNotifyElement(_notifications, queue: _r.queue)
]),
- new DivElement()..classes = ['content-centered-big']
+ new DivElement()
+ ..classes = ['content-centered-big']
..children = [
new HeadingElement.h2()..text = 'ICData',
new HRElement(),
new ObjectCommonElement(_isolate, _icdata, _retainedSizes,
- _reachableSizes, _references, _retainingPaths,
- _instances, queue: _r.queue),
- new DivElement()..classes = ['memberList']
+ _reachableSizes, _references, _retainingPaths, _instances,
+ queue: _r.queue),
+ new DivElement()
+ ..classes = ['memberList']
..children = [
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'selector',
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = _icdata.selector
],
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'owner',
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..children = [
_icdata.dartOwner == null
- ? (new SpanElement()..text = '<none>')
- : anyRef(_isolate, _icdata.dartOwner, _instances,
- queue: _r.queue)
+ ? (new SpanElement()..text = '<none>')
+ : anyRef(_isolate, _icdata.dartOwner, _instances,
+ queue: _r.queue)
]
],
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'argumentsDescriptor',
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..children = [
_icdata.argumentsDescriptor == null
- ? (new SpanElement()..text = '<none>')
- : anyRef(_isolate, _icdata.argumentsDescriptor,
- _instances, queue: _r.queue)
+ ? (new SpanElement()..text = '<none>')
+ : anyRef(
+ _isolate, _icdata.argumentsDescriptor, _instances,
+ queue: _r.queue)
]
],
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'entries',
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..children = [
_icdata.entries == null
- ? (new SpanElement()..text = '<none>')
- : anyRef(_isolate, _icdata.entries, _instances,
- queue: _r.queue)
+ ? (new SpanElement()..text = '<none>')
+ : anyRef(_isolate, _icdata.entries, _instances,
+ queue: _r.queue)
]
]
],
- new HRElement(),
- new ViewFooterElement(queue: _r.queue)
+ new HRElement(),
+ new ViewFooterElement(queue: _r.queue)
]
];
}
diff --git a/runtime/observatory/lib/src/elements/inbound_references.dart b/runtime/observatory/lib/src/elements/inbound_references.dart
index f8d69f3..8e68a00 100644
--- a/runtime/observatory/lib/src/elements/inbound_references.dart
+++ b/runtime/observatory/lib/src/elements/inbound_references.dart
@@ -13,15 +13,12 @@
class InboundReferencesElement extends HtmlElement implements Renderable {
static const tag = const Tag<InboundReferencesElement>('inbound-references',
- dependencies: const [
- CurlyBlockElement.tag,
- InstanceRefElement.tag
- ]);
+ dependencies: const [CurlyBlockElement.tag, InstanceRefElement.tag]);
RenderingScheduler<InboundReferencesElement> _r;
Stream<RenderedEvent<InboundReferencesElement>> get onRendered =>
- _r.onRendered;
+ _r.onRendered;
M.IsolateRef _isolate;
M.ObjectRef _object;
@@ -97,30 +94,27 @@
if (reference.parentField != null) {
content.addAll([
new SpanElement()..text = 'from ',
- anyRef(_isolate, reference.parentField, _instances,
- queue: _r.queue),
+ anyRef(_isolate, reference.parentField, _instances, queue: _r.queue),
new SpanElement()..text = ' of '
]);
} else if (reference.parentListIndex != null) {
- content.add(
- new SpanElement()
- ..text = 'from [ ${reference.parentListIndex} ] of '
- );
+ content.add(new SpanElement()
+ ..text = 'from [ ${reference.parentListIndex} ] of ');
} else if (reference.parentWordOffset != null) {
- content.add(
- new SpanElement()
- ..text = 'from word [ ${reference.parentWordOffset} ] of '
- );
+ content.add(new SpanElement()
+ ..text = 'from word [ ${reference.parentWordOffset} ] of ');
}
content.addAll([
anyRef(_isolate, reference.source, _instances, queue: _r.queue),
new SpanElement()..text = ' referenced by ',
- new InboundReferencesElement(_isolate, reference.source, _references,
- _instances, queue: _r.queue )
+ new InboundReferencesElement(
+ _isolate, reference.source, _references, _instances,
+ queue: _r.queue)
]);
- return new DivElement()..classes = ['indent']
- ..children = content;
+ return new DivElement()
+ ..classes = ['indent']
+ ..children = content;
}
}
diff --git a/runtime/observatory/lib/src/elements/instance_ref.dart b/runtime/observatory/lib/src/elements/instance_ref.dart
index f54b41b..9d5fcc9 100644
--- a/runtime/observatory/lib/src/elements/instance_ref.dart
+++ b/runtime/observatory/lib/src/elements/instance_ref.dart
@@ -11,7 +11,6 @@
import 'package:observatory/src/elements/helpers/rendering_scheduler.dart';
import 'package:observatory/src/elements/helpers/tag.dart';
import 'package:observatory/src/elements/helpers/uris.dart';
-import 'package:observatory/src/elements/sentinel_value.dart';
import 'package:observatory/utils.dart';
class InstanceRefElement extends HtmlElement implements Renderable {
@@ -31,7 +30,8 @@
M.InstanceRef get instance => _instance;
factory InstanceRefElement(M.IsolateRef isolate, M.InstanceRef instance,
- M.InstanceRepository instances, {RenderingQueue queue}) {
+ M.InstanceRepository instances,
+ {RenderingQueue queue}) {
assert(isolate != null);
assert(instance != null);
assert(instances != null);
@@ -66,7 +66,8 @@
new SpanElement()..text = ' ',
new CurlyBlockElement(expanded: _expanded, queue: _r.queue)
..content = [
- new DivElement()..classes = ['indent']
+ new DivElement()
+ ..classes = ['indent']
..children = _createValue()
]
..onToggle.listen((e) async {
@@ -93,12 +94,11 @@
return [];
}
final count = _loadedInstance.count;
- final button = new ButtonElement()
- ..text = 'show next ${count}';
+ final button = new ButtonElement()..text = 'show next ${count}';
button.onClick.listen((_) async {
button.disabled = true;
- _loadedInstance = await _instances.get(_isolate, _instance.id,
- count: count * 2);
+ _loadedInstance =
+ await _instances.get(_isolate, _instance.id, count: count * 2);
_r.dirty();
});
return [button];
@@ -120,8 +120,8 @@
case M.InstanceKind.string:
return [
new AnchorElement(href: Uris.inspect(_isolate, object: _instance))
- ..text = Utils.formatStringAsLiteral(_instance.valueAsString,
- _instance.valueAsStringIsTruncated)
+ ..text = Utils.formatStringAsLiteral(
+ _instance.valueAsString, _instance.valueAsStringIsTruncated)
];
case M.InstanceKind.type:
case M.InstanceKind.typeRef:
@@ -135,7 +135,8 @@
return [
new AnchorElement(href: Uris.inspect(_isolate, object: _instance))
..children = [
- new SpanElement()..classes = ['emphasize']
+ new SpanElement()
+ ..classes = ['emphasize']
..text = 'Closure',
new SpanElement()..text = _instance.closureFunction.name
]
@@ -144,7 +145,8 @@
return [
new AnchorElement(href: Uris.inspect(_isolate, object: _instance))
..children = [
- new SpanElement()..classes = ['emphasize']
+ new SpanElement()
+ ..classes = ['emphasize']
..text = _instance.clazz.name,
new SpanElement()..text = _instance.pattern.name
]
@@ -155,7 +157,8 @@
..text = _instance.clazz.name,
new CurlyBlockElement(queue: _r.queue)
..content = [
- new DivElement()..classes = ['stackTraceBox']
+ new DivElement()
+ ..classes = ['stackTraceBox']
..text = _instance.valueAsString
]
];
@@ -184,7 +187,8 @@
return [
new AnchorElement(href: Uris.inspect(_isolate, object: _instance))
..children = [
- new SpanElement()..classes = ['emphasize']
+ new SpanElement()
+ ..classes = ['emphasize']
..text = _instance.clazz.name,
new SpanElement()..text = ' (${_instance.length})'
]
@@ -232,52 +236,41 @@
return false;
}
}
+
List<Element> _createValue() {
if (_loadedInstance == null) {
return [new SpanElement()..text = 'Loading...'];
}
switch (_instance.kind) {
case M.InstanceKind.plainInstance:
- return _loadedInstance.fields.map((f) =>
- new DivElement()
- ..children = [
- new FieldRefElement(_isolate, f.decl, _instances,
- queue: _r.queue),
- new SpanElement()..text = ' = ',
- f.value.isSentinel
- ? new SentinelValueElement(f.value.asSentinel, queue: _r.queue)
- : new InstanceRefElement(_isolate, f.value.asValue, _instances,
- queue: _r.queue)
- ]).toList();
+ return _loadedInstance.fields
+ .map((f) => new DivElement()
+ ..children = [
+ new FieldRefElement(_isolate, f.decl, _instances,
+ queue: _r.queue),
+ new SpanElement()..text = ' = ',
+ anyRef(_isolate, f.value, _instances, queue: _r.queue)
+ ])
+ .toList();
case M.InstanceKind.list:
var index = 0;
- return _loadedInstance.elements.map((e) =>
- new DivElement()
- ..children = [
- new SpanElement()..text = '[ ${index++} ] : ',
- e.isSentinel
- ? new SentinelValueElement(e.asSentinel, queue: _r.queue)
- : anyRef(_isolate, e.asValue, _instances, queue: _r.queue)
- // should be:
- // new InstanceRefElement(_isolate, e.asValue, _instances,
- // queue: _r.queue)
- // in some situations we obtain values that are not InstanceRef.
- ]).toList()..addAll(_createShowMoreButton());
+ return _loadedInstance.elements
+ .map((element) => new DivElement()
+ ..children = [
+ new SpanElement()..text = '[ ${index++} ] : ',
+ anyRef(_isolate, element, _instances, queue: _r.queue)
+ ])
+ .toList()..addAll(_createShowMoreButton());
case M.InstanceKind.map:
- return _loadedInstance.associations.map((a) =>
- new DivElement()
- ..children = [
- new SpanElement()..text = '[ ',
- a.key.isSentinel
- ? new SentinelValueElement(a.key.asSentinel, queue: _r.queue)
- : new InstanceRefElement(_isolate, a.key.asValue, _instances,
- queue: _r.queue),
- new SpanElement()..text = ' ] : ',
- a.value.isSentinel
- ? new SentinelValueElement(a.value.asSentinel, queue: _r.queue)
- : new InstanceRefElement(_isolate, a.value.asValue, _instances,
- queue: _r.queue)
- ]).toList()..addAll(_createShowMoreButton());
+ return _loadedInstance.associations
+ .map((association) => new DivElement()
+ ..children = [
+ new SpanElement()..text = '[ ',
+ anyRef(_isolate, association.key, _instances, queue: _r.queue),
+ new SpanElement()..text = ' ] : ',
+ anyRef(_isolate, association.value, _instances, queue: _r.queue)
+ ])
+ .toList()..addAll(_createShowMoreButton());
case M.InstanceKind.uint8ClampedList:
case M.InstanceKind.uint8List:
case M.InstanceKind.uint16List:
@@ -294,8 +287,8 @@
case M.InstanceKind.float64x2List:
var index = 0;
return _loadedInstance.typedElements
- .map((e) => new DivElement()..text = '[ ${index++} ] : $e')
- .toList()..addAll(_createShowMoreButton());
+ .map((e) => new DivElement()..text = '[ ${index++} ] : $e')
+ .toList()..addAll(_createShowMoreButton());
case M.InstanceKind.mirrorReference:
return [
new SpanElement()..text = '<referent> : ',
@@ -310,7 +303,7 @@
new BRElement(),
new SpanElement()..text = '<value> : ',
new InstanceRefElement(_isolate, _loadedInstance.value, _instances,
- queue: _r.queue),
+ queue: _r.queue),
];
default:
return [];
diff --git a/runtime/observatory/lib/src/elements/instance_view.dart b/runtime/observatory/lib/src/elements/instance_view.dart
index 6f40929..1a33542 100644
--- a/runtime/observatory/lib/src/elements/instance_view.dart
+++ b/runtime/observatory/lib/src/elements/instance_view.dart
@@ -33,26 +33,26 @@
import 'package:observatory/utils.dart';
class InstanceViewElement extends HtmlElement implements Renderable {
- static const tag = const Tag<InstanceViewElement>('instance-view',
- dependencies: const [
- ClassRefElement.tag,
- ContextRefElement.tag,
- CurlyBlockElement.tag,
- FieldRefElement.tag,
- FunctionRefElement.tag,
- InstanceRefElement.tag,
- NavClassMenuElement.tag,
- NavLibraryMenuElement.tag,
- NavTopMenuElement.tag,
- NavVMMenuElement.tag,
- NavIsolateMenuElement.tag,
- NavRefreshElement.tag,
- NavNotifyElement.tag,
- ObjectCommonElement.tag,
- SourceInsetElement.tag,
- SourceLinkElement.tag,
- ViewFooterElement.tag
- ]);
+ static const tag =
+ const Tag<InstanceViewElement>('instance-view', dependencies: const [
+ ClassRefElement.tag,
+ ContextRefElement.tag,
+ CurlyBlockElement.tag,
+ FieldRefElement.tag,
+ FunctionRefElement.tag,
+ InstanceRefElement.tag,
+ NavClassMenuElement.tag,
+ NavLibraryMenuElement.tag,
+ NavTopMenuElement.tag,
+ NavVMMenuElement.tag,
+ NavIsolateMenuElement.tag,
+ NavRefreshElement.tag,
+ NavNotifyElement.tag,
+ ObjectCommonElement.tag,
+ SourceInsetElement.tag,
+ SourceLinkElement.tag,
+ ViewFooterElement.tag
+ ]);
RenderingScheduler<InstanceViewElement> _r;
@@ -78,28 +78,29 @@
M.FunctionRepository _functions;
M.SourceLocation _location;
-
M.VMRef get vm => _vm;
M.IsolateRef get isolate => _isolate;
M.NotificationRepository get notifications => _notifications;
M.Instance get instance => _instance;
- factory InstanceViewElement(M.VM vm, M.IsolateRef isolate,
- M.Instance instance,
- M.EventRepository events,
- M.NotificationRepository notifications,
- M.InstanceRepository instances,
- M.ClassRepository classes,
- M.RetainedSizeRepository retainedSizes,
- M.ReachableSizeRepository reachableSizes,
- M.InboundReferencesRepository references,
- M.RetainingPathRepository retainingPaths,
- M.ScriptRepository scripts,
- M.EvalRepository eval,
- M.TypeArgumentsRepository arguments,
- M.BreakpointRepository breakpoints,
- M.FunctionRepository functions,
- {RenderingQueue queue}) {
+ factory InstanceViewElement(
+ M.VM vm,
+ M.IsolateRef isolate,
+ M.Instance instance,
+ M.EventRepository events,
+ M.NotificationRepository notifications,
+ M.InstanceRepository instances,
+ M.ClassRepository classes,
+ M.RetainedSizeRepository retainedSizes,
+ M.ReachableSizeRepository reachableSizes,
+ M.InboundReferencesRepository references,
+ M.RetainingPathRepository retainingPaths,
+ M.ScriptRepository scripts,
+ M.EvalRepository eval,
+ M.TypeArgumentsRepository arguments,
+ M.BreakpointRepository breakpoints,
+ M.FunctionRepository functions,
+ {RenderingQueue queue}) {
assert(vm != null);
assert(isolate != null);
assert(events != null);
@@ -155,38 +156,38 @@
void render() {
final content = [
- new HeadingElement.h2()..text = M.isAbstractType(_instance.kind)
- ? 'type ${_instance.name}'
- : 'instance of ${_instance.clazz.name}',
+ new HeadingElement.h2()
+ ..text = M.isAbstractType(_instance.kind)
+ ? 'type ${_instance.name}'
+ : 'instance of ${_instance.clazz.name}',
new HRElement(),
new ObjectCommonElement(_isolate, _instance, _retainedSizes,
- _reachableSizes, _references, _retainingPaths,
- _instances, queue: _r.queue),
+ _reachableSizes, _references, _retainingPaths, _instances,
+ queue: _r.queue),
new BRElement(),
- new DivElement()..classes = ['memberList']
+ new DivElement()
+ ..classes = ['memberList']
..children = _createMembers(),
new HRElement(),
new EvalBoxElement(_isolate, _instance, _instances, _eval,
- quickExpressions: const ['toString()',
- 'runtimeType'],
- queue: _r.queue)
+ quickExpressions: const ['toString()', 'runtimeType'],
+ queue: _r.queue)
];
if (_location != null) {
content.addAll([
new HRElement(),
- new SourceInsetElement(_isolate, _location, _scripts, _instances,
- _events, queue: _r.queue)
+ new SourceInsetElement(
+ _isolate, _location, _scripts, _instances, _events,
+ queue: _r.queue)
]);
}
- content.addAll([
- new HRElement(),
- new ViewFooterElement(queue: _r.queue)
- ]);
+ content.addAll([new HRElement(), new ViewFooterElement(queue: _r.queue)]);
children = [
navBar(_createMenu()),
- new DivElement()..classes = ['content-centered-big']
+ new DivElement()
+ ..classes = ['content-centered-big']
..children = content
- ];
+ ];
}
List<Element> _createMenu() {
@@ -196,17 +197,16 @@
new NavIsolateMenuElement(_isolate, _events, queue: _r.queue)
];
if (_library != null) {
- menu.add(new NavLibraryMenuElement(_isolate, _library,
- queue: _r.queue));
+ menu.add(new NavLibraryMenuElement(_isolate, _library, queue: _r.queue));
}
menu.addAll([
new NavClassMenuElement(_isolate, _instance.clazz, queue: _r.queue),
navMenu('instance'),
new NavRefreshElement(queue: _r.queue)
- ..onRefresh.listen((e) {
- e.element.disabled = true;
- _refresh();
- }),
+ ..onRefresh.listen((e) {
+ e.element.disabled = true;
+ _refresh();
+ }),
new NavNotifyElement(_notifications, queue: _r.queue)
]);
return menu;
@@ -215,130 +215,158 @@
List<Element> _createMembers() {
final members = <Element>[];
if (_instance.valueAsString != null) {
- members.add(new DivElement()..classes = ['memberItem']
+ members.add(new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = _instance.kind == M.InstanceKind.string
- ? 'value as literal'
- : 'value',
- new DivElement()..classes = ['memberValue']
+ ? 'value as literal'
+ : 'value',
+ new DivElement()
+ ..classes = ['memberValue']
..text = _instance.kind == M.InstanceKind.string
- ? Utils.formatStringAsLiteral(_instance.valueAsString,
- _instance.valueAsStringIsTruncated)
- : _instance.valueAsString
+ ? Utils.formatStringAsLiteral(
+ _instance.valueAsString, _instance.valueAsStringIsTruncated)
+ : _instance.valueAsString
]);
}
if (_instance.typeClass != null) {
- members.add(new DivElement()..classes = ['memberItem']
+ members.add(new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'type class',
- new DivElement()..classes = ['memberValue']
+ new DivElement()
+ ..classes = ['memberValue']
..children = [
new ClassRefElement(_isolate, _instance.typeClass,
- queue: _r.queue)
+ queue: _r.queue)
]
]);
}
if (_typeArguments != null && _typeArguments.types.isNotEmpty) {
- members.add(new DivElement()..classes = ['memberItem']
+ members.add(new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'type arguments',
- new DivElement()..classes = ['memberValue']
- ..children = ([
- new SpanElement()..text = '< '
- ]
- ..addAll(_typeArguments.types.expand((type) => [
- new InstanceRefElement(_isolate, type, _instances, queue:
- _r.queue),
- new SpanElement()..text = ', '
- ]))
- ..removeLast()
- ..add(new SpanElement()..text = ' >'))
+ new DivElement()
+ ..classes = ['memberValue']
+ ..children = ([new SpanElement()..text = '< ']
+ ..addAll(_typeArguments.types.expand((type) => [
+ new InstanceRefElement(_isolate, type, _instances,
+ queue: _r.queue),
+ new SpanElement()..text = ', '
+ ]))
+ ..removeLast()
+ ..add(new SpanElement()..text = ' >'))
]);
}
if (_instance.parameterizedClass != null) {
- members.add(new DivElement()..classes = ['memberItem']
+ members.add(new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'parameterized class',
- new DivElement()..classes = ['memberValue']
+ new DivElement()
+ ..classes = ['memberValue']
..children = [
new ClassRefElement(_isolate, _instance.parameterizedClass,
- queue: _r.queue)
+ queue: _r.queue)
]
]);
}
if (_instance.parameterIndex != null) {
- members.add(new DivElement()..classes = ['memberItem']
+ members.add(new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'parameter index',
- new DivElement()..classes = ['memberValue']
+ new DivElement()
+ ..classes = ['memberValue']
..text = '${_instance.parameterIndex}'
]);
}
if (_instance.targetType != null) {
- members.add(new DivElement()..classes = ['memberItem']
+ members.add(new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'target type',
- new DivElement()..classes = ['memberValue']
+ new DivElement()
+ ..classes = ['memberValue']
..children = [
new InstanceRefElement(_isolate, _instance.targetType, _instances,
- queue: _r.queue)
+ queue: _r.queue)
]
]);
}
if (_instance.bound != null) {
- members.add(new DivElement()..classes = ['memberItem']
+ members.add(new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'bound',
- new DivElement()..classes = ['memberValue']
+ new DivElement()
+ ..classes = ['memberValue']
..children = [
new InstanceRefElement(_isolate, _instance.bound, _instances,
- queue: _r.queue)
+ queue: _r.queue)
]
]);
}
if (_instance.closureFunction != null) {
- members.add(new DivElement()..classes = ['memberItem']
+ members.add(new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'closure function',
- new DivElement()..classes = ['memberValue']
+ new DivElement()
+ ..classes = ['memberValue']
..children = [
new FunctionRefElement(_isolate, _instance.closureFunction,
- queue: _r.queue)
+ queue: _r.queue)
]
]);
}
if (_instance.closureContext != null) {
- members.add(new DivElement()..classes = ['memberItem']
+ members.add(new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'closure context',
- new DivElement()..classes = ['memberValue']
+ new DivElement()
+ ..classes = ['memberValue']
..children = [
new ContextRefElement(_isolate, _instance.closureContext,
- queue: _r.queue)
+ queue: _r.queue)
]
]);
}
if (_instance.kind == M.InstanceKind.closure) {
ButtonElement btn;
- members.add(new DivElement()..classes = ['memberItem']
+ members.add(new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'closure breakpoint',
- new DivElement()..classes = ['memberValue']
+ new DivElement()
+ ..classes = ['memberValue']
..children = [
btn = new ButtonElement()
..text = _instance.activationBreakpoint == null
- ? 'break on activation'
- : 'remove'
+ ? 'break on activation'
+ : 'remove'
..onClick.listen((_) {
btn.disabled = true;
_toggleBreakpoint();
@@ -349,25 +377,33 @@
if (_instance.nativeFields != null && _instance.nativeFields.isNotEmpty) {
int i = 0;
- members.add(new DivElement()..classes = ['memberItem']
+ members.add(new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'native fields (${_instance.nativeFields.length})',
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..children = [
new CurlyBlockElement(
expanded: _instance.nativeFields.length <= 100,
queue: _r.queue)
..content = [
- new DivElement()..classes = ['memberList']
- ..children = _instance.nativeFields.map((f) =>
- new DivElement()..classes = ['memberItem']
- ..children = [
- new DivElement()..classes = ['memberName']
- ..text = '[ ${i++} ]',
- new DivElement()..classes = ['memberValue']
- ..text = '[ ${f.value} ]'
- ]).toList()
+ new DivElement()
+ ..classes = ['memberList']
+ ..children = _instance.nativeFields
+ .map((f) => new DivElement()
+ ..classes = ['memberItem']
+ ..children = [
+ new DivElement()
+ ..classes = ['memberName']
+ ..text = '[ ${i++} ]',
+ new DivElement()
+ ..classes = ['memberValue']
+ ..text = '[ ${f.value} ]'
+ ])
+ .toList()
]
]
]);
@@ -375,32 +411,40 @@
if (_instance.fields != null && _instance.fields.isNotEmpty) {
final fields = _instance.fields.toList();
- members.add(new DivElement()..classes = ['memberItem']
+ members.add(new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'fields (${fields.length})',
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..children = [
new CurlyBlockElement(
- expanded: fields.length <= 100,
- queue: _r.queue)
+ expanded: fields.length <= 100, queue: _r.queue)
..content = [
- new DivElement()..classes = ['memberList']
- ..children = fields.map((f) =>
- new DivElement()..classes = ['memberItem']
- ..children = [
- new DivElement()..classes = ['memberName']
- ..children = [
- new FieldRefElement(_isolate, f.decl, _instances,
- queue: _r.queue)
- ],
- new DivElement()..classes = ['memberValue']
- ..children = [
- new SpanElement()..text = ' = ',
- anyRef(_isolate, f.value, _instances,
- queue: _r.queue)
- ]
- ]).toList()
+ new DivElement()
+ ..classes = ['memberList']
+ ..children = fields
+ .map((f) => new DivElement()
+ ..classes = ['memberItem']
+ ..children = [
+ new DivElement()
+ ..classes = ['memberName']
+ ..children = [
+ new FieldRefElement(
+ _isolate, f.decl, _instances,
+ queue: _r.queue)
+ ],
+ new DivElement()
+ ..classes = ['memberValue']
+ ..children = [
+ new SpanElement()..text = ' = ',
+ anyRef(_isolate, f.value, _instances,
+ queue: _r.queue)
+ ]
+ ])
+ .toList()
]
]
]);
@@ -409,37 +453,47 @@
if (_instance.elements != null && _instance.elements.isNotEmpty) {
final elements = _instance.elements.toList();
int i = 0;
- members.add(new DivElement()..classes = ['memberItem']
+ members.add(new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'elements (${_instance.length})',
- new DivElement()..classes = ['memberValue']
+ new DivElement()
+ ..classes = ['memberValue']
..children = [
new CurlyBlockElement(
- expanded: elements.length <= 100,
- queue: _r.queue)
- ..children = [
- new DivElement()..classes = ['memberList']
- ..children = elements.map((e) =>
- new DivElement()..classes = ['memberItem']
- ..children = [
- new DivElement()..classes = ['memberName']
- ..text = '[ ${i++} ]',
- new DivElement()..classes = ['memberValue']
- ..children = [
- anyRef(_isolate, e, _instances,
- queue: _r.queue)
- ]
- ]).toList()
+ expanded: elements.length <= 100, queue: _r.queue)
+ ..content = [
+ new DivElement()
+ ..classes = ['memberList']
+ ..children = elements
+ .map((element) => new DivElement()
+ ..classes = ['memberItem']
+ ..children = [
+ new DivElement()
+ ..classes = ['memberName']
+ ..text = '[ ${i++} ]',
+ new DivElement()
+ ..classes = ['memberValue']
+ ..children = [
+ anyRef(_isolate, element, _instances,
+ queue: _r.queue)
+ ]
+ ])
+ .toList()
]
]
]);
if (_instance.length != elements.length) {
- members.add(new DivElement()..classes = ['memberItem']
+ members.add(new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = '...',
- new DivElement()..classes = ['memberValue']
+ new DivElement()
+ ..classes = ['memberValue']
..text = '${_instance.length - elements.length} omitted elements'
]);
}
@@ -447,44 +501,54 @@
if (_instance.associations != null && _instance.associations.isNotEmpty) {
final associations = _instance.associations.toList();
- members.add(new DivElement()..classes = ['memberItem']
+ members.add(new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'associations (${_instance.length})',
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..children = [
new CurlyBlockElement(
- expanded: associations.length <= 100,
- queue: _r.queue)
+ expanded: associations.length <= 100, queue: _r.queue)
..content = [
- new DivElement()..classes = ['memberList']
- ..children = associations.map((a) =>
- new DivElement()..classes = ['memberItem']
- ..children = [
- new DivElement()..classes = ['memberName']
- ..children = [
- new SpanElement()..text = '[ ',
- anyRef(_isolate, a.key, _instances,
- queue: _r.queue),
- new SpanElement()..text = ' ]',
- ],
- new DivElement()..classes = ['memberValue']
- ..children = [
- anyRef(_isolate, a.value, _instances,
- queue: _r.queue)
- ]
- ]).toList()
+ new DivElement()
+ ..classes = ['memberList']
+ ..children = associations
+ .map((a) => new DivElement()
+ ..classes = ['memberItem']
+ ..children = [
+ new DivElement()
+ ..classes = ['memberName']
+ ..children = [
+ new SpanElement()..text = '[ ',
+ anyRef(_isolate, a.key, _instances,
+ queue: _r.queue),
+ new SpanElement()..text = ' ]',
+ ],
+ new DivElement()
+ ..classes = ['memberValue']
+ ..children = [
+ anyRef(_isolate, a.value, _instances,
+ queue: _r.queue)
+ ]
+ ])
+ .toList()
]
]
]);
if (_instance.length != associations.length) {
- members.add(new DivElement()..classes = ['memberItem']
+ members.add(new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = '...',
- new DivElement()..classes = ['memberValue']
+ new DivElement()
+ ..classes = ['memberValue']
..text = '${_instance.length - associations.length} '
- 'omitted elements'
+ 'omitted elements'
]);
}
}
@@ -492,162 +556,210 @@
if (_instance.typedElements != null && _instance.typedElements.isNotEmpty) {
final typedElements = _instance.typedElements.toList();
int i = 0;
- members.add(new DivElement()..classes = ['memberItem']
+ members.add(new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'elements (${_instance.length})',
- new DivElement()..classes = ['memberValue']
+ new DivElement()
+ ..classes = ['memberValue']
..children = [
new CurlyBlockElement(
- expanded: typedElements.length <= 100,
- queue: _r.queue)
+ expanded: typedElements.length <= 100, queue: _r.queue)
..content = [
- new DivElement()..classes = ['memberList']
- ..children = typedElements.map((e) =>
- new DivElement()..classes = ['memberItem']
- ..children = [
- new DivElement()..classes = ['memberName']
- ..text = '[ ${i++} ]',
- new DivElement()..classes = ['memberValue']
- ..text = '$e'
- ]).toList()
+ new DivElement()
+ ..classes = ['memberList']
+ ..children = typedElements
+ .map((e) => new DivElement()
+ ..classes = ['memberItem']
+ ..children = [
+ new DivElement()
+ ..classes = ['memberName']
+ ..text = '[ ${i++} ]',
+ new DivElement()
+ ..classes = ['memberValue']
+ ..text = '$e'
+ ])
+ .toList()
]
]
]);
if (_instance.length != typedElements.length) {
- members.add(new DivElement()..classes = ['memberItem']
+ members.add(new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = '...',
- new DivElement()..classes = ['memberValue']
+ new DivElement()
+ ..classes = ['memberValue']
..text = '${_instance.length - typedElements.length} '
- 'omitted elements'
+ 'omitted elements'
]);
}
}
if (_instance.kind == M.InstanceKind.regExp) {
members.addAll([
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'pattern',
- new DivElement()..classes = ['memberValue']
+ new DivElement()
+ ..classes = ['memberValue']
..children = [
anyRef(_isolate, _instance.pattern, _instances, queue: _r.queue)
]
],
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'isCaseSensitive',
- new DivElement()..classes = ['memberValue']
+ new DivElement()
+ ..classes = ['memberValue']
..text = _instance.isCaseSensitive ? 'yes' : 'no'
],
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'isMultiLine',
- new DivElement()..classes = ['memberValue']
+ new DivElement()
+ ..classes = ['memberValue']
..text = _instance.isMultiLine ? 'yes' : 'no'
],
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'oneByteFunction',
- new DivElement()..classes = ['memberValue']
+ new DivElement()
+ ..classes = ['memberValue']
..children = [
new FunctionRefElement(_isolate, _instance.oneByteFunction,
- queue: _r.queue)
+ queue: _r.queue)
]
],
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'twoByteFunction',
- new DivElement()..classes = ['memberValue']
+ new DivElement()
+ ..classes = ['memberValue']
..children = [
new FunctionRefElement(_isolate, _instance.twoByteFunction,
- queue: _r.queue)
+ queue: _r.queue)
]
],
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'externalOneByteFunction',
- new DivElement()..classes = ['memberValue']
+ new DivElement()
+ ..classes = ['memberValue']
..children = [
- new FunctionRefElement(_isolate,
- _instance.externalOneByteFunction,
- queue: _r.queue)
+ new FunctionRefElement(
+ _isolate, _instance.externalOneByteFunction,
+ queue: _r.queue)
]
],
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'externalTwoByteFunction',
- new DivElement()..classes = ['memberValue']
+ new DivElement()
+ ..classes = ['memberValue']
..children = [
- new FunctionRefElement(_isolate,
- _instance.externalTwoByteFunction,
- queue: _r.queue)
+ new FunctionRefElement(
+ _isolate, _instance.externalTwoByteFunction,
+ queue: _r.queue)
]
],
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'oneByteBytecode',
- new DivElement()..classes = ['memberValue']
+ new DivElement()
+ ..classes = ['memberValue']
..children = [
- new InstanceRefElement(_isolate, _instance.oneByteBytecode,
- _instances, queue: _r.queue)
+ new InstanceRefElement(
+ _isolate, _instance.oneByteBytecode, _instances,
+ queue: _r.queue)
]
],
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'twoByteBytecode',
- new DivElement()..classes = ['memberValue']
+ new DivElement()
+ ..classes = ['memberValue']
..children = [
- new InstanceRefElement(_isolate, _instance.twoByteBytecode,
- _instances, queue: _r.queue)
+ new InstanceRefElement(
+ _isolate, _instance.twoByteBytecode, _instances,
+ queue: _r.queue)
]
]
]);
}
if (_instance.kind == M.InstanceKind.mirrorReference) {
- members.add(new DivElement()..classes = ['memberItem']
+ members.add(new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'referent',
- new DivElement()..classes = ['memberValue']
+ new DivElement()
+ ..classes = ['memberValue']
..children = [
new ContextRefElement(_isolate, _instance.referent,
- queue: _r.queue)
+ queue: _r.queue)
]
]);
}
if (_instance.kind == M.InstanceKind.weakProperty) {
members.addAll([
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'key',
- new DivElement()..classes = ['memberValue']
+ new DivElement()
+ ..classes = ['memberValue']
..children = [
new InstanceRefElement(_isolate, _instance.key, _instances,
- queue: _r.queue),
+ queue: _r.queue),
]
],
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'value',
- new DivElement()..classes = ['memberValue']
+ new DivElement()
+ ..classes = ['memberValue']
..children = [
new InstanceRefElement(_isolate, _instance.value, _instances,
- queue: _r.queue),
+ queue: _r.queue),
]
]
]);
@@ -664,17 +776,17 @@
Future _loadExtraData() async {
_library = (await _classes.get(_isolate, _instance.clazz.id)).library;
if (_instance.typeArguments != null) {
- _typeArguments = await _arguments.get(_isolate,
- _instance.typeArguments.id);
+ _typeArguments =
+ await _arguments.get(_isolate, _instance.typeArguments.id);
} else {
_typeArguments = null;
}
if (_instance.closureFunction != null) {
- _location = (await _functions.get(_isolate,
- _instance.closureFunction.id)).location;
+ _location = (await _functions.get(_isolate, _instance.closureFunction.id))
+ .location;
} else if (_instance.typeClass != null) {
- _location = (await _classes.get(_isolate,
- _instance.typeClass.id)).location;
+ _location =
+ (await _classes.get(_isolate, _instance.typeClass.id)).location;
}
_r.dirty();
}
diff --git a/runtime/observatory/lib/src/elements/isolate/counter_chart.dart b/runtime/observatory/lib/src/elements/isolate/counter_chart.dart
index fc782a4..b3917ec 100644
--- a/runtime/observatory/lib/src/elements/isolate/counter_chart.dart
+++ b/runtime/observatory/lib/src/elements/isolate/counter_chart.dart
@@ -11,7 +11,7 @@
class IsolateCounterChartElement extends HtmlElement implements Renderable {
static const tag =
- const Tag<IsolateCounterChartElement>('isolate-counter-chart');
+ const Tag<IsolateCounterChartElement>('isolate-counter-chart');
RenderingScheduler<IsolateCounterChartElement> _r;
@@ -52,23 +52,26 @@
];
void render() {
- final _series = [new ChartSeries("Work", const [1], new PieChartRenderer(
- sortDataByValue: false
- ))];
+ final _series = [
+ new ChartSeries(
+ "Work", const [1], new PieChartRenderer(sortDataByValue: false))
+ ];
final areaHost = new DivElement()..classes = ['host'];
- final legendHost = new DivElement()..classes = ['legend'];
+ final legendHost = new DivElement()..classes = ['legend'];
children = [areaHost, legendHost];
final rect = areaHost.getBoundingClientRect();
final minSize = new Rect.size(rect.width, rect.height);
final config = new ChartConfig(_series, const [0])
- ..minimumSize = minSize
- ..legend = new ChartLegend(legendHost, showValues: true);
- final data = new ChartData(_columns, _counters.keys
- .map((key) => [key, double.parse(_counters[key].split('%')[0])])
- .toList());
+ ..minimumSize = minSize
+ ..legend = new ChartLegend(legendHost, showValues: true);
+ final data = new ChartData(
+ _columns,
+ _counters.keys
+ .map((key) => [key, double.parse(_counters[key].split('%')[0])])
+ .toList());
- new LayoutArea(areaHost, data, config, state: new ChartState(),
- autoUpdate: false)
+ new LayoutArea(areaHost, data, config,
+ state: new ChartState(), autoUpdate: false)
..addChartBehavior(new Hovercard())
..addChartBehavior(new AxisLabelTooltip())
..draw();
diff --git a/runtime/observatory/lib/src/elements/isolate/location.dart b/runtime/observatory/lib/src/elements/isolate/location.dart
index fffadf6..6f565ce 100644
--- a/runtime/observatory/lib/src/elements/isolate/location.dart
+++ b/runtime/observatory/lib/src/elements/isolate/location.dart
@@ -12,15 +12,11 @@
class IsolateLocationElement extends HtmlElement implements Renderable {
static const tag = const Tag<IsolateLocationElement>('isolate-location',
- dependencies: const [
- FunctionRefElement.tag,
- SourceLinkElement.tag
- ]);
+ dependencies: const [FunctionRefElement.tag, SourceLinkElement.tag]);
RenderingScheduler<IsolateLocationElement> _r;
- Stream<RenderedEvent<IsolateLocationElement>> get onRendered =>
- _r.onRendered;
+ Stream<RenderedEvent<IsolateLocationElement>> get onRendered => _r.onRendered;
M.Isolate _isolate;
M.EventRepository _events;
@@ -28,10 +24,9 @@
StreamSubscription _debugSubscription;
StreamSubscription _isolateSubscription;
- factory IsolateLocationElement(M.Isolate isolate,
- M.EventRepository events,
- M.ScriptRepository scripts,
- {RenderingQueue queue}) {
+ factory IsolateLocationElement(
+ M.Isolate isolate, M.EventRepository events, M.ScriptRepository scripts,
+ {RenderingQueue queue}) {
assert(isolate != null);
assert(events != null);
assert(scripts != null);
@@ -70,14 +65,13 @@
case M.IsolateStatus.running:
children = [
new SpanElement()..text = 'at ',
- new FunctionRefElement(_isolate,
- M.topFrame(_isolate.pauseEvent).function,
- queue: _r.queue),
+ new FunctionRefElement(
+ _isolate, M.topFrame(_isolate.pauseEvent).function,
+ queue: _r.queue),
new SpanElement()..text = ' (',
- new SourceLinkElement(_isolate,
- M.topFrame(_isolate.pauseEvent).location,
- _scripts,
- queue: _r.queue),
+ new SourceLinkElement(
+ _isolate, M.topFrame(_isolate.pauseEvent).location, _scripts,
+ queue: _r.queue),
new SpanElement()..text = ') '
];
break;
@@ -98,14 +92,13 @@
if (M.topFrame(_isolate.pauseEvent) != null) {
content.addAll([
new SpanElement()..text = ' at ',
- new FunctionRefElement(_isolate,
- M.topFrame(_isolate.pauseEvent).function,
- queue: _r.queue),
+ new FunctionRefElement(
+ _isolate, M.topFrame(_isolate.pauseEvent).function,
+ queue: _r.queue),
new SpanElement()..text = ' (',
- new SourceLinkElement(_isolate,
- M.topFrame(_isolate.pauseEvent).location,
- _scripts,
- queue: _r.queue),
+ new SourceLinkElement(
+ _isolate, M.topFrame(_isolate.pauseEvent).location, _scripts,
+ queue: _r.queue),
new SpanElement()..text = ') '
]);
}
diff --git a/runtime/observatory/lib/src/elements/isolate/run_state.dart b/runtime/observatory/lib/src/elements/isolate/run_state.dart
index 547bdc2..0919cee 100644
--- a/runtime/observatory/lib/src/elements/isolate/run_state.dart
+++ b/runtime/observatory/lib/src/elements/isolate/run_state.dart
@@ -13,17 +13,15 @@
RenderingScheduler<IsolateRunStateElement> _r;
- Stream<RenderedEvent<IsolateRunStateElement>> get onRendered =>
- _r.onRendered;
+ Stream<RenderedEvent<IsolateRunStateElement>> get onRendered => _r.onRendered;
M.Isolate _isolate;
M.EventRepository _events;
StreamSubscription _debugSubscription;
StreamSubscription _isolateSubscription;
- factory IsolateRunStateElement(M.Isolate isolate,
- M.EventRepository events,
- {RenderingQueue queue}) {
+ factory IsolateRunStateElement(M.Isolate isolate, M.EventRepository events,
+ {RenderingQueue queue}) {
assert(isolate != null);
assert(events != null);
IsolateRunStateElement e = document.createElement(tag.name);
diff --git a/runtime/observatory/lib/src/elements/isolate/shared_summary.dart b/runtime/observatory/lib/src/elements/isolate/shared_summary.dart
index 6bba9ed..4ee3e39 100644
--- a/runtime/observatory/lib/src/elements/isolate/shared_summary.dart
+++ b/runtime/observatory/lib/src/elements/isolate/shared_summary.dart
@@ -12,11 +12,9 @@
import 'package:observatory/src/elements/isolate/counter_chart.dart';
class IsolateSharedSummaryElement extends HtmlElement implements Renderable {
- static const tag =
- const Tag<IsolateSharedSummaryElement>('isolate-shared-summary',
- dependencies: const [
- IsolateCounterChartElement.tag
- ]);
+ static const tag = const Tag<IsolateSharedSummaryElement>(
+ 'isolate-shared-summary',
+ dependencies: const [IsolateCounterChartElement.tag]);
RenderingScheduler<IsolateSharedSummaryElement> _r;
@@ -27,9 +25,9 @@
M.EventRepository _events;
StreamSubscription _isolateSubscription;
- factory IsolateSharedSummaryElement(M.Isolate isolate,
- M.EventRepository events,
- {RenderingQueue queue}) {
+ factory IsolateSharedSummaryElement(
+ M.Isolate isolate, M.EventRepository events,
+ {RenderingQueue queue}) {
assert(isolate != null);
assert(events != null);
IsolateSharedSummaryElement e = document.createElement(tag.name);
@@ -62,22 +60,30 @@
final oldHeapUsed = Utils.formatSize(_isolate.oldSpace.used);
final oldHeapCapacity = Utils.formatSize(_isolate.oldSpace.capacity);
final content = [
- new DivElement()..classes = ['menu']
+ new DivElement()
+ ..classes = ['menu']
..children = [
- new DivElement()..classes = ['memberList']
+ new DivElement()
+ ..classes = ['memberList']
..children = [
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'new heap',
- new DivElement()..classes = ['memberValue']
+ new DivElement()
+ ..classes = ['memberValue']
..text = '$newHeapUsed of $newHeapCapacity',
],
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'old heap',
- new DivElement()..classes = ['memberValue']
+ new DivElement()
+ ..classes = ['memberValue']
..text = '$oldHeapUsed of $oldHeapCapacity',
]
],
@@ -85,8 +91,7 @@
new DivElement()
..children = [
new SpanElement()..text = 'see ',
- new AnchorElement(href: Uris.debugger(_isolate))
- ..text = 'debug'
+ new AnchorElement(href: Uris.debugger(_isolate))..text = 'debug'
],
new DivElement()
..children = [
@@ -115,14 +120,12 @@
new DivElement()
..children = [
new SpanElement()..text = 'see ',
- new AnchorElement(href: Uris.heapMap(_isolate))
- ..text = 'heap map'
+ new AnchorElement(href: Uris.heapMap(_isolate))..text = 'heap map'
],
new DivElement()
..children = [
new SpanElement()..text = 'see ',
- new AnchorElement(href: Uris.metrics(_isolate))
- ..text = 'metrics'
+ new AnchorElement(href: Uris.metrics(_isolate))..text = 'metrics'
],
new DivElement()
..children = [
@@ -139,28 +142,29 @@
new DivElement()
..children = [
new SpanElement()..text = 'see ',
- new AnchorElement(href: Uris.ports(_isolate))
- ..text = 'ports'
+ new AnchorElement(href: Uris.ports(_isolate))..text = 'ports'
],
new DivElement()
..children = [
new SpanElement()..text = 'see ',
- new AnchorElement(href: Uris.logging(_isolate))
- ..text = 'logging'
+ new AnchorElement(href: Uris.logging(_isolate))..text = 'logging'
]
- ],
+ ],
new IsolateCounterChartElement(_isolate.counters, queue: _r.queue)
];
if (_isolate.error != null) {
children = [
- new PreElement()..classes = ['errorBox']
+ new PreElement()
+ ..classes = ['errorBox']
..text = _isolate.error.message,
- new DivElement()..classes = ['summary']
+ new DivElement()
+ ..classes = ['summary']
..children = content
];
} else {
children = [
- new DivElement()..classes = ['summary']
+ new DivElement()
+ ..classes = ['summary']
..children = content
];
}
diff --git a/runtime/observatory/lib/src/elements/isolate/summary.dart b/runtime/observatory/lib/src/elements/isolate/summary.dart
index 1130b03..82d768a 100644
--- a/runtime/observatory/lib/src/elements/isolate/summary.dart
+++ b/runtime/observatory/lib/src/elements/isolate/summary.dart
@@ -14,18 +14,17 @@
import 'package:observatory/src/elements/isolate/shared_summary.dart';
class IsolateSummaryElement extends HtmlElement implements Renderable {
- static const tag = const Tag<IsolateSummaryElement>('isolate-summary',
- dependencies: const [
- IsolateRefElement.tag,
- IsolateLocationElement.tag,
- IsolateRunStateElement.tag,
- IsolateSharedSummaryElement.tag
- ]);
+ static const tag =
+ const Tag<IsolateSummaryElement>('isolate-summary', dependencies: const [
+ IsolateRefElement.tag,
+ IsolateLocationElement.tag,
+ IsolateRunStateElement.tag,
+ IsolateSharedSummaryElement.tag
+ ]);
RenderingScheduler<IsolateSummaryElement> _r;
- Stream<RenderedEvent<IsolateSummaryElement>> get onRendered =>
- _r.onRendered;
+ Stream<RenderedEvent<IsolateSummaryElement>> get onRendered => _r.onRendered;
M.IsolateRef _isolate;
M.EventRepository _events;
@@ -33,11 +32,12 @@
M.ScriptRepository _scripts;
M.Isolate _loadedIsolate;
- factory IsolateSummaryElement(M.IsolateRef isolate,
- M.IsolateRepository isolates,
- M.EventRepository events,
- M.ScriptRepository scripts,
- {RenderingQueue queue}) {
+ factory IsolateSummaryElement(
+ M.IsolateRef isolate,
+ M.IsolateRepository isolates,
+ M.EventRepository events,
+ M.ScriptRepository scripts,
+ {RenderingQueue queue}) {
assert(isolate != null);
assert(isolates != null);
assert(events != null);
@@ -75,7 +75,8 @@
];
} else {
children = [
- new DivElement()..classes = ['flex-row']
+ new DivElement()
+ ..classes = ['flex-row']
..children = [
new DivElement()
..children = [
@@ -86,7 +87,7 @@
..children = [
new IsolateRunStateElement(_isolate, _events, queue: _r.queue),
new IsolateLocationElement(_isolate, _events, _scripts,
- queue: _r.queue),
+ queue: _r.queue),
new SpanElement()..text = ' [',
new AnchorElement(href: Uris.debugger(_isolate))
..text = 'debug',
diff --git a/runtime/observatory/lib/src/elements/isolate_reconnect.dart b/runtime/observatory/lib/src/elements/isolate_reconnect.dart
index df3e77a..423009f 100644
--- a/runtime/observatory/lib/src/elements/isolate_reconnect.dart
+++ b/runtime/observatory/lib/src/elements/isolate_reconnect.dart
@@ -15,11 +15,13 @@
import 'package:observatory/src/elements/nav/top_menu.dart';
import 'package:observatory/src/elements/view_footer.dart';
-class IsolateReconnectElement extends HtmlElement implements Renderable{
+class IsolateReconnectElement extends HtmlElement implements Renderable {
static const tag = const Tag<IsolateReconnectElement>('isolate-reconnect',
- dependencies: const [NavTopMenuElement.tag,
- NavNotifyElement.tag,
- ViewFooterElement.tag]);
+ dependencies: const [
+ NavTopMenuElement.tag,
+ NavNotifyElement.tag,
+ ViewFooterElement.tag
+ ]);
RenderingScheduler _r;
@@ -32,7 +34,7 @@
M.EventRepository _events;
StreamSubscription _subscription;
- M.VM get vm => _vm;
+ M.VM get vm => _vm;
String get missing => _missing;
Uri get uri => _uri;
@@ -85,26 +87,29 @@
..classes = ['content-centered']
..children = [
new HeadingElement.h1()..text = 'Isolate $_missing no longer exists',
- new BRElement(), new HRElement(),
- new DivElement()..classes = ['memberList']
+ new BRElement(),
+ new HRElement(),
+ new DivElement()
+ ..classes = ['memberList']
..children = (_vm.isolates.map((isolate) {
final query = new Map.from(_uri.queryParameters);
query['isolateId'] = isolate.id;
final href = new Uri(path: _uri.path, queryParameters: query);
- return new DivElement()..classes = ['memberItem', 'doubleSpaced']
+ return new DivElement()
+ ..classes = ['memberItem', 'doubleSpaced']
..children = [
new SpanElement()..text = 'Continue in ',
- new AnchorElement(href: '#$href')..classes = ['isolate-link']
+ new AnchorElement(href: '#$href')
+ ..classes = ['isolate-link']
..text = '${isolate.id} (${isolate.name})'
];
- }).toList()..add(
- new DivElement()..classes = ['memberItem', 'doubleSpaced']
+ }).toList()
+ ..add(new DivElement()
+ ..classes = ['memberItem', 'doubleSpaced']
..children = [
new SpanElement()..text = 'Go to ',
- new AnchorElement(href: Uris.vm())
- ..text = 'isolates summary',
- ]
- ))
+ new AnchorElement(href: Uris.vm())..text = 'isolates summary',
+ ]))
],
new ViewFooterElement(queue: _r.queue)
];
diff --git a/runtime/observatory/lib/src/elements/isolate_ref.dart b/runtime/observatory/lib/src/elements/isolate_ref.dart
index 2bee70b..3b32c18 100644
--- a/runtime/observatory/lib/src/elements/isolate_ref.dart
+++ b/runtime/observatory/lib/src/elements/isolate_ref.dart
@@ -6,8 +6,7 @@
import 'dart:html';
import 'dart:async';
-import 'package:observatory/models.dart' as M
- show IsolateRef, EventRepository;
+import 'package:observatory/models.dart' as M show IsolateRef, EventRepository;
import 'package:observatory/src/elements/helpers/rendering_scheduler.dart';
import 'package:observatory/src/elements/helpers/tag.dart';
import 'package:observatory/src/elements/helpers/uris.dart';
@@ -19,7 +18,6 @@
Stream<RenderedEvent<IsolateRefElement>> get onRendered => _r.onRendered;
-
M.IsolateRef _isolate;
M.EventRepository _events;
StreamSubscription _updatesSubscription;
@@ -43,8 +41,11 @@
void attached() {
super.attached();
_updatesSubscription = _events.onIsolateUpdate
- .where((e) => e.isolate.id == isolate.id)
- .listen((e) { _isolate = e.isolate; _r.dirty(); });
+ .where((e) => e.isolate.id == isolate.id)
+ .listen((e) {
+ _isolate = e.isolate;
+ _r.dirty();
+ });
_r.enable();
}
diff --git a/runtime/observatory/lib/src/elements/isolate_view.dart b/runtime/observatory/lib/src/elements/isolate_view.dart
index 55d9332..e3c7dac 100644
--- a/runtime/observatory/lib/src/elements/isolate_view.dart
+++ b/runtime/observatory/lib/src/elements/isolate_view.dart
@@ -29,24 +29,24 @@
import 'package:observatory/src/elements/view_footer.dart';
class IsolateViewElement extends HtmlElement implements Renderable {
- static const tag = const Tag<IsolateViewElement>('isolate-view',
- dependencies: const [
- CurlyBlockElement.tag,
- EvalBoxElement.tag,
- FunctionRefElement.tag,
- IsolateLocationElement.tag,
- IsolateRunStateElement.tag,
- IsolateSharedSummaryElement.tag,
- LibraryRefElement.tag,
- NavClassMenuElement.tag,
- NavTopMenuElement.tag,
- NavIsolateMenuElement.tag,
- NavRefreshElement.tag,
- NavNotifyElement.tag,
- ScriptInsetElement.tag,
- SourceInsetElement.tag,
- ViewFooterElement.tag
- ]);
+ static const tag =
+ const Tag<IsolateViewElement>('isolate-view', dependencies: const [
+ CurlyBlockElement.tag,
+ EvalBoxElement.tag,
+ FunctionRefElement.tag,
+ IsolateLocationElement.tag,
+ IsolateRunStateElement.tag,
+ IsolateSharedSummaryElement.tag,
+ LibraryRefElement.tag,
+ NavClassMenuElement.tag,
+ NavTopMenuElement.tag,
+ NavIsolateMenuElement.tag,
+ NavRefreshElement.tag,
+ NavNotifyElement.tag,
+ ScriptInsetElement.tag,
+ SourceInsetElement.tag,
+ ViewFooterElement.tag
+ ]);
RenderingScheduler<IsolateViewElement> _r;
@@ -70,16 +70,18 @@
M.Isolate get isolate => _isolate;
M.NotificationRepository get notifications => _notifications;
- factory IsolateViewElement(M.VM vm, M.Isolate isolate,
- M.EventRepository events,
- M.NotificationRepository notifications,
- M.IsolateRepository isolates,
- M.ScriptRepository scripts,
- M.FunctionRepository functions,
- M.LibraryRepository libraries,
- M.InstanceRepository instances,
- M.EvalRepository eval,
- {RenderingQueue queue}) {
+ factory IsolateViewElement(
+ M.VM vm,
+ M.Isolate isolate,
+ M.EventRepository events,
+ M.NotificationRepository notifications,
+ M.IsolateRepository isolates,
+ M.ScriptRepository scripts,
+ M.FunctionRepository functions,
+ M.LibraryRepository libraries,
+ M.InstanceRepository instances,
+ M.EvalRepository eval,
+ {RenderingQueue queue}) {
assert(vm != null);
assert(isolate != null);
assert(events != null);
@@ -135,35 +137,37 @@
navBar([
new NavTopMenuElement(queue: _r.queue),
new NavVMMenuElement(_vm, _events, queue: _r.queue),
- new NavIsolateMenuElement(_isolate, _events,
- queue: _r.queue),
+ new NavIsolateMenuElement(_isolate, _events, queue: _r.queue),
new NavRefreshElement(label: 'reload source', queue: _r.queue)
- ..onRefresh.listen((e) async {
- e.element.disabled = true;
- await _isolates.reloadSources(_isolate);
- _r.dirty();
- }),
+ ..onRefresh.listen((e) async {
+ e.element.disabled = true;
+ await _isolates.reloadSources(_isolate);
+ _r.dirty();
+ }),
new NavRefreshElement(queue: _r.queue)
- ..onRefresh.listen((e) async {
- e.element.disabled = true;
- _isolate = await _isolates.get(_isolate);
- await _loadExtraData();
- _r.dirty();
- }),
+ ..onRefresh.listen((e) async {
+ e.element.disabled = true;
+ _isolate = await _isolates.get(_isolate);
+ await _loadExtraData();
+ _r.dirty();
+ }),
new NavNotifyElement(_notifications, queue: _r.queue)
]),
- new DivElement()..classes = ['content-centered-big']
+ new DivElement()
+ ..classes = ['content-centered-big']
..children = [
new HeadingElement.h2()..text = 'Isolate ${_isolate.name}',
new BRElement(),
- new DivElement()..classes = ['flex-row']
+ new DivElement()
+ ..classes = ['flex-row']
..children = [
new DivElement()..style.flex = '1',
new DivElement()
..children = [
- new IsolateRunStateElement(_isolate, _events, queue: _r.queue),
+ new IsolateRunStateElement(_isolate, _events,
+ queue: _r.queue),
new IsolateLocationElement(_isolate, _events, _scripts,
- queue: _r.queue),
+ queue: _r.queue),
new SpanElement()..text = ' [',
new AnchorElement(href: Uris.debugger(_isolate))
..text = 'debug',
@@ -172,115 +176,145 @@
],
new DivElement()
..children = _function != null
- ? [new BRElement(),
- new SourceInsetElement(_isolate, _function.location,
- _scripts,
- _instances,
- _events,
- currentPos: M.topFrame(isolate.pauseEvent).location.tokenPos,
- queue: _r.queue)..classes = ['header_inset']]
- : const [],
+ ? [
+ new BRElement(),
+ new SourceInsetElement(_isolate, _function.location,
+ _scripts, _instances, _events,
+ currentPos:
+ M.topFrame(isolate.pauseEvent).location.tokenPos,
+ queue: _r.queue)..classes = ['header_inset']
+ ]
+ : const [],
new HRElement(),
new IsolateSharedSummaryElement(_isolate, _events, queue: _r.queue),
new HRElement(),
- new DivElement()..classes = ['memberList']
+ new DivElement()
+ ..classes = ['memberList']
..children = [
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'started at',
- new DivElement()..classes = ['memberValue']
+ new DivElement()
+ ..classes = ['memberValue']
..text = '${_isolate.startTime}'
],
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'uptime',
- new DivElement()..classes = ['memberValue']
+ new DivElement()
+ ..classes = ['memberValue']
..text = '$uptime'
],
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'root library',
- new DivElement()..classes = ['memberValue']
+ new DivElement()
+ ..classes = ['memberValue']
..children = [
_isolate.rootLibrary == null
- ? (new SpanElement()..text = 'loading...')
- : new LibraryRefElement(_isolate, _isolate.rootLibrary,
- queue: _r.queue)
+ ? (new SpanElement()..text = 'loading...')
+ : new LibraryRefElement(
+ _isolate, _isolate.rootLibrary,
+ queue: _r.queue)
]
],
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..children = _isolate.entry != null
- ? [
- new DivElement()..classes = ['memberName']
- ..text = 'entry',
- new DivElement()..classes = ['memberValue']
- ..children = [
- new FunctionRefElement(_isolate, _isolate.entry,
- queue: _r.queue)
- ]
- ]
- : const [],
- new DivElement()..classes = ['memberItem']
+ ? [
+ new DivElement()
+ ..classes = ['memberName']
+ ..text = 'entry',
+ new DivElement()
+ ..classes = ['memberValue']
+ ..children = [
+ new FunctionRefElement(_isolate, _isolate.entry,
+ queue: _r.queue)
+ ]
+ ]
+ : const [],
+ new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'isolate id',
- new DivElement()..classes = ['memberValue']
+ new DivElement()
+ ..classes = ['memberValue']
..text = '${_isolate.number}'
],
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'service protocol extensions',
- new DivElement()..classes = ['memberValue']
+ new DivElement()
+ ..classes = ['memberValue']
..text = '${_isolate.extensionRPCs}'
],
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'object store',
- new DivElement()..classes = ['memberValue']
+ new DivElement()
+ ..classes = ['memberValue']
..children = [
new AnchorElement(href: Uris.objectStore(_isolate))
..text = 'object store'
]
],
new BRElement(),
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'libraries (${libraries.length})',
- new DivElement()..classes = ['memberValue']
+ new DivElement()
+ ..classes = ['memberValue']
..children = [
new CurlyBlockElement(queue: _r.queue)
- ..content = libraries.map((l) =>
- new DivElement()
- ..children = [
- new LibraryRefElement(_isolate, l,
- queue: _r.queue)
- ]
- ).toList()
+ ..content = libraries
+ .map((l) => new DivElement()
+ ..children = [
+ new LibraryRefElement(_isolate, l,
+ queue: _r.queue)
+ ])
+ .toList()
]
]
],
new HRElement(),
new EvalBoxElement(_isolate, _isolate.rootLibrary, _instances, _eval,
- queue: _r.queue),
+ queue: _r.queue),
new DivElement()
..children = _rootScript != null
- ? [new HRElement(),
- new ScriptInsetElement(_isolate, _rootScript, _scripts,
- _instances, _events, queue: _r.queue)]
- : const [],
+ ? [
+ new HRElement(),
+ new ScriptInsetElement(
+ _isolate, _rootScript, _scripts, _instances, _events,
+ queue: _r.queue)
+ ]
+ : const [],
new HRElement(),
new ViewFooterElement(queue: _r.queue)
]
];
}
- Future _loadExtraData() async{
+ Future _loadExtraData() async {
_function = null;
_rootScript = null;
final frame = M.topFrame(_isolate.pauseEvent);
@@ -288,8 +322,8 @@
_function = await _functions.get(_isolate, frame.function.id);
}
if (_isolate.rootLibrary != null) {
- final rootLibrary = await _libraries.get(_isolate,
- _isolate.rootLibrary.id);
+ final rootLibrary =
+ await _libraries.get(_isolate, _isolate.rootLibrary.id);
_rootScript = rootLibrary.rootScript;
}
_r.dirty();
diff --git a/runtime/observatory/lib/src/elements/json_view.dart b/runtime/observatory/lib/src/elements/json_view.dart
index 8134064..5ce987b 100644
--- a/runtime/observatory/lib/src/elements/json_view.dart
+++ b/runtime/observatory/lib/src/elements/json_view.dart
@@ -16,11 +16,11 @@
class JSONViewElement extends HtmlElement implements Renderable {
static const tag = const Tag<JSONViewElement>('json-view',
- dependencies: const [
- NavTopMenuElement.tag,
- NavNotifyElement.tag,
- ViewFooterElement.tag
- ]);
+ dependencies: const [
+ NavTopMenuElement.tag,
+ NavNotifyElement.tag,
+ ViewFooterElement.tag
+ ]);
RenderingScheduler<JSONViewElement> _r;
@@ -29,13 +29,11 @@
M.NotificationRepository _notifications;
Map _map;
-
M.NotificationRepository get notifications => _notifications;
Map get map => _map;
- factory JSONViewElement(Map map,
- M.NotificationRepository notifications,
- {RenderingQueue queue}) {
+ factory JSONViewElement(Map map, M.NotificationRepository notifications,
+ {RenderingQueue queue}) {
assert(notifications != null);
assert(map != null);
JSONViewElement e = document.createElement(tag.name);
@@ -66,12 +64,12 @@
new NavTopMenuElement(queue: _r.queue),
new NavNotifyElement(_notifications, queue: _r.queue)
]),
- new DivElement()..classes = ['content-centered-big']
+ new DivElement()
+ ..classes = ['content-centered-big']
..children = [
new HeadingElement.h2()..text = 'Object',
new HRElement(),
- new PreElement()
- ..text = JSONPretty.stringify(_map),
+ new PreElement()..text = JSONPretty.stringify(_map),
new HRElement(),
new ViewFooterElement(queue: _r.queue)
]
@@ -79,7 +77,6 @@
}
}
-
class JSONPretty {
JSONPretty._();
@@ -149,7 +146,7 @@
}
void _writeIndent(int depth) {
- const tab = ' '; // 2 spaces.
+ const tab = ' '; // 2 spaces.
_buffer.write(tab * depth);
}
diff --git a/runtime/observatory/lib/src/elements/library_ref.dart b/runtime/observatory/lib/src/elements/library_ref.dart
index f749828..fbc396b 100644
--- a/runtime/observatory/lib/src/elements/library_ref.dart
+++ b/runtime/observatory/lib/src/elements/library_ref.dart
@@ -6,8 +6,7 @@
import 'dart:html';
import 'dart:async';
-import 'package:observatory/models.dart' as M
- show IsolateRef, LibraryRef;
+import 'package:observatory/models.dart' as M show IsolateRef, LibraryRef;
import 'package:observatory/src/elements/helpers/rendering_scheduler.dart';
import 'package:observatory/src/elements/helpers/tag.dart';
import 'package:observatory/src/elements/helpers/uris.dart';
diff --git a/runtime/observatory/lib/src/elements/library_view.dart b/runtime/observatory/lib/src/elements/library_view.dart
index 052e6f4..2265d1b 100644
--- a/runtime/observatory/lib/src/elements/library_view.dart
+++ b/runtime/observatory/lib/src/elements/library_view.dart
@@ -28,26 +28,26 @@
import 'package:observatory/src/elements/script_inset.dart';
import 'package:observatory/src/elements/view_footer.dart';
-class LibraryViewElement extends HtmlElement implements Renderable {
- static const tag = const Tag<LibraryViewElement>('library-view',
- dependencies: const [
- ClassRefElement.tag,
- CurlyBlockElement.tag,
- EvalBoxElement.tag,
- FieldRefElement.tag,
- FunctionRefElement.tag,
- LibraryRefElement.tag,
- NavTopMenuElement.tag,
- NavVMMenuElement.tag,
- NavIsolateMenuElement.tag,
- NavLibraryMenuElement.tag,
- NavRefreshElement.tag,
- NavNotifyElement.tag,
- ObjectCommonElement.tag,
- ScriptRefElement.tag,
- ScriptInsetElement.tag,
- ViewFooterElement.tag
- ]);
+class LibraryViewElement extends HtmlElement implements Renderable {
+ static const tag =
+ const Tag<LibraryViewElement>('library-view', dependencies: const [
+ ClassRefElement.tag,
+ CurlyBlockElement.tag,
+ EvalBoxElement.tag,
+ FieldRefElement.tag,
+ FunctionRefElement.tag,
+ LibraryRefElement.tag,
+ NavTopMenuElement.tag,
+ NavVMMenuElement.tag,
+ NavIsolateMenuElement.tag,
+ NavLibraryMenuElement.tag,
+ NavRefreshElement.tag,
+ NavNotifyElement.tag,
+ ObjectCommonElement.tag,
+ ScriptRefElement.tag,
+ ScriptInsetElement.tag,
+ ViewFooterElement.tag
+ ]);
RenderingScheduler<LibraryViewElement> _r;
@@ -69,25 +69,27 @@
M.EvalRepository _eval;
Iterable<M.Field> _variables;
-
M.VMRef get vm => _vm;
M.IsolateRef get isolate => _isolate;
M.NotificationRepository get notifications => _notifications;
M.Library get library => _library;
- factory LibraryViewElement(M.VM vm, M.IsolateRef isolate, M.Library library,
- M.EventRepository events,
- M.NotificationRepository notifications,
- M.LibraryRepository libraries,
- M.FieldRepository fields,
- M.RetainedSizeRepository retainedSizes,
- M.ReachableSizeRepository reachableSizes,
- M.InboundReferencesRepository references,
- M.RetainingPathRepository retainingPaths,
- M.ScriptRepository scripts,
- M.InstanceRepository instances,
- M.EvalRepository eval,
- {RenderingQueue queue}) {
+ factory LibraryViewElement(
+ M.VM vm,
+ M.IsolateRef isolate,
+ M.Library library,
+ M.EventRepository events,
+ M.NotificationRepository notifications,
+ M.LibraryRepository libraries,
+ M.FieldRepository fields,
+ M.RetainedSizeRepository retainedSizes,
+ M.ReachableSizeRepository reachableSizes,
+ M.InboundReferencesRepository references,
+ M.RetainingPathRepository retainingPaths,
+ M.ScriptRepository scripts,
+ M.InstanceRepository instances,
+ M.EvalRepository eval,
+ {RenderingQueue queue}) {
assert(vm != null);
assert(isolate != null);
assert(events != null);
@@ -145,39 +147,47 @@
new NavIsolateMenuElement(_isolate, _events, queue: _r.queue),
new NavLibraryMenuElement(_isolate, _library, queue: _r.queue),
new NavRefreshElement(queue: _r.queue)
- ..onRefresh.listen((e) async {
- e.element.disabled = true;
- _refresh();
- }),
+ ..onRefresh.listen((e) async {
+ e.element.disabled = true;
+ _refresh();
+ }),
new NavNotifyElement(_notifications, queue: _r.queue)
]),
- new DivElement()..classes = ['content-centered-big']
+ new DivElement()
+ ..classes = ['content-centered-big']
..children = [
new HeadingElement.h2()..text = 'ICData',
new HRElement(),
new ObjectCommonElement(_isolate, _library, _retainedSizes,
- _reachableSizes, _references, _retainingPaths,
- _instances, queue: _r.queue),
- new DivElement()..classes = ['memberList']
+ _reachableSizes, _references, _retainingPaths, _instances,
+ queue: _r.queue),
+ new DivElement()
+ ..classes = ['memberList']
..children = [
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'uri',
- new DivElement()..classes = ['memberValue']
+ new DivElement()
+ ..classes = ['memberValue']
..text = _library.uri
],
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'vm name',
- new DivElement()..classes = ['memberValue']
+ new DivElement()
+ ..classes = ['memberValue']
..text = _library.vmName
]
],
new HRElement(),
new EvalBoxElement(_isolate, _library, _instances, _eval,
- queue: _r.queue),
+ queue: _r.queue),
new HRElement(),
_createDependencies(),
new BRElement(),
@@ -189,8 +199,9 @@
new BRElement(),
_createFunctions(),
new HRElement(),
- new ScriptInsetElement(_isolate, _library.rootScript, _scripts,
- _instances, _events, queue: _r.queue),
+ new ScriptInsetElement(
+ _isolate, _library.rootScript, _scripts, _instances, _events,
+ queue: _r.queue),
new HRElement(),
new ViewFooterElement(queue: _r.queue)
]
@@ -201,8 +212,8 @@
_library = await _libraries.get(_isolate, _library.id);
_variables = null;
_r.dirty();
- _variables = await Future.wait(_library.variables.map((field) =>
- _fields.get(_isolate, field.id)));
+ _variables = await Future.wait(
+ _library.variables.map((field) => _fields.get(_isolate, field.id)));
_r.dirty();
}
@@ -215,15 +226,17 @@
..children = [
new SpanElement()..text = 'dependencies (${dependencies.length}) ',
new CurlyBlockElement(queue: _r.queue)
- ..content = dependencies.map((d) =>
- new DivElement()..classes = ['indent']
- ..children = [
- new SpanElement()..text = d.isImport ? 'import ' : 'export ',
- new LibraryRefElement(_isolate, d.target, queue: _r.queue),
- new SpanElement()..text = d.prefix == null ? ''
- : ' as ${d.prefix}',
- new SpanElement()..text = d.isDeferred ? ' deferred' : '',
- ]).toList()
+ ..content = dependencies
+ .map((d) => new DivElement()
+ ..classes = ['indent']
+ ..children = [
+ new SpanElement()..text = d.isImport ? 'import ' : 'export ',
+ new LibraryRefElement(_isolate, d.target, queue: _r.queue),
+ new SpanElement()
+ ..text = d.prefix == null ? '' : ' as ${d.prefix}',
+ new SpanElement()..text = d.isDeferred ? ' deferred' : '',
+ ])
+ .toList()
];
}
@@ -236,11 +249,13 @@
..children = [
new SpanElement()..text = 'scripts (${scripts.length}) ',
new CurlyBlockElement(queue: _r.queue)
- ..content = scripts.map((s) =>
- new DivElement()..classes = ['indent']
- ..children = [
- new ScriptRefElement(_isolate, s, queue: _r.queue)
- ]).toList()
+ ..content = scripts
+ .map((s) => new DivElement()
+ ..classes = ['indent']
+ ..children = [
+ new ScriptRefElement(_isolate, s, queue: _r.queue)
+ ])
+ .toList()
];
}
@@ -253,11 +268,13 @@
..children = [
new SpanElement()..text = 'classes (${classes.length}) ',
new CurlyBlockElement(queue: _r.queue)
- ..content = classes.map((c) =>
- new DivElement()..classes = ['indent']
- ..children = [
- new ClassRefElement(_isolate, c, queue: _r.queue)
- ]).toList()
+ ..content = classes
+ .map((c) => new DivElement()
+ ..classes = ['indent']
+ ..children = [
+ new ClassRefElement(_isolate, c, queue: _r.queue)
+ ])
+ .toList()
];
}
@@ -272,23 +289,28 @@
new CurlyBlockElement(queue: _r.queue)
..content = [
_variables == null
- ? (new SpanElement()..text = 'loading...')
- : (new DivElement()..classes = ['indent', 'memberList']
- ..children = _variables.map((f) =>
- new DivElement()..classes = ['memberItem']
- ..children = [
- new DivElement()..classes = ['memberName']
- ..children = [
- new FieldRefElement(_isolate, f, _instances,
- queue: _r.queue)
- ],
- new DivElement()..classes = ['memberValue']
- ..children = [
- new SpanElement()..text = ' = ',
- anyRef(_isolate, f.staticValue, _instances,
- queue: _r.queue)
- ]
- ]).toList())
+ ? (new SpanElement()..text = 'loading...')
+ : (new DivElement()
+ ..classes = ['indent', 'memberList']
+ ..children = _variables
+ .map((f) => new DivElement()
+ ..classes = ['memberItem']
+ ..children = [
+ new DivElement()
+ ..classes = ['memberName']
+ ..children = [
+ new FieldRefElement(_isolate, f, _instances,
+ queue: _r.queue)
+ ],
+ new DivElement()
+ ..classes = ['memberValue']
+ ..children = [
+ new SpanElement()..text = ' = ',
+ anyRef(_isolate, f.staticValue, _instances,
+ queue: _r.queue)
+ ]
+ ])
+ .toList())
]
];
}
@@ -302,11 +324,13 @@
..children = [
new SpanElement()..text = 'functions (${functions.length}) ',
new CurlyBlockElement(queue: _r.queue)
- ..content = functions.map((f) =>
- new DivElement()..classes = ['indent']
- ..children = [
- new FunctionRefElement(_isolate, f, queue: _r.queue)
- ]).toList()
+ ..content = functions
+ .map((f) => new DivElement()
+ ..classes = ['indent']
+ ..children = [
+ new FunctionRefElement(_isolate, f, queue: _r.queue)
+ ])
+ .toList()
];
}
}
diff --git a/runtime/observatory/lib/src/elements/local_var_descriptors_ref.dart b/runtime/observatory/lib/src/elements/local_var_descriptors_ref.dart
index 4ca623d..ce3981c 100644
--- a/runtime/observatory/lib/src/elements/local_var_descriptors_ref.dart
+++ b/runtime/observatory/lib/src/elements/local_var_descriptors_ref.dart
@@ -5,7 +5,7 @@
import 'dart:html';
import 'dart:async';
import 'package:observatory/models.dart' as M
- show IsolateRef, LocalVarDescriptorsRef;
+ show IsolateRef, LocalVarDescriptorsRef;
import 'package:observatory/src/elements/helpers/rendering_scheduler.dart';
import 'package:observatory/src/elements/helpers/tag.dart';
import 'package:observatory/src/elements/helpers/uris.dart';
@@ -24,8 +24,9 @@
M.IsolateRef get isolate => _isolate;
M.LocalVarDescriptorsRef get localVar => _localVar;
- factory LocalVarDescriptorsRefElement(M.IsolateRef isolate,
- M.LocalVarDescriptorsRef localVar, {RenderingQueue queue}) {
+ factory LocalVarDescriptorsRefElement(
+ M.IsolateRef isolate, M.LocalVarDescriptorsRef localVar,
+ {RenderingQueue queue}) {
assert(isolate != null);
assert(localVar != null);
LocalVarDescriptorsRefElement e = document.createElement(tag.name);
@@ -52,8 +53,8 @@
void render() {
final text = (_localVar.name == null || _localVar.name == '')
- ? 'LocalVarDescriptors'
- : _localVar.name;
+ ? 'LocalVarDescriptors'
+ : _localVar.name;
children = [
new AnchorElement(href: Uris.inspect(_isolate, object: _localVar))
..text = text
diff --git a/runtime/observatory/lib/src/elements/logging.dart b/runtime/observatory/lib/src/elements/logging.dart
index 67ac79d..5350a30 100644
--- a/runtime/observatory/lib/src/elements/logging.dart
+++ b/runtime/observatory/lib/src/elements/logging.dart
@@ -22,17 +22,17 @@
import 'package:observatory/src/elements/view_footer.dart';
class LoggingPageElement extends HtmlElement implements Renderable {
- static const tag = const Tag<LoggingPageElement>('logging-page',
- dependencies: const [
- LoggingListElement.tag,
- NavClassMenuElement.tag,
- NavTopMenuElement.tag,
- NavVMMenuElement.tag,
- NavIsolateMenuElement.tag,
- NavRefreshElement.tag,
- NavNotifyElement.tag,
- ViewFooterElement.tag
- ]);
+ static const tag =
+ const Tag<LoggingPageElement>('logging-page', dependencies: const [
+ LoggingListElement.tag,
+ NavClassMenuElement.tag,
+ NavTopMenuElement.tag,
+ NavVMMenuElement.tag,
+ NavIsolateMenuElement.tag,
+ NavRefreshElement.tag,
+ NavNotifyElement.tag,
+ ViewFooterElement.tag
+ ]);
RenderingScheduler<LoggingPageElement> _r;
@@ -44,15 +44,13 @@
M.NotificationRepository _notifications;
Level _level = Level.ALL;
-
M.VMRef get vm => _vm;
M.IsolateRef get isolate => _isolate;
M.NotificationRepository get notifications => _notifications;
factory LoggingPageElement(M.VM vm, M.IsolateRef isolate,
- M.EventRepository events,
- M.NotificationRepository notifications,
- {RenderingQueue queue}) {
+ M.EventRepository events, M.NotificationRepository notifications,
+ {RenderingQueue queue}) {
assert(vm != null);
assert(isolate != null);
assert(events != null);
@@ -93,18 +91,18 @@
new NavIsolateMenuElement(_isolate, _events, queue: _r.queue),
navMenu('logging'),
new NavRefreshElement(label: 'clear', queue: _r.queue)
- ..onRefresh.listen((e) async {
- e.element.disabled = true;
- _logs = null;
- _r.dirty();
- }),
+ ..onRefresh.listen((e) async {
+ e.element.disabled = true;
+ _logs = null;
+ _r.dirty();
+ }),
new NavNotifyElement(_notifications, queue: _r.queue)
]),
- new DivElement()..classes = ['content-centered-big']
+ new DivElement()
+ ..classes = ['content-centered-big']
..children = [
new HeadingElement.h2()..text = 'Logging',
- new SpanElement()
- ..text = 'Show messages with severity ',
+ new SpanElement()..text = 'Show messages with severity ',
_createLevelSelector(),
new HRElement(),
_logs
@@ -114,12 +112,11 @@
Element _createLevelSelector() {
var s = new SelectElement()
- ..value = _level.name
- ..children = Level.LEVELS.map((level) {
- return new OptionElement(value : level.name,
- selected: _level == level)
- ..text = level.name;
- }).toList(growable: false);
+ ..value = _level.name
+ ..children = Level.LEVELS.map((level) {
+ return new OptionElement(value: level.name, selected: _level == level)
+ ..text = level.name;
+ }).toList(growable: false);
s.onChange.listen((_) {
_level = Level.LEVELS[s.selectedIndex];
_r.dirty();
diff --git a/runtime/observatory/lib/src/elements/logging_list.dart b/runtime/observatory/lib/src/elements/logging_list.dart
index e803639..8b8b77d 100644
--- a/runtime/observatory/lib/src/elements/logging_list.dart
+++ b/runtime/observatory/lib/src/elements/logging_list.dart
@@ -28,9 +28,8 @@
set level(Level value) => _level = _r.checkAndReact(_level, value);
- factory LoggingListElement(M.IsolateRef isolate,
- M.EventRepository events,
- {RenderingQueue queue}) {
+ factory LoggingListElement(M.IsolateRef isolate, M.EventRepository events,
+ {RenderingQueue queue}) {
assert(isolate != null);
assert(events != null);
LoggingListElement e = document.createElement(tag.name);
@@ -65,17 +64,22 @@
}
void render() {
- children = _logs.where(_shouldBeVisible).map((logRecord) =>
- new DivElement()..classes = ['logItem', logRecord['level'].name]
- ..children = [
- new SpanElement()..classes = ['level']
- ..text = logRecord['level'].name,
- new SpanElement()..classes = ['time']
- ..text = Utils.formatDateTime(logRecord['time']),
- new SpanElement()..classes = ['message']
- ..text = logRecord["message"].valueAsString
- ]
- ).toList();
+ children = _logs
+ .where(_shouldBeVisible)
+ .map((logRecord) => new DivElement()
+ ..classes = ['logItem', logRecord['level'].name]
+ ..children = [
+ new SpanElement()
+ ..classes = ['level']
+ ..text = logRecord['level'].name,
+ new SpanElement()
+ ..classes = ['time']
+ ..text = Utils.formatDateTime(logRecord['time']),
+ new SpanElement()
+ ..classes = ['message']
+ ..text = logRecord["message"].valueAsString
+ ])
+ .toList();
}
bool _shouldBeVisible(Map record) => _level.compareTo(record['level']) <= 0;
diff --git a/runtime/observatory/lib/src/elements/megamorphiccache_ref.dart b/runtime/observatory/lib/src/elements/megamorphiccache_ref.dart
index e596727..36a4aa9 100644
--- a/runtime/observatory/lib/src/elements/megamorphiccache_ref.dart
+++ b/runtime/observatory/lib/src/elements/megamorphiccache_ref.dart
@@ -5,7 +5,7 @@
import 'dart:html';
import 'dart:async';
import 'package:observatory/models.dart' as M
- show IsolateRef, MegamorphicCacheRef;
+ show IsolateRef, MegamorphicCacheRef;
import 'package:observatory/src/elements/helpers/rendering_scheduler.dart';
import 'package:observatory/src/elements/helpers/tag.dart';
import 'package:observatory/src/elements/helpers/uris.dart';
@@ -25,8 +25,9 @@
M.IsolateRef get isolate => _isolate;
M.MegamorphicCacheRef get cache => _cache;
- factory MegamorphicCacheRefElement(M.IsolateRef isolate,
- M.MegamorphicCacheRef cache, {RenderingQueue queue}) {
+ factory MegamorphicCacheRefElement(
+ M.IsolateRef isolate, M.MegamorphicCacheRef cache,
+ {RenderingQueue queue}) {
assert(isolate != null);
assert(cache != null);
MegamorphicCacheRefElement e = document.createElement(tag.name);
@@ -55,7 +56,8 @@
children = [
new AnchorElement(href: Uris.inspect(_isolate, object: _cache))
..children = [
- new SpanElement()..classes = ['emphasize']
+ new SpanElement()
+ ..classes = ['emphasize']
..text = 'MegarmorphicCache',
new SpanElement()..text = ' (${_cache.selector})'
]
diff --git a/runtime/observatory/lib/src/elements/megamorphiccache_view.dart b/runtime/observatory/lib/src/elements/megamorphiccache_view.dart
index 541b472..0ab12b9 100644
--- a/runtime/observatory/lib/src/elements/megamorphiccache_view.dart
+++ b/runtime/observatory/lib/src/elements/megamorphiccache_view.dart
@@ -23,19 +23,19 @@
import 'package:observatory/src/elements/view_footer.dart';
class MegamorphicCacheViewElement extends HtmlElement implements Renderable {
- static const tag =
- const Tag<MegamorphicCacheViewElement>('megamorphiccache-view',
- dependencies: const [
- ContextRefElement.tag,
- CurlyBlockElement.tag,
- NavTopMenuElement.tag,
- NavVMMenuElement.tag,
- NavIsolateMenuElement.tag,
- NavRefreshElement.tag,
- NavNotifyElement.tag,
- ObjectCommonElement.tag,
- ViewFooterElement.tag
- ]);
+ static const tag = const Tag<MegamorphicCacheViewElement>(
+ 'megamorphiccache-view',
+ dependencies: const [
+ ContextRefElement.tag,
+ CurlyBlockElement.tag,
+ NavTopMenuElement.tag,
+ NavVMMenuElement.tag,
+ NavIsolateMenuElement.tag,
+ NavRefreshElement.tag,
+ NavNotifyElement.tag,
+ ObjectCommonElement.tag,
+ ViewFooterElement.tag
+ ]);
RenderingScheduler<MegamorphicCacheViewElement> _r;
@@ -54,23 +54,24 @@
M.RetainingPathRepository _retainingPaths;
M.InstanceRepository _instances;
-
M.VMRef get vm => _vm;
M.IsolateRef get isolate => _isolate;
M.NotificationRepository get notifications => _notifications;
M.MegamorphicCache get cache => _cache;
- factory MegamorphicCacheViewElement(M.VM vm, M.IsolateRef isolate,
- M.MegamorphicCache cache,
- M.EventRepository events,
- M.NotificationRepository notifications,
- M.MegamorphicCacheRepository caches,
- M.RetainedSizeRepository retainedSizes,
- M.ReachableSizeRepository reachableSizes,
- M.InboundReferencesRepository references,
- M.RetainingPathRepository retainingPaths,
- M.InstanceRepository instances,
- {RenderingQueue queue}) {
+ factory MegamorphicCacheViewElement(
+ M.VM vm,
+ M.IsolateRef isolate,
+ M.MegamorphicCache cache,
+ M.EventRepository events,
+ M.NotificationRepository notifications,
+ M.MegamorphicCacheRepository caches,
+ M.RetainedSizeRepository retainedSizes,
+ M.ReachableSizeRepository reachableSizes,
+ M.InboundReferencesRepository references,
+ M.RetainingPathRepository retainingPaths,
+ M.InstanceRepository instances,
+ {RenderingQueue queue}) {
assert(vm != null);
assert(isolate != null);
assert(events != null);
@@ -121,55 +122,69 @@
new NavIsolateMenuElement(_isolate, _events, queue: _r.queue),
navMenu('megamorphic inline cache'),
new NavRefreshElement(queue: _r.queue)
- ..onRefresh.listen((e) async {
- e.element.disabled = true;
- _cache = await _caches.get(_isolate, _cache.id);
- _r.dirty();
- }),
+ ..onRefresh.listen((e) async {
+ e.element.disabled = true;
+ _cache = await _caches.get(_isolate, _cache.id);
+ _r.dirty();
+ }),
new NavNotifyElement(_notifications, queue: _r.queue)
]),
- new DivElement()..classes = ['content-centered-big']
+ new DivElement()
+ ..classes = ['content-centered-big']
..children = [
new HeadingElement.h2()..text = 'Megamorphic Cache',
new HRElement(),
new ObjectCommonElement(_isolate, _cache, _retainedSizes,
- _reachableSizes, _references, _retainingPaths,
- _instances, queue: _r.queue),
+ _reachableSizes, _references, _retainingPaths, _instances,
+ queue: _r.queue),
new BRElement(),
- new DivElement()..classes = ['memberList']
+ new DivElement()
+ ..classes = ['memberList']
..children = [
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'selector',
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = '${_cache.selector}'
],
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'mask',
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = '${_cache.mask}'
],
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'buckets',
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..children = [
anyRef(_isolate, _cache.buckets, _instances,
- queue: _r.queue)
+ queue: _r.queue)
]
],
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'argumentsDescriptor',
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..children = [
anyRef(_isolate, _cache.argumentsDescriptor, _instances,
- queue: _r.queue)
+ queue: _r.queue)
]
]
],
diff --git a/runtime/observatory/lib/src/elements/metric/details.dart b/runtime/observatory/lib/src/elements/metric/details.dart
index 28e7686..e45e4d1 100644
--- a/runtime/observatory/lib/src/elements/metric/details.dart
+++ b/runtime/observatory/lib/src/elements/metric/details.dart
@@ -22,9 +22,9 @@
M.IsolateRef get isolate => _isolate;
M.Metric get metric => _metric;
- factory MetricDetailsElement(M.IsolateRef isolate, M.Metric metric,
- M.MetricRepository metrics,
- {RenderingQueue queue}) {
+ factory MetricDetailsElement(
+ M.IsolateRef isolate, M.Metric metric, M.MetricRepository metrics,
+ {RenderingQueue queue}) {
assert(isolate != null);
assert(metric != null);
assert(metrics != null);
@@ -53,34 +53,47 @@
void render() {
children = [
- new DivElement()..classes = ['memberList']
+ new DivElement()
+ ..classes = ['memberList']
..children = [
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'name',
- new DivElement()..classes = ['memberValue']
+ new DivElement()
+ ..classes = ['memberValue']
..text = _metric.name,
],
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'description',
- new DivElement()..classes = ['memberValue']
+ new DivElement()
+ ..classes = ['memberValue']
..text = _metric.description,
],
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'refresh rate',
- new DivElement()..classes = ['memberValue']
+ new DivElement()
+ ..classes = ['memberValue']
..children = _createRefreshRateSelect(),
],
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'buffer size',
- new DivElement()..classes = ['memberValue']
+ new DivElement()
+ ..classes = ['memberValue']
..children = _createBufferSizeSelect(),
]
]
@@ -94,15 +107,15 @@
s = new SelectElement()
..value = _rateToString(current)
..children = M.MetricSamplingRate.values.map((rate) {
- return new OptionElement(value: _rateToString(current),
- selected: current == rate)
- ..text = _rateToString(rate);
- }).toList(growable: false)
+ return new OptionElement(
+ value: _rateToString(current),
+ selected: current == rate)..text = _rateToString(rate);
+ }).toList(growable: false)
..onChange.listen((_) {
- _metrics.setSamplingRate(_isolate, _metric,
- M.MetricSamplingRate.values[s.selectedIndex]);
- _r.dirty();
- })
+ _metrics.setSamplingRate(
+ _isolate, _metric, M.MetricSamplingRate.values[s.selectedIndex]);
+ _r.dirty();
+ })
];
}
@@ -113,35 +126,44 @@
s = new SelectElement()
..value = _sizeToString(current)
..children = M.MetricBufferSize.values.map((rate) {
- return new OptionElement(value: _sizeToString(current),
- selected: current == rate)
- ..text = _sizeToString(rate);
- }).toList(growable: false)
+ return new OptionElement(
+ value: _sizeToString(current),
+ selected: current == rate)..text = _sizeToString(rate);
+ }).toList(growable: false)
..onChange.listen((_) {
- _metrics.setBufferSize(_isolate, _metric,
- M.MetricBufferSize.values[s.selectedIndex]);
- _r.dirty();
- })
+ _metrics.setBufferSize(
+ _isolate, _metric, M.MetricBufferSize.values[s.selectedIndex]);
+ _r.dirty();
+ })
];
}
static String _rateToString(M.MetricSamplingRate rate) {
switch (rate) {
- case M.MetricSamplingRate.off: return 'Never';
- case M.MetricSamplingRate.e100ms: return 'Ten times per second';
- case M.MetricSamplingRate.e1s: return 'Once a second';
- case M.MetricSamplingRate.e2s: return 'Every two seconds';
- case M.MetricSamplingRate.e4s: return 'Every four seconds';
- case M.MetricSamplingRate.e8s: return 'Every eight seconds';
+ case M.MetricSamplingRate.off:
+ return 'Never';
+ case M.MetricSamplingRate.e100ms:
+ return 'Ten times per second';
+ case M.MetricSamplingRate.e1s:
+ return 'Once a second';
+ case M.MetricSamplingRate.e2s:
+ return 'Every two seconds';
+ case M.MetricSamplingRate.e4s:
+ return 'Every four seconds';
+ case M.MetricSamplingRate.e8s:
+ return 'Every eight seconds';
}
throw new Exception('Unknown MetricSamplingRate ($rate)');
}
static String _sizeToString(M.MetricBufferSize size) {
switch (size) {
- case M.MetricBufferSize.n10samples: return '10';
- case M.MetricBufferSize.n100samples: return '100';
- case M.MetricBufferSize.n1000samples: return '1000';
+ case M.MetricBufferSize.n10samples:
+ return '10';
+ case M.MetricBufferSize.n100samples:
+ return '100';
+ case M.MetricBufferSize.n1000samples:
+ return '1000';
}
throw new Exception('Unknown MetricSamplingRate ($size)');
}
diff --git a/runtime/observatory/lib/src/elements/metric/graph.dart b/runtime/observatory/lib/src/elements/metric/graph.dart
index cc0d370..4286f55 100644
--- a/runtime/observatory/lib/src/elements/metric/graph.dart
+++ b/runtime/observatory/lib/src/elements/metric/graph.dart
@@ -24,9 +24,9 @@
M.IsolateRef get isolate => _isolate;
M.Metric get metric => _metric;
- factory MetricGraphElement(M.IsolateRef isolate, M.Metric metric,
- M.MetricRepository metrics,
- {RenderingQueue queue}) {
+ factory MetricGraphElement(
+ M.IsolateRef isolate, M.Metric metric, M.MetricRepository metrics,
+ {RenderingQueue queue}) {
assert(isolate != null);
assert(metric != null);
assert(metrics != null);
@@ -56,15 +56,17 @@
}
final _columns = [
- new ChartColumnSpec(label: 'Time', type: ChartColumnSpec.TYPE_TIMESTAMP),
- new ChartColumnSpec(label: 'Value', formatter: (v) => v.toString())
+ new ChartColumnSpec(label: 'Time', type: ChartColumnSpec.TYPE_TIMESTAMP),
+ new ChartColumnSpec(label: 'Value', formatter: (v) => v.toString())
];
void render() {
final min = _metrics.getMinValue(_isolate, _metric);
final max = _metrics.getMaxValue(_isolate, _metric);
- final rows = _metrics.getSamples(_isolate, _metric).map((s) =>
- [s.time.millisecondsSinceEpoch, s.value]).toList();
+ final rows = _metrics
+ .getSamples(_isolate, _metric)
+ .map((s) => [s.time.millisecondsSinceEpoch, s.value])
+ .toList();
final current = rows.last.last;
var message = 'current: $current';
@@ -77,34 +79,47 @@
final host = new DivElement();
children = [
- new DivElement()..classes = ['memberList']
+ new DivElement()
+ ..classes = ['memberList']
..children = [
- new DivElement()..classes = ['memberItem']
- ..children = min == null ? const [] : [
- new DivElement()..classes = ['memberName']
- ..text = 'min',
- new DivElement()..classes = ['memberValue']
- ..text = '$min'
- ],
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
+ ..children = min == null
+ ? const []
+ : [
+ new DivElement()
+ ..classes = ['memberName']
+ ..text = 'min',
+ new DivElement()
+ ..classes = ['memberValue']
+ ..text = '$min'
+ ],
+ new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'current',
- new DivElement()..classes = ['memberValue']
+ new DivElement()
+ ..classes = ['memberValue']
..text = '$current'
],
- new DivElement()..classes = ['memberItem']
- ..children = max == null ? const [] : [
- new DivElement()..classes = ['memberName']
- ..text = 'max',
- new DivElement()..classes = ['memberValue']
- ..text = '$max'
- ]
+ new DivElement()
+ ..classes = ['memberItem']
+ ..children = max == null
+ ? const []
+ : [
+ new DivElement()
+ ..classes = ['memberName']
+ ..text = 'max',
+ new DivElement()
+ ..classes = ['memberValue']
+ ..text = '$max'
+ ]
],
- new DivElement()..classes = ['graph']
- ..children = [
- host
- ]
+ new DivElement()
+ ..classes = ['graph']
+ ..children = [host]
];
if (rows.length <= 1) {
return;
diff --git a/runtime/observatory/lib/src/elements/metrics.dart b/runtime/observatory/lib/src/elements/metrics.dart
index 12a3ef6..4c769c7 100644
--- a/runtime/observatory/lib/src/elements/metrics.dart
+++ b/runtime/observatory/lib/src/elements/metrics.dart
@@ -20,16 +20,16 @@
import 'package:observatory/src/elements/nav/vm_menu.dart';
class MetricsPageElement extends HtmlElement implements Renderable {
- static const tag = const Tag<MetricsPageElement>('metrics-page',
- dependencies: const [
- MetricDetailsElement.tag,
- MetricGraphElement.tag,
- NavTopMenuElement.tag,
- NavVMMenuElement.tag,
- NavIsolateMenuElement.tag,
- NavRefreshElement.tag,
- NavNotifyElement.tag,
- ]);
+ static const tag =
+ const Tag<MetricsPageElement>('metrics-page', dependencies: const [
+ MetricDetailsElement.tag,
+ MetricGraphElement.tag,
+ NavTopMenuElement.tag,
+ NavVMMenuElement.tag,
+ NavIsolateMenuElement.tag,
+ NavRefreshElement.tag,
+ NavNotifyElement.tag,
+ ]);
RenderingScheduler<MetricsPageElement> _r;
@@ -43,16 +43,17 @@
List<M.Metric> _available;
M.Metric _selected;
-
M.VMRef get vm => _vm;
M.IsolateRef get isolate => _isolate;
M.NotificationRepository get notifications => _notifications;
- factory MetricsPageElement(M.VM vm, M.IsolateRef isolate,
- M.EventRepository events,
- M.NotificationRepository notifications,
- M.MetricRepository metrics,
- {RenderingQueue queue}) {
+ factory MetricsPageElement(
+ M.VM vm,
+ M.IsolateRef isolate,
+ M.EventRepository events,
+ M.NotificationRepository notifications,
+ M.MetricRepository metrics,
+ {RenderingQueue queue}) {
assert(vm != null);
assert(isolate != null);
assert(events != null);
@@ -91,42 +92,50 @@
new NavIsolateMenuElement(_isolate, _events, queue: _r.queue),
navMenu('metrics'),
new NavRefreshElement(queue: _r.queue)
- ..onRefresh.listen((e) {
- e.element.disabled = true;
- _refresh();
- }),
+ ..onRefresh.listen((e) {
+ e.element.disabled = true;
+ _refresh();
+ }),
new NavNotifyElement(_notifications, queue: _r.queue)
]),
- new DivElement()..classes = ['content-centered-big']
+ new DivElement()
+ ..classes = ['content-centered-big']
..children = [
new HeadingElement.h2()..text = 'Metrics',
new HRElement(),
- new DivElement()..classes = ['memberList']
+ new DivElement()
+ ..classes = ['memberList']
..children = [
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'Metric',
- new DivElement()..classes = ['memberValue']
+ new DivElement()
+ ..classes = ['memberValue']
..children = _available == null
- ? [new SpanElement()..text = 'Loading..']
- : _createMetricSelect()
+ ? [new SpanElement()..text = 'Loading..']
+ : _createMetricSelect()
]
],
new HRElement(),
new DivElement()
- ..children = _selected == null ? const []
- : [
- new MetricDetailsElement(_isolate, _selected, _metrics,
- queue: _r.queue)
- ],
+ ..children = _selected == null
+ ? const []
+ : [
+ new MetricDetailsElement(_isolate, _selected, _metrics,
+ queue: _r.queue)
+ ],
new HRElement(),
- new DivElement()..classes = ['graph']
- ..children = _selected == null ? const []
- : [
- new MetricGraphElement(_isolate, _selected, _metrics,
- queue: _r.queue)
- ]
+ new DivElement()
+ ..classes = ['graph']
+ ..children = _selected == null
+ ? const []
+ : [
+ new MetricGraphElement(_isolate, _selected, _metrics,
+ queue: _r.queue)
+ ]
],
];
}
@@ -145,14 +154,14 @@
s = new SelectElement()
..value = _selected.name
..children = _available.map((metric) {
- return new OptionElement(value: metric.name,
- selected: _selected == metric)
- ..text = metric.name;
- }).toList(growable: false)
+ return new OptionElement(
+ value: metric.name,
+ selected: _selected == metric)..text = metric.name;
+ }).toList(growable: false)
..onChange.listen((_) {
- _selected = _available[s.selectedIndex];
- _r.dirty();
- })
+ _selected = _available[s.selectedIndex];
+ _r.dirty();
+ })
];
}
}
diff --git a/runtime/observatory/lib/src/elements/nav/class_menu.dart b/runtime/observatory/lib/src/elements/nav/class_menu.dart
index 6c13336..d8ef46e 100644
--- a/runtime/observatory/lib/src/elements/nav/class_menu.dart
+++ b/runtime/observatory/lib/src/elements/nav/class_menu.dart
@@ -58,8 +58,8 @@
void render() {
children = [
- navMenu(cls.name, content: _content,
- link: Uris.inspect(isolate, object: cls))
+ navMenu(cls.name,
+ content: _content, link: Uris.inspect(isolate, object: cls))
];
}
}
diff --git a/runtime/observatory/lib/src/elements/nav/isolate_menu.dart b/runtime/observatory/lib/src/elements/nav/isolate_menu.dart
index a5b64f1..771d785 100644
--- a/runtime/observatory/lib/src/elements/nav/isolate_menu.dart
+++ b/runtime/observatory/lib/src/elements/nav/isolate_menu.dart
@@ -4,8 +4,7 @@
import 'dart:html';
import 'dart:async';
-import 'package:observatory/models.dart' as M
- show IsolateRef, EventRepository;
+import 'package:observatory/models.dart' as M show IsolateRef, EventRepository;
import 'package:observatory/src/elements/helpers/nav_menu.dart';
import 'package:observatory/src/elements/helpers/rendering_scheduler.dart';
import 'package:observatory/src/elements/helpers/tag.dart';
@@ -14,7 +13,7 @@
class NavIsolateMenuElement extends HtmlElement implements Renderable {
static const tag = const Tag<NavIsolateMenuElement>('nav-isolate-menu',
- dependencies: const [NavMenuItemElement.tag]);
+ dependencies: const [NavMenuItemElement.tag]);
RenderingScheduler _r;
@@ -33,8 +32,8 @@
_r.dirty();
}
- factory NavIsolateMenuElement(M.IsolateRef isolate,
- M.EventRepository events, {RenderingQueue queue}) {
+ factory NavIsolateMenuElement(M.IsolateRef isolate, M.EventRepository events,
+ {RenderingQueue queue}) {
assert(isolate != null);
assert(events != null);
NavIsolateMenuElement e = document.createElement(tag.name);
@@ -50,8 +49,11 @@
void attached() {
super.attached();
_updatesSubscription = _events.onIsolateUpdate
- .where((e) => e.isolate.id == isolate.id)
- .listen((e) { _isolate = e.isolate; _r.dirty(); });
+ .where((e) => e.isolate.id == isolate.id)
+ .listen((e) {
+ _isolate = e.isolate;
+ _r.dirty();
+ });
_r.enable();
}
@@ -67,32 +69,31 @@
void render() {
final content = [
- new NavMenuItemElement('debugger', queue: _r.queue,
- link: Uris.debugger(isolate)),
- new NavMenuItemElement('class hierarchy', queue: _r.queue,
- link: Uris.classTree(isolate)),
- new NavMenuItemElement('cpu profile', queue: _r.queue,
- link: Uris.cpuProfiler(isolate)),
- new NavMenuItemElement('cpu profile (table)', queue: _r.queue,
- link: Uris.cpuProfilerTable(isolate)),
- new NavMenuItemElement('allocation profile', queue: _r.queue,
- link: Uris.allocationProfiler(isolate)),
- new NavMenuItemElement('heap map', queue: _r.queue,
- link: Uris.heapMap(isolate)),
- new NavMenuItemElement('metrics', queue: _r.queue,
- link: Uris.metrics(isolate)),
- new NavMenuItemElement('heap snapshot', queue: _r.queue,
- link: Uris.heapSnapshot(isolate)),
- new NavMenuItemElement('persistent handles', queue: _r.queue,
- link: Uris.persistentHandles(isolate)),
- new NavMenuItemElement('ports', queue: _r.queue,
- link: Uris.ports(isolate)),
- new NavMenuItemElement('logging', queue: _r.queue,
- link: Uris.logging(isolate)),
+ new NavMenuItemElement('debugger',
+ queue: _r.queue, link: Uris.debugger(isolate)),
+ new NavMenuItemElement('class hierarchy',
+ queue: _r.queue, link: Uris.classTree(isolate)),
+ new NavMenuItemElement('cpu profile',
+ queue: _r.queue, link: Uris.cpuProfiler(isolate)),
+ new NavMenuItemElement('cpu profile (table)',
+ queue: _r.queue, link: Uris.cpuProfilerTable(isolate)),
+ new NavMenuItemElement('allocation profile',
+ queue: _r.queue, link: Uris.allocationProfiler(isolate)),
+ new NavMenuItemElement('heap map',
+ queue: _r.queue, link: Uris.heapMap(isolate)),
+ new NavMenuItemElement('metrics',
+ queue: _r.queue, link: Uris.metrics(isolate)),
+ new NavMenuItemElement('heap snapshot',
+ queue: _r.queue, link: Uris.heapSnapshot(isolate)),
+ new NavMenuItemElement('persistent handles',
+ queue: _r.queue, link: Uris.persistentHandles(isolate)),
+ new NavMenuItemElement('ports',
+ queue: _r.queue, link: Uris.ports(isolate)),
+ new NavMenuItemElement('logging',
+ queue: _r.queue, link: Uris.logging(isolate)),
]..addAll(_content);
children = [
- navMenu(isolate.name, content: content,
- link: Uris.inspect(isolate))
+ navMenu(isolate.name, content: content, link: Uris.inspect(isolate))
];
}
}
diff --git a/runtime/observatory/lib/src/elements/nav/library_menu.dart b/runtime/observatory/lib/src/elements/nav/library_menu.dart
index 783adf3..5f22f81 100644
--- a/runtime/observatory/lib/src/elements/nav/library_menu.dart
+++ b/runtime/observatory/lib/src/elements/nav/library_menu.dart
@@ -58,8 +58,9 @@
void render() {
children = [
- navMenu(library.name, content: _content,
- link: Uris.inspect(isolate, object: library).toString())
+ navMenu(library.name,
+ content: _content,
+ link: Uris.inspect(isolate, object: library).toString())
];
}
}
diff --git a/runtime/observatory/lib/src/elements/nav/menu_item.dart b/runtime/observatory/lib/src/elements/nav/menu_item.dart
index 5be6723..b7c3ea3 100644
--- a/runtime/observatory/lib/src/elements/nav/menu_item.dart
+++ b/runtime/observatory/lib/src/elements/nav/menu_item.dart
@@ -29,9 +29,8 @@
_r.dirty();
}
-
- factory NavMenuItemElement(String label, {String link,
- RenderingQueue queue}) {
+ factory NavMenuItemElement(String label,
+ {String link, RenderingQueue queue}) {
assert(label != null);
NavMenuItemElement e = document.createElement(tag.name);
e._r = new RenderingScheduler(e, queue: queue);
@@ -60,10 +59,8 @@
new LIElement()
..classes = ['nav-menu-item']
..children = [
- new AnchorElement(href: link)
- ..text = label,
- new UListElement()
- ..children = _content
+ new AnchorElement(href: link)..text = label,
+ new UListElement()..children = _content
]
];
}
diff --git a/runtime/observatory/lib/src/elements/nav/notify.dart b/runtime/observatory/lib/src/elements/nav/notify.dart
index 5411e11..cbba2db 100644
--- a/runtime/observatory/lib/src/elements/nav/notify.dart
+++ b/runtime/observatory/lib/src/elements/nav/notify.dart
@@ -12,8 +12,10 @@
class NavNotifyElement extends HtmlElement implements Renderable {
static const tag = const Tag<NavNotifyElement>('nav-notify',
- dependencies: const [ NavNotifyEventElement.tag,
- NavNotifyExceptionElement.tag ]);
+ dependencies: const [
+ NavNotifyEventElement.tag,
+ NavNotifyExceptionElement.tag
+ ]);
RenderingScheduler _r;
@@ -30,7 +32,7 @@
_notifyOnPause = _r.checkAndReact(_notifyOnPause, value);
factory NavNotifyElement(M.NotificationRepository repository,
- {bool notifyOnPause: true, RenderingQueue queue}) {
+ {bool notifyOnPause: true, RenderingQueue queue}) {
assert(repository != null);
assert(notifyOnPause != null);
NavNotifyElement e = document.createElement(tag.name);
@@ -62,8 +64,8 @@
new DivElement()
..children = [
new DivElement()
- ..children = _repository.list()
- .where(_filter).map(_toElement).toList()
+ ..children =
+ _repository.list().where(_filter).map(_toElement).toList()
]
];
}
@@ -78,12 +80,11 @@
HtmlElement _toElement(M.Notification notification) {
if (notification is M.EventNotification) {
return new NavNotifyEventElement(notification.event, queue: _r.queue)
- ..onDelete.listen((_) => _repository.delete(notification));
+ ..onDelete.listen((_) => _repository.delete(notification));
} else if (notification is M.ExceptionNotification) {
- return new NavNotifyExceptionElement(
- notification.exception, stacktrace: notification.stacktrace,
- queue: _r.queue)
- ..onDelete.listen((_) => _repository.delete(notification));
+ return new NavNotifyExceptionElement(notification.exception,
+ stacktrace: notification.stacktrace, queue: _r.queue)
+ ..onDelete.listen((_) => _repository.delete(notification));
} else {
assert(false);
return new DivElement()..text = 'Invalid Notification Type';
diff --git a/runtime/observatory/lib/src/elements/nav/notify_event.dart b/runtime/observatory/lib/src/elements/nav/notify_event.dart
index b46236e..44a6d26 100644
--- a/runtime/observatory/lib/src/elements/nav/notify_event.dart
+++ b/runtime/observatory/lib/src/elements/nav/notify_event.dart
@@ -9,7 +9,7 @@
import 'package:observatory/src/elements/helpers/tag.dart';
import 'package:observatory/src/elements/helpers/uris.dart';
-class EventDeleteEvent{
+class EventDeleteEvent {
final M.Event event;
EventDeleteEvent(this.event);
}
@@ -26,7 +26,7 @@
Stream<EventDeleteEvent> get onDelete => _onDelete.stream;
M.Event _event;
-
+
M.Event get event => _event;
factory NavNotifyEventElement(M.Event event, {RenderingQueue queue}) {
@@ -80,22 +80,22 @@
new DivElement()
..children = []
..children.addAll(content)
- ..children.add(new ButtonElement()..innerHtml = '×'
- ..onClick.map(_toEvent).listen(_delete))
+ ..children.add(new ButtonElement()
+ ..innerHtml = '×'
+ ..onClick.map(_toEvent).listen(_delete))
];
}
static List<Element> _managePauseStartEvent(M.PauseStartEvent event) {
return [
new SpanElement()..text = 'Isolate ',
- new AnchorElement(
- href: Uris.inspect(event.isolate))
+ new AnchorElement(href: Uris.inspect(event.isolate))
..text = event.isolate.name,
new SpanElement()..text = ' is paused at isolate start',
- new BRElement(), new BRElement(), new SpanElement()..text = '[',
- new AnchorElement(
- href: Uris.debugger(event.isolate))
- ..text = 'debug',
+ new BRElement(),
+ new BRElement(),
+ new SpanElement()..text = '[',
+ new AnchorElement(href: Uris.debugger(event.isolate))..text = 'debug',
new SpanElement()..text = ']'
];
}
@@ -103,50 +103,47 @@
static List<Element> _managePauseExitEvent(M.PauseExitEvent event) {
return [
new SpanElement()..text = 'Isolate ',
- new AnchorElement(
- href: Uris.inspect(event.isolate))
+ new AnchorElement(href: Uris.inspect(event.isolate))
..text = event.isolate.name,
new SpanElement()..text = ' is paused at isolate exit',
- new BRElement(), new BRElement(), new SpanElement()..text = '[',
- new AnchorElement(
- href: Uris.debugger(event.isolate))
- ..text = 'debug',
+ new BRElement(),
+ new BRElement(),
+ new SpanElement()..text = '[',
+ new AnchorElement(href: Uris.debugger(event.isolate))..text = 'debug',
new SpanElement()..text = ']'
];
}
- static List<Element> _managePauseBreakpointEvent(M.PauseBreakpointEvent event) {
+ static List<Element> _managePauseBreakpointEvent(
+ M.PauseBreakpointEvent event) {
String message = ' is paused';
if (event.breakpoint != null) {
- message += ' at breakpoint ${event.breakpoint.number}';
+ message += ' at breakpoint ${event.breakpoint.number}';
}
return [
new SpanElement()..text = 'Isolate ',
- new AnchorElement(
- href: Uris.inspect(event.isolate))
+ new AnchorElement(href: Uris.inspect(event.isolate))
..text = event.isolate.name,
- new SpanElement()
- ..text = message,
- new BRElement(), new BRElement(), new SpanElement()..text = '[',
- new AnchorElement(
- href: Uris.debugger(event.isolate))
- ..text = 'debug',
+ new SpanElement()..text = message,
+ new BRElement(),
+ new BRElement(),
+ new SpanElement()..text = '[',
+ new AnchorElement(href: Uris.debugger(event.isolate))..text = 'debug',
new SpanElement()..text = ']'
];
}
- static List<Element> _managePauseInterruptedEvent(M.PauseInterruptedEvent event) {
+ static List<Element> _managePauseInterruptedEvent(
+ M.PauseInterruptedEvent event) {
return [
new SpanElement()..text = 'Isolate ',
- new AnchorElement(
- href: Uris.inspect(event.isolate))
+ new AnchorElement(href: Uris.inspect(event.isolate))
..text = event.isolate.name,
- new SpanElement()
- ..text = ' is paused',
- new BRElement(), new BRElement(), new SpanElement()..text = '[',
- new AnchorElement(
- href: Uris.debugger(event.isolate))
- ..text = 'debug',
+ new SpanElement()..text = ' is paused',
+ new BRElement(),
+ new BRElement(),
+ new SpanElement()..text = '[',
+ new AnchorElement(href: Uris.debugger(event.isolate))..text = 'debug',
new SpanElement()..text = ']'
];
}
@@ -154,15 +151,13 @@
static List<Element> _managePauseExceptionEvent(M.PauseExceptionEvent event) {
return [
new SpanElement()..text = 'Isolate ',
- new AnchorElement(
- href: Uris.inspect(event.isolate))
+ new AnchorElement(href: Uris.inspect(event.isolate))
..text = event.isolate.name,
- new SpanElement()
- ..text = ' is paused due to exception',
- new BRElement(), new BRElement(), new SpanElement()..text = '[',
- new AnchorElement(
- href: Uris.debugger(event.isolate))
- ..text = 'debug',
+ new SpanElement()..text = ' is paused due to exception',
+ new BRElement(),
+ new BRElement(),
+ new SpanElement()..text = '[',
+ new AnchorElement(href: Uris.debugger(event.isolate))..text = 'debug',
new SpanElement()..text = ']'
];
}
@@ -170,23 +165,24 @@
static List<Element> _manageNoneEvent(M.NoneEvent event) {
return [
new SpanElement()..text = 'Isolate ',
- new AnchorElement(
- href: Uris.inspect(event.isolate))
+ new AnchorElement(href: Uris.inspect(event.isolate))
..text = event.isolate.name,
- new SpanElement()
- ..text = ' is paused',
- new BRElement(), new BRElement(), new SpanElement()..text = '[',
- new AnchorElement(
- href: Uris.debugger(event.isolate))
- ..text = 'debug',
+ new SpanElement()..text = ' is paused',
+ new BRElement(),
+ new BRElement(),
+ new SpanElement()..text = '[',
+ new AnchorElement(href: Uris.debugger(event.isolate))..text = 'debug',
new SpanElement()..text = ']'
];
}
- static List<Element> _manageConnectionClosedEvent(M.ConnectionClosedEvent event) {
+ static List<Element> _manageConnectionClosedEvent(
+ M.ConnectionClosedEvent event) {
return [
new SpanElement()..text = 'Disconnected from VM: ${event.reason}',
- new BRElement(), new BRElement(), new SpanElement()..text = '[',
+ new BRElement(),
+ new BRElement(),
+ new SpanElement()..text = '[',
new AnchorElement(href: Uris.vmConnect())..text = 'Connect to a VM',
new SpanElement()..text = ']'
];
@@ -196,8 +192,8 @@
return [
new SpanElement()..text = 'Inspect ${event.inspectee.id}',
new BRElement(), new BRElement(), new SpanElement()..text = '[',
- new AnchorElement(href: Uris.inspect(event.isolate,
- object: event.inspectee))
+ new AnchorElement(
+ href: Uris.inspect(event.isolate, object: event.inspectee))
..text = 'Inspect',
new SpanElement()..text = ']'
// TODO(cbernaschina) add InstanceRefElement back.
@@ -209,7 +205,8 @@
if (event.error != null) {
return [
new SpanElement()..text = 'Isolate reload failed:',
- new BRElement(), new BRElement(),
+ new BRElement(),
+ new BRElement(),
new DivElement()
..classes = ["indent", "error"]
..text = event.error.message.toString()
diff --git a/runtime/observatory/lib/src/elements/nav/notify_exception.dart b/runtime/observatory/lib/src/elements/nav/notify_exception.dart
index 0e92bda..167181c 100644
--- a/runtime/observatory/lib/src/elements/nav/notify_exception.dart
+++ b/runtime/observatory/lib/src/elements/nav/notify_exception.dart
@@ -9,8 +9,7 @@
import 'package:observatory/src/elements/helpers/uris.dart';
import 'package:observatory/models.dart' show ConnectionException;
-
-class ExceptionDeleteEvent{
+class ExceptionDeleteEvent {
final Exception exception;
final StackTrace stacktrace;
@@ -23,7 +22,7 @@
RenderingScheduler _r;
Stream<RenderedEvent<NavNotifyExceptionElement>> get onRendered =>
- _r.onRendered;
+ _r.onRendered;
final StreamController<ExceptionDeleteEvent> _onDelete =
new StreamController<ExceptionDeleteEvent>.broadcast();
@@ -31,7 +30,7 @@
Exception _exception;
StackTrace _stacktrace;
-
+
Exception get exception => _exception;
StackTrace get stacktrace => _stacktrace;
@@ -72,16 +71,19 @@
children = [
new DivElement()
..children = [
- new SpanElement()..text = 'The request cannot be completed because the '
- 'VM is currently disconnected',
- new BRElement(), new BRElement(),
- new SpanElement()..text = '[',
- new AnchorElement(href: Uris.vmConnect())
- ..text = 'Connect to a different VM',
- new SpanElement()..text = ']',
- new ButtonElement()..innerHtml = '×'
- ..onClick.map(_toEvent).listen(_delete)
- ]
+ new SpanElement()
+ ..text = 'The request cannot be completed because the '
+ 'VM is currently disconnected',
+ new BRElement(),
+ new BRElement(),
+ new SpanElement()..text = '[',
+ new AnchorElement(href: Uris.vmConnect())
+ ..text = 'Connect to a different VM',
+ new SpanElement()..text = ']',
+ new ButtonElement()
+ ..innerHtml = '×'
+ ..onClick.map(_toEvent).listen(_delete)
+ ]
];
}
@@ -89,14 +91,16 @@
List<Node> content;
content = [
new SpanElement()..text = 'Unexpected exception:',
- new BRElement(), new BRElement(),
+ new BRElement(),
+ new BRElement(),
new DivElement()..text = exception.toString(),
new BRElement()
];
if (stacktrace != null) {
content.addAll([
new SpanElement()..text = 'Stacktrace:',
- new BRElement(), new BRElement(),
+ new BRElement(),
+ new BRElement(),
new DivElement()..text = stacktrace.toString(),
new BRElement()
]);
@@ -106,13 +110,11 @@
new AnchorElement(href: Uris.vmConnect())
..text = 'Connect to a different VM',
new SpanElement()..text = ']',
- new ButtonElement()..innerHtml = '×'
+ new ButtonElement()
+ ..innerHtml = '×'
..onClick.map(_toEvent).listen(_delete)
]);
- children = [
- new DivElement()
- ..children = content
- ];
+ children = [new DivElement()..children = content];
}
ExceptionDeleteEvent _toEvent(_) {
diff --git a/runtime/observatory/lib/src/elements/nav/refresh.dart b/runtime/observatory/lib/src/elements/nav/refresh.dart
index b246851..0b515d4 100644
--- a/runtime/observatory/lib/src/elements/nav/refresh.dart
+++ b/runtime/observatory/lib/src/elements/nav/refresh.dart
@@ -20,7 +20,7 @@
Stream<RenderedEvent<NavRefreshElement>> get onRendered => _r.onRendered;
final StreamController<RefreshEvent> _onRefresh =
- new StreamController<RefreshEvent>.broadcast();
+ new StreamController<RefreshEvent>.broadcast();
Stream<RefreshEvent> get onRefresh => _onRefresh.stream;
bool _disabled;
@@ -32,8 +32,8 @@
set disabled(bool value) => _disabled = _r.checkAndReact(_disabled, value);
set label(String value) => _label = _r.checkAndReact(_label, value);
- factory NavRefreshElement({String label: 'Refresh', bool disabled: false,
- RenderingQueue queue}) {
+ factory NavRefreshElement(
+ {String label: 'Refresh', bool disabled: false, RenderingQueue queue}) {
assert(label != null);
assert(disabled != null);
NavRefreshElement e = document.createElement(tag.name);
diff --git a/runtime/observatory/lib/src/elements/nav/top_menu.dart b/runtime/observatory/lib/src/elements/nav/top_menu.dart
index 77a0402..0c4c957 100644
--- a/runtime/observatory/lib/src/elements/nav/top_menu.dart
+++ b/runtime/observatory/lib/src/elements/nav/top_menu.dart
@@ -12,7 +12,7 @@
class NavTopMenuElement extends HtmlElement implements Renderable {
static const tag = const Tag<NavTopMenuElement>('nav-top-menu',
- dependencies: const [NavMenuItemElement.tag]);
+ dependencies: const [NavMenuItemElement.tag]);
RenderingScheduler _r;
@@ -52,8 +52,6 @@
final content = ([
new NavMenuItemElement('Connect to a VM', link: Uris.vmConnect()),
]..addAll(_content));
- children = [
- navMenu('Observatory', link: Uris.vm(), content: content)
- ];
+ children = [navMenu('Observatory', link: Uris.vm(), content: content)];
}
}
diff --git a/runtime/observatory/lib/src/elements/nav/vm_menu.dart b/runtime/observatory/lib/src/elements/nav/vm_menu.dart
index c652f36..4b598cd 100644
--- a/runtime/observatory/lib/src/elements/nav/vm_menu.dart
+++ b/runtime/observatory/lib/src/elements/nav/vm_menu.dart
@@ -4,8 +4,7 @@
import 'dart:html';
import 'dart:async';
-import 'package:observatory/models.dart' as M
- show VM, EventRepository;
+import 'package:observatory/models.dart' as M show VM, EventRepository;
import 'package:observatory/src/elements/helpers/nav_menu.dart';
import 'package:observatory/src/elements/helpers/rendering_scheduler.dart';
import 'package:observatory/src/elements/helpers/tag.dart';
@@ -14,7 +13,7 @@
class NavVMMenuElement extends HtmlElement implements Renderable {
static const tag = const Tag<NavVMMenuElement>('nav-vm-menu',
- dependencies: const [NavMenuItemElement.tag]);
+ dependencies: const [NavMenuItemElement.tag]);
RenderingScheduler _r;
@@ -34,7 +33,7 @@
}
factory NavVMMenuElement(M.VM vm, M.EventRepository events,
- {RenderingQueue queue}) {
+ {RenderingQueue queue}) {
assert(vm != null);
assert(events != null);
NavVMMenuElement e = document.createElement(tag.name);
@@ -49,8 +48,10 @@
@override
void attached() {
super.attached();
- _updatesSubscription = _events.onVMUpdate
- .listen((e) { _vm = e.vm; _r.dirty(); });
+ _updatesSubscription = _events.onVMUpdate.listen((e) {
+ _vm = e.vm;
+ _r.dirty();
+ });
_r.enable();
}
@@ -63,15 +64,10 @@
}
void render() {
- final content = (
- _vm.isolates.map((isolate) {
- return new NavMenuItemElement(isolate.name, queue: _r.queue,
- link: Uris.inspect(isolate));
- }).toList()
- ..addAll(_content)
- );
- children = [
- navMenu(vm.displayName, link: Uris.vm(), content: content)
- ];
+ final content = (_vm.isolates.map((isolate) {
+ return new NavMenuItemElement(isolate.name,
+ queue: _r.queue, link: Uris.inspect(isolate));
+ }).toList()..addAll(_content));
+ children = [navMenu(vm.displayName, link: Uris.vm(), content: content)];
}
}
diff --git a/runtime/observatory/lib/src/elements/object_common.dart b/runtime/observatory/lib/src/elements/object_common.dart
index a52dc7b..0db760d 100644
--- a/runtime/observatory/lib/src/elements/object_common.dart
+++ b/runtime/observatory/lib/src/elements/object_common.dart
@@ -14,13 +14,13 @@
import 'package:observatory/utils.dart';
class ObjectCommonElement extends HtmlElement implements Renderable {
- static const tag = const Tag<ObjectCommonElement>('object-common',
- dependencies: const [
- ClassRefElement.tag,
- InboundReferencesElement.tag,
- RetainingPathElement.tag,
- SentinelValueElement.tag
- ]);
+ static const tag =
+ const Tag<ObjectCommonElement>('object-common', dependencies: const [
+ ClassRefElement.tag,
+ InboundReferencesElement.tag,
+ RetainingPathElement.tag,
+ SentinelValueElement.tag
+ ]);
RenderingScheduler<ObjectCommonElement> _r;
@@ -41,13 +41,15 @@
M.IsolateRef get isolate => _isolate;
M.Object get object => _object;
- factory ObjectCommonElement(M.IsolateRef isolate, M.Object object,
- M.RetainedSizeRepository retainedSizes,
- M.ReachableSizeRepository reachableSizes,
- M.InboundReferencesRepository references,
- M.RetainingPathRepository retainingPaths,
- M.InstanceRepository instances,
- {RenderingQueue queue}) {
+ factory ObjectCommonElement(
+ M.IsolateRef isolate,
+ M.Object object,
+ M.RetainedSizeRepository retainedSizes,
+ M.ReachableSizeRepository reachableSizes,
+ M.InboundReferencesRepository references,
+ M.RetainingPathRepository retainingPaths,
+ M.InstanceRepository instances,
+ {RenderingQueue queue}) {
assert(isolate != null);
assert(object != null);
assert(retainedSizes != null);
@@ -86,67 +88,85 @@
InboundReferencesElement _inbounds;
void render() {
- _path = _path ?? new RetainingPathElement(_isolate, _object,
- _retainingPaths, _instances,
- queue: _r.queue);
- _inbounds = _inbounds ?? new InboundReferencesElement(_isolate, _object,
- _references,
- _instances,
- queue: _r.queue);
+ _path = _path ??
+ new RetainingPathElement(_isolate, _object, _retainingPaths, _instances,
+ queue: _r.queue);
+ _inbounds = _inbounds ??
+ new InboundReferencesElement(_isolate, _object, _references, _instances,
+ queue: _r.queue);
children = [
- new DivElement()..classes = ['memberList']
+ new DivElement()
+ ..classes = ['memberList']
..children = [
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'Class ',
- new DivElement()..classes = ['memberValue']
+ new DivElement()
+ ..classes = ['memberValue']
..children = [
_object.clazz == null
- ? (new SpanElement()..text = '...')
- : new ClassRefElement(_isolate, _object.clazz,
- queue: _r.queue)
+ ? (new SpanElement()..text = '...')
+ : new ClassRefElement(_isolate, _object.clazz,
+ queue: _r.queue)
]
],
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..title = 'Space for this object in memory'
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'Shallow size ',
- new DivElement()..classes = ['memberValue']
+ new DivElement()
+ ..classes = ['memberValue']
..text = Utils.formatSize(_object.size ?? 0)
],
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..title = 'Space reachable from this object, '
- 'excluding class references'
+ 'excluding class references'
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'Reachable size ',
- new DivElement()..classes = ['memberValue']
+ new DivElement()
+ ..classes = ['memberValue']
..children = _createReachableSizeValue()
],
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..title = 'Space that would be reclaimed if references to this '
- 'object were replaced with null'
+ 'object were replaced with null'
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'Retained size ',
- new DivElement()..classes = ['memberValue']
+ new DivElement()
+ ..classes = ['memberValue']
..children = _createRetainedSizeValue()
],
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'Retaining path ',
- new DivElement()..classes = ['memberValue']
+ new DivElement()
+ ..classes = ['memberValue']
..children = [_path]
],
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..title = 'Objects which directly reference this object'
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'Inbound references ',
- new DivElement()..classes = ['memberValue']
+ new DivElement()
+ ..classes = ['memberValue']
..children = [_inbounds]
]
]
@@ -157,29 +177,26 @@
final content = <Element>[];
if (_reachableSize != null) {
if (_reachableSize.isSentinel) {
- content.add(
- new SentinelValueElement(_reachableSize.asSentinel, queue: _r.queue)
- );
+ content.add(new SentinelValueElement(_reachableSize.asSentinel,
+ queue: _r.queue));
} else {
- content.add(
- new SpanElement()..text = Utils.formatSize(int.parse(
- _reachableSize.asValue.valueAsString))
- );
+ content.add(new SpanElement()
+ ..text = Utils
+ .formatSize(int.parse(_reachableSize.asValue.valueAsString)));
}
} else {
- content.add(
- new SpanElement()..text = '...'
- );
+ content.add(new SpanElement()..text = '...');
}
- final button = new ButtonElement()..classes = ['reachable_size']
+ final button = new ButtonElement()
+ ..classes = ['reachable_size']
..disabled = _loadingReachableBytes
..text = '↺';
button.onClick.listen((_) async {
- button.disabled = true;
- _loadingReachableBytes = true;
- _reachableSize = await _reachableSizes.get(_isolate, _object.id);
- _r.dirty();
- });
+ button.disabled = true;
+ _loadingReachableBytes = true;
+ _reachableSize = await _reachableSizes.get(_isolate, _object.id);
+ _r.dirty();
+ });
content.add(button);
return content;
}
@@ -188,29 +205,26 @@
final content = <Element>[];
if (_retainedSize != null) {
if (_retainedSize.isSentinel) {
- content.add(
- new SentinelValueElement(_retainedSize.asSentinel, queue: _r.queue)
- );
+ content.add(new SentinelValueElement(_retainedSize.asSentinel,
+ queue: _r.queue));
} else {
- content.add(
- new SpanElement()..text = Utils.formatSize(int.parse(
- _retainedSize.asValue.valueAsString))
- );
+ content.add(new SpanElement()
+ ..text =
+ Utils.formatSize(int.parse(_retainedSize.asValue.valueAsString)));
}
} else {
- content.add(
- new SpanElement()..text = '...'
- );
+ content.add(new SpanElement()..text = '...');
}
- final button = new ButtonElement()..classes = ['retained_size']
+ final button = new ButtonElement()
+ ..classes = ['retained_size']
..disabled = _loadingRetainedBytes
..text = '↺';
button.onClick.listen((_) async {
- button.disabled = true;
- _loadingRetainedBytes = true;
- _retainedSize = await _retainedSizes.get(_isolate, _object.id);
- _r.dirty();
- });
+ button.disabled = true;
+ _loadingRetainedBytes = true;
+ _retainedSize = await _retainedSizes.get(_isolate, _object.id);
+ _r.dirty();
+ });
content.add(button);
return content;
}
diff --git a/runtime/observatory/lib/src/elements/object_view.dart b/runtime/observatory/lib/src/elements/object_view.dart
index 89efd2d..f8440ae 100644
--- a/runtime/observatory/lib/src/elements/object_view.dart
+++ b/runtime/observatory/lib/src/elements/object_view.dart
@@ -20,18 +20,18 @@
import 'package:observatory/src/elements/view_footer.dart';
class ObjectViewElement extends HtmlElement implements Renderable {
- static const tag = const Tag<ObjectViewElement>('object-view',
- dependencies: const [
- ContextRefElement.tag,
- CurlyBlockElement.tag,
- NavTopMenuElement.tag,
- NavVMMenuElement.tag,
- NavIsolateMenuElement.tag,
- NavRefreshElement.tag,
- NavNotifyElement.tag,
- ObjectCommonElement.tag,
- ViewFooterElement.tag
- ]);
+ static const tag =
+ const Tag<ObjectViewElement>('object-view', dependencies: const [
+ ContextRefElement.tag,
+ CurlyBlockElement.tag,
+ NavTopMenuElement.tag,
+ NavVMMenuElement.tag,
+ NavIsolateMenuElement.tag,
+ NavRefreshElement.tag,
+ NavNotifyElement.tag,
+ ObjectCommonElement.tag,
+ ViewFooterElement.tag
+ ]);
RenderingScheduler<ObjectViewElement> _r;
@@ -49,22 +49,24 @@
M.RetainingPathRepository _retainingPaths;
M.InstanceRepository _instances;
-
M.VMRef get vm => _vm;
M.IsolateRef get isolate => _isolate;
M.NotificationRepository get notifications => _notifications;
M.Context get object => _object;
- factory ObjectViewElement(M.VM vm, M.IsolateRef isolate, M.Object object,
- M.EventRepository events,
- M.NotificationRepository notifications,
- M.ObjectRepository objects,
- M.RetainedSizeRepository retainedSizes,
- M.ReachableSizeRepository reachableSizes,
- M.InboundReferencesRepository references,
- M.RetainingPathRepository retainingPaths,
- M.InstanceRepository instances,
- {RenderingQueue queue}) {
+ factory ObjectViewElement(
+ M.VM vm,
+ M.IsolateRef isolate,
+ M.Object object,
+ M.EventRepository events,
+ M.NotificationRepository notifications,
+ M.ObjectRepository objects,
+ M.RetainedSizeRepository retainedSizes,
+ M.ReachableSizeRepository reachableSizes,
+ M.InboundReferencesRepository references,
+ M.RetainingPathRepository retainingPaths,
+ M.InstanceRepository instances,
+ {RenderingQueue queue}) {
assert(vm != null);
assert(isolate != null);
assert(events != null);
@@ -115,20 +117,21 @@
new NavIsolateMenuElement(_isolate, _events, queue: _r.queue),
navMenu('object'),
new NavRefreshElement(queue: _r.queue)
- ..onRefresh.listen((e) async {
- e.element.disabled = true;
- _object = await _objects.get(_isolate, _object.id);
- _r.dirty();
- }),
+ ..onRefresh.listen((e) async {
+ e.element.disabled = true;
+ _object = await _objects.get(_isolate, _object.id);
+ _r.dirty();
+ }),
new NavNotifyElement(_notifications, queue: _r.queue)
]),
- new DivElement()..classes = ['content-centered-big']
+ new DivElement()
+ ..classes = ['content-centered-big']
..children = [
new HeadingElement.h2()..text = 'Object',
new HRElement(),
new ObjectCommonElement(_isolate, _object, _retainedSizes,
- _reachableSizes, _references, _retainingPaths,
- _instances, queue: _r.queue),
+ _reachableSizes, _references, _retainingPaths, _instances,
+ queue: _r.queue),
new HRElement(),
new ViewFooterElement(queue: _r.queue)
]
diff --git a/runtime/observatory/lib/src/elements/objectpool_ref.dart b/runtime/observatory/lib/src/elements/objectpool_ref.dart
index aad18b8..489581c 100644
--- a/runtime/observatory/lib/src/elements/objectpool_ref.dart
+++ b/runtime/observatory/lib/src/elements/objectpool_ref.dart
@@ -4,8 +4,7 @@
import 'dart:html';
import 'dart:async';
-import 'package:observatory/models.dart' as M
- show IsolateRef, ObjectPoolRef;
+import 'package:observatory/models.dart' as M show IsolateRef, ObjectPoolRef;
import 'package:observatory/src/elements/helpers/rendering_scheduler.dart';
import 'package:observatory/src/elements/helpers/tag.dart';
import 'package:observatory/src/elements/helpers/uris.dart';
@@ -53,7 +52,8 @@
children = [
new AnchorElement(href: Uris.inspect(_isolate, object: _pool))
..children = [
- new SpanElement()..classes = ['emphasize']
+ new SpanElement()
+ ..classes = ['emphasize']
..text = 'ObjectPool',
new SpanElement()..text = ' (${_pool.length})'
]
diff --git a/runtime/observatory/lib/src/elements/objectpool_view.dart b/runtime/observatory/lib/src/elements/objectpool_view.dart
index 890b5d1..43f649b 100644
--- a/runtime/observatory/lib/src/elements/objectpool_view.dart
+++ b/runtime/observatory/lib/src/elements/objectpool_view.dart
@@ -22,19 +22,19 @@
import 'package:observatory/src/elements/object_common.dart';
import 'package:observatory/src/elements/view_footer.dart';
-class ObjectPoolViewElement extends HtmlElement implements Renderable {
- static const tag = const Tag<ObjectPoolViewElement>('object-pool-view',
- dependencies: const [
- ContextRefElement.tag,
- CurlyBlockElement.tag,
- NavTopMenuElement.tag,
- NavVMMenuElement.tag,
- NavIsolateMenuElement.tag,
- NavRefreshElement.tag,
- NavNotifyElement.tag,
- ObjectCommonElement.tag,
- ViewFooterElement.tag
- ]);
+class ObjectPoolViewElement extends HtmlElement implements Renderable {
+ static const tag =
+ const Tag<ObjectPoolViewElement>('object-pool-view', dependencies: const [
+ ContextRefElement.tag,
+ CurlyBlockElement.tag,
+ NavTopMenuElement.tag,
+ NavVMMenuElement.tag,
+ NavIsolateMenuElement.tag,
+ NavRefreshElement.tag,
+ NavNotifyElement.tag,
+ ObjectCommonElement.tag,
+ ViewFooterElement.tag
+ ]);
RenderingScheduler<ObjectPoolViewElement> _r;
@@ -52,23 +52,24 @@
M.RetainingPathRepository _retainingPaths;
M.InstanceRepository _instances;
-
M.VMRef get vm => _vm;
M.IsolateRef get isolate => _isolate;
M.NotificationRepository get notifications => _notifications;
M.ObjectPoolRef get pool => _pool;
- factory ObjectPoolViewElement(M.VM vm, M.IsolateRef isolate,
- M.ObjectPool pool,
- M.EventRepository events,
- M.NotificationRepository notifications,
- M.ObjectPoolRepository pools,
- M.RetainedSizeRepository retainedSizes,
- M.ReachableSizeRepository reachableSizes,
- M.InboundReferencesRepository references,
- M.RetainingPathRepository retainingPaths,
- M.InstanceRepository instances,
- {RenderingQueue queue}) {
+ factory ObjectPoolViewElement(
+ M.VM vm,
+ M.IsolateRef isolate,
+ M.ObjectPool pool,
+ M.EventRepository events,
+ M.NotificationRepository notifications,
+ M.ObjectPoolRepository pools,
+ M.RetainedSizeRepository retainedSizes,
+ M.ReachableSizeRepository reachableSizes,
+ M.InboundReferencesRepository references,
+ M.RetainingPathRepository retainingPaths,
+ M.InstanceRepository instances,
+ {RenderingQueue queue}) {
assert(vm != null);
assert(isolate != null);
assert(events != null);
@@ -119,32 +120,37 @@
new NavIsolateMenuElement(_isolate, _events, queue: _r.queue),
navMenu('instance'),
new NavRefreshElement(queue: _r.queue)
- ..onRefresh.listen((e) async {
- e.element.disabled = true;
- _pool = await _pools.get(_isolate, _pool.id);
- _r.dirty();
- }),
+ ..onRefresh.listen((e) async {
+ e.element.disabled = true;
+ _pool = await _pools.get(_isolate, _pool.id);
+ _r.dirty();
+ }),
new NavNotifyElement(_notifications, queue: _r.queue)
]),
- new DivElement()..classes = ['content-centered-big']
+ new DivElement()
+ ..classes = ['content-centered-big']
..children = [
new HeadingElement.h2()..text = 'ObjectPool',
new HRElement(),
new ObjectCommonElement(_isolate, _pool, _retainedSizes,
- _reachableSizes, _references, _retainingPaths,
- _instances, queue: _r.queue),
+ _reachableSizes, _references, _retainingPaths, _instances,
+ queue: _r.queue),
new HRElement(),
new HeadingElement.h3()..text = 'entries (${_pool.entries.length})',
- new DivElement()..classes = ['memberList']
- ..children = _pool.entries.map((entry)
- => new DivElement()..classes = ['memberItem']
- ..children = [
- new DivElement()..classes = ['memberName',
- 'hexadecimal']
- ..text = '[PP+0x${entry.offset.toRadixString(16)}]',
- new DivElement()..classes = ['memberName']
- ..children = _createEntry(entry)
- ]).toList(),
+ new DivElement()
+ ..classes = ['memberList']
+ ..children = _pool.entries
+ .map((entry) => new DivElement()
+ ..classes = ['memberItem']
+ ..children = [
+ new DivElement()
+ ..classes = ['memberName', 'hexadecimal']
+ ..text = '[PP+0x${entry.offset.toRadixString(16)}]',
+ new DivElement()
+ ..classes = ['memberName']
+ ..children = _createEntry(entry)
+ ])
+ .toList(),
new HRElement(),
new ViewFooterElement(queue: _r.queue)
]
@@ -153,20 +159,18 @@
List<Element> _createEntry(M.ObjectPoolEntry entry) {
switch (entry.kind) {
- case M.ObjectPoolEntryKind.object:
- return [
- anyRef(_isolate, entry.asObject, _instances, queue: _r.queue)
- ];
- case M.ObjectPoolEntryKind.immediate:
- return [
- new SpanElement()
- ..text = 'Immediate 0x${entry.asInteger.toRadixString(16)}'
- ];
- case M.ObjectPoolEntryKind.nativeEntry:
- return [
- new SpanElement()
- ..text = 'NativeEntry 0x${entry.asInteger.toRadixString(16)}'
- ];
+ case M.ObjectPoolEntryKind.object:
+ return [anyRef(_isolate, entry.asObject, _instances, queue: _r.queue)];
+ case M.ObjectPoolEntryKind.immediate:
+ return [
+ new SpanElement()
+ ..text = 'Immediate 0x${entry.asInteger.toRadixString(16)}'
+ ];
+ case M.ObjectPoolEntryKind.nativeEntry:
+ return [
+ new SpanElement()
+ ..text = 'NativeEntry 0x${entry.asInteger.toRadixString(16)}'
+ ];
}
throw new Exception('Unkown ObjectPoolEntryKind (${entry.kind})');
}
diff --git a/runtime/observatory/lib/src/elements/objectstore_view.dart b/runtime/observatory/lib/src/elements/objectstore_view.dart
index d8d5597..3539411 100644
--- a/runtime/observatory/lib/src/elements/objectstore_view.dart
+++ b/runtime/observatory/lib/src/elements/objectstore_view.dart
@@ -19,17 +19,17 @@
import 'package:observatory/src/elements/nav/vm_menu.dart';
import 'package:observatory/src/elements/view_footer.dart';
-class ObjectStoreViewElement extends HtmlElement implements Renderable {
+class ObjectStoreViewElement extends HtmlElement implements Renderable {
static const tag = const Tag<ObjectStoreViewElement>('objectstore-view',
- dependencies: const [
- InstanceRefElement.tag,
- NavTopMenuElement.tag,
- NavVMMenuElement.tag,
- NavIsolateMenuElement.tag,
- NavRefreshElement.tag,
- NavNotifyElement.tag,
- ViewFooterElement.tag
- ]);
+ dependencies: const [
+ InstanceRefElement.tag,
+ NavTopMenuElement.tag,
+ NavVMMenuElement.tag,
+ NavIsolateMenuElement.tag,
+ NavRefreshElement.tag,
+ NavNotifyElement.tag,
+ ViewFooterElement.tag
+ ]);
RenderingScheduler<ObjectStoreViewElement> _r;
@@ -43,17 +43,18 @@
M.ObjectStoreRepository _stores;
M.InstanceRepository _instances;
-
M.VMRef get vm => _vm;
M.IsolateRef get isolate => _isolate;
M.NotificationRepository get notifications => _notifications;
- factory ObjectStoreViewElement(M.VM vm, M.IsolateRef isolate,
- M.EventRepository events,
- M.NotificationRepository notifications,
- M.ObjectStoreRepository stores,
- M.InstanceRepository instances,
- {RenderingQueue queue}) {
+ factory ObjectStoreViewElement(
+ M.VM vm,
+ M.IsolateRef isolate,
+ M.EventRepository events,
+ M.NotificationRepository notifications,
+ M.ObjectStoreRepository stores,
+ M.InstanceRepository instances,
+ {RenderingQueue queue}) {
assert(vm != null);
assert(isolate != null);
assert(events != null);
@@ -95,30 +96,36 @@
new NavVMMenuElement(_vm, _events, queue: _r.queue),
new NavIsolateMenuElement(_isolate, _events, queue: _r.queue),
new NavRefreshElement(disabled: _store == null, queue: _r.queue)
- ..onRefresh.listen((e) => _refresh()),
+ ..onRefresh.listen((e) => _refresh()),
new NavNotifyElement(_notifications, queue: _r.queue)
]),
- new DivElement()..classes = ['content-centered-big']
+ new DivElement()
+ ..classes = ['content-centered-big']
..children = [
new HeadingElement.h1()
..text = fields == null
- ? 'Object Store'
- : 'Object Store (${fields.length})',
+ ? 'Object Store'
+ : 'Object Store (${fields.length})',
new HRElement(),
fields == null
- ? (new HeadingElement.h2()..text = 'Loading...')
- : (new DivElement()..classes = ['memberList']
- ..children = fields.map((field) =>
- new DivElement()..classes = ['memberItem']
- ..children = [
- new DivElement()..classes = ['memberName']
- ..text = field.name,
- new DivElement()..classes = ['memberValue']
- ..children = [
- anyRef(_isolate, field.value, _instances,
+ ? (new HeadingElement.h2()..text = 'Loading...')
+ : (new DivElement()
+ ..classes = ['memberList']
+ ..children = fields
+ .map((field) => new DivElement()
+ ..classes = ['memberItem']
+ ..children = [
+ new DivElement()
+ ..classes = ['memberName']
+ ..text = field.name,
+ new DivElement()
+ ..classes = ['memberValue']
+ ..children = [
+ anyRef(_isolate, field.value, _instances,
queue: _r.queue)
- ]
- ]).toList()),
+ ]
+ ])
+ .toList()),
new ViewFooterElement(queue: _r.queue)
]
];
diff --git a/runtime/observatory/lib/src/elements/pc_descriptors_ref.dart b/runtime/observatory/lib/src/elements/pc_descriptors_ref.dart
index 8f724fa..838f1fa 100644
--- a/runtime/observatory/lib/src/elements/pc_descriptors_ref.dart
+++ b/runtime/observatory/lib/src/elements/pc_descriptors_ref.dart
@@ -4,8 +4,7 @@
import 'dart:html';
import 'dart:async';
-import 'package:observatory/models.dart' as M
- show IsolateRef, PcDescriptorsRef;
+import 'package:observatory/models.dart' as M show IsolateRef, PcDescriptorsRef;
import 'package:observatory/src/elements/helpers/rendering_scheduler.dart';
import 'package:observatory/src/elements/helpers/tag.dart';
import 'package:observatory/src/elements/helpers/uris.dart';
@@ -16,7 +15,7 @@
RenderingScheduler<PcDescriptorsRefElement> _r;
Stream<RenderedEvent<PcDescriptorsRefElement>> get onRendered =>
- _r.onRendered;
+ _r.onRendered;
M.IsolateRef _isolate;
M.PcDescriptorsRef _descriptors;
@@ -24,8 +23,9 @@
M.IsolateRef get isolate => _isolate;
M.PcDescriptorsRef get descriptors => _descriptors;
- factory PcDescriptorsRefElement(M.IsolateRef isolate,
- M.PcDescriptorsRef descriptors, {RenderingQueue queue}) {
+ factory PcDescriptorsRefElement(
+ M.IsolateRef isolate, M.PcDescriptorsRef descriptors,
+ {RenderingQueue queue}) {
assert(isolate != null);
assert(descriptors != null);
PcDescriptorsRefElement e = document.createElement(tag.name);
@@ -52,8 +52,8 @@
void render() {
final text = (_descriptors.name == null || _descriptors.name == '')
- ? 'PcDescriptors'
- : _descriptors.name;
+ ? 'PcDescriptors'
+ : _descriptors.name;
children = [
new AnchorElement(href: Uris.inspect(_isolate, object: _descriptors))
..text = text
diff --git a/runtime/observatory/lib/src/elements/persistent_handles.dart b/runtime/observatory/lib/src/elements/persistent_handles.dart
index f8b56dc..f925fb7 100644
--- a/runtime/observatory/lib/src/elements/persistent_handles.dart
+++ b/runtime/observatory/lib/src/elements/persistent_handles.dart
@@ -21,29 +21,22 @@
import 'package:observatory/src/elements/nav/vm_menu.dart';
import 'package:observatory/utils.dart';
-enum _SortingField {
- externalSize,
- peer,
- finalizerCallback
-}
+enum _SortingField { externalSize, peer, finalizerCallback }
-enum _SortingDirection {
- ascending,
- descending
-}
+enum _SortingDirection { ascending, descending }
-class PersistentHandlesPageElement extends HtmlElement implements Renderable {
- static const tag =
- const Tag<PersistentHandlesPageElement>('persistent-handles-page',
- dependencies: const [
- InstanceRefElement.tag,
- NavTopMenuElement.tag,
- NavVMMenuElement.tag,
- NavIsolateMenuElement.tag,
- NavRefreshElement.tag,
- NavNotifyElement.tag,
- VirtualCollectionElement.tag
- ]);
+class PersistentHandlesPageElement extends HtmlElement implements Renderable {
+ static const tag = const Tag<PersistentHandlesPageElement>(
+ 'persistent-handles-page',
+ dependencies: const [
+ InstanceRefElement.tag,
+ NavTopMenuElement.tag,
+ NavVMMenuElement.tag,
+ NavIsolateMenuElement.tag,
+ NavRefreshElement.tag,
+ NavNotifyElement.tag,
+ VirtualCollectionElement.tag
+ ]);
RenderingScheduler<PersistentHandlesPageElement> _r;
@@ -57,21 +50,21 @@
M.PersistentHandlesRepository _repository;
M.InstanceRepository _instances;
M.PersistentHandles _handles;
- _SortingField _sortingField =
- _SortingField.externalSize;
- _SortingDirection _sortingDirection =
- _SortingDirection.descending;
+ _SortingField _sortingField = _SortingField.externalSize;
+ _SortingDirection _sortingDirection = _SortingDirection.descending;
M.VMRef get vm => _vm;
M.IsolateRef get isolate => _isolate;
M.NotificationRepository get notifications => _notifications;
- factory PersistentHandlesPageElement(M.VM vm, M.IsolateRef isolate,
- M.EventRepository events,
- M.NotificationRepository notifications,
- M.PersistentHandlesRepository repository,
- M.InstanceRepository instances,
- {RenderingQueue queue}) {
+ factory PersistentHandlesPageElement(
+ M.VM vm,
+ M.IsolateRef isolate,
+ M.EventRepository events,
+ M.NotificationRepository notifications,
+ M.PersistentHandlesRepository repository,
+ M.InstanceRepository instances,
+ {RenderingQueue queue}) {
assert(vm != null);
assert(isolate != null);
assert(events != null);
@@ -116,39 +109,39 @@
..onRefresh.listen((_) => _refresh()),
new NavNotifyElement(_notifications, queue: _r.queue)
])
- ]..addAll(_createHandlers('Persistent Handles',
- _handles?.elements?.toList(),
- _createLine,
- _updateLine))
- ..add(new BRElement())
- ..addAll(_createHandlers('Weak Persistent Handles',
- _handles == null
- ? null
- : (_handles.weakElements.toList()
- ..sort(_createSorter())),
- _createWeakLine,
- _updateWeakLine,
- createHeader: _createWeakHeader));
+ ]
+ ..addAll(_createHandlers('Persistent Handles',
+ _handles?.elements?.toList(), _createLine, _updateLine))
+ ..add(new BRElement())
+ ..addAll(_createHandlers(
+ 'Weak Persistent Handles',
+ _handles == null
+ ? null
+ : (_handles.weakElements.toList()..sort(_createSorter())),
+ _createWeakLine,
+ _updateWeakLine,
+ createHeader: _createWeakHeader));
}
List<Element> _createHandlers(String name, List items, create, update,
- {createHeader}) {
+ {createHeader}) {
return [
- new DivElement()..classes = ['content-centered-big']
+ new DivElement()
+ ..classes = ['content-centered-big']
..children = [
new HeadingElement.h1()
- ..text = items == null ? '$name'
- : '$name (${items.length})',
+ ..text = items == null ? '$name' : '$name (${items.length})',
new HRElement(),
],
- new DivElement()..classes = ['persistent-handles']
+ new DivElement()
+ ..classes = ['persistent-handles']
..children = [
items == null
- ? (new HeadingElement.h2()..classes = ['content-centered-big']
+ ? (new HeadingElement.h2()
+ ..classes = ['content-centered-big']
..text = 'Loading...')
- : new VirtualCollectionElement(create, update, items: items,
- createHeader: createHeader,
- queue: _r.queue)
+ : new VirtualCollectionElement(create, update,
+ items: items, createHeader: createHeader, queue: _r.queue)
]
];
}
@@ -174,53 +167,51 @@
}
}
- static Element _createLine() =>
- new DivElement()..classes = ['collection-item']
- ..text = 'object';
+ static Element _createLine() => new DivElement()
+ ..classes = ['collection-item']
+ ..text = 'object';
- static Element _createWeakLine() =>
- new DivElement()
- ..classes = ['weak-item']
- ..children = [
- new SpanElement()..classes = ['external-size']
- ..text = '0B',
- new SpanElement()..classes = ['peer']
- ..text = '0x00000',
- new SpanElement()..classes = ['object'],
- new SpanElement()..classes = ['finalizer']
- ..text = 'dart::Class::Method()'
- ];
+ static Element _createWeakLine() => new DivElement()
+ ..classes = ['weak-item']
+ ..children = [
+ new SpanElement()
+ ..classes = ['external-size']
+ ..text = '0B',
+ new SpanElement()
+ ..classes = ['peer']
+ ..text = '0x00000',
+ new SpanElement()..classes = ['object'],
+ new SpanElement()
+ ..classes = ['finalizer']
+ ..text = 'dart::Class::Method()'
+ ];
- Element _createWeakHeader() =>
- new DivElement()
- ..classes = ['weak-item']
- ..children = [
- _createHeaderButton(const ['external-size'], 'External Size',
- _SortingField.externalSize,
- _SortingDirection.descending),
- _createHeaderButton(const ['peer'], 'Peer',
- _SortingField.peer,
- _SortingDirection.descending),
- new SpanElement()..classes = ['object']
- ..text = 'Object',
- _createHeaderButton(const ['finalizer'], 'Finalizer Callback',
- _SortingField.finalizerCallback,
- _SortingDirection.ascending)
- ];
+ Element _createWeakHeader() => new DivElement()
+ ..classes = ['weak-item']
+ ..children = [
+ _createHeaderButton(const ['external-size'], 'External Size',
+ _SortingField.externalSize, _SortingDirection.descending),
+ _createHeaderButton(const ['peer'], 'Peer', _SortingField.peer,
+ _SortingDirection.descending),
+ new SpanElement()
+ ..classes = ['object']
+ ..text = 'Object',
+ _createHeaderButton(const ['finalizer'], 'Finalizer Callback',
+ _SortingField.finalizerCallback, _SortingDirection.ascending)
+ ];
- ButtonElement _createHeaderButton(List<String> classes,
- String text,
- _SortingField field,
- _SortingDirection direction) =>
- new ButtonElement()..classes = classes
- ..text = _sortingField != field ? text :
- _sortingDirection == _SortingDirection.ascending
- ? '$text▼' : '$text▲'
- ..onClick.listen((_) => _setSorting(field, direction));
+ ButtonElement _createHeaderButton(List<String> classes, String text,
+ _SortingField field, _SortingDirection direction) =>
+ new ButtonElement()
+ ..classes = classes
+ ..text = _sortingField != field
+ ? text
+ : _sortingDirection == _SortingDirection.ascending
+ ? '$text▼'
+ : '$text▲'
+ ..onClick.listen((_) => _setSorting(field, direction));
-
- void _setSorting(_SortingField field,
- _SortingDirection defaultDirection) {
+ void _setSorting(_SortingField field, _SortingDirection defaultDirection) {
if (_sortingField == field) {
switch (_sortingDirection) {
case _SortingDirection.descending:
@@ -237,21 +228,20 @@
_r.dirty();
}
- void _updateWeakLine(Element e, M.WeakPersistentHandle item,
- index) {
+ void _updateWeakLine(Element e, M.WeakPersistentHandle item, index) {
e.children[0].text = Utils.formatSize(_getExternalSize(item));
e.children[1].text = '${_getPeer(item)}';
e.children[2] = anyRef(_isolate, item.object, _instances, queue: _r.queue)
..classes = ['object'];
- e.children[3]..text = '${_getFinalizerCallback(item)}'
- ..title = '${_getFinalizerCallback(item)}';
+ e.children[3]
+ ..text = '${_getFinalizerCallback(item)}'
+ ..title = '${_getFinalizerCallback(item)}';
}
- void _updateLine(Element e, M.PersistentHandle item,
- index) {
+ void _updateLine(Element e, M.PersistentHandle item, index) {
e.children = [
anyRef(_isolate, item.object, _instances, queue: _r.queue)
- ..classes = ['object']
+ ..classes = ['object']
];
}
diff --git a/runtime/observatory/lib/src/elements/ports.dart b/runtime/observatory/lib/src/elements/ports.dart
index c71b285..793de37 100644
--- a/runtime/observatory/lib/src/elements/ports.dart
+++ b/runtime/observatory/lib/src/elements/ports.dart
@@ -19,16 +19,15 @@
import 'package:observatory/src/elements/view_footer.dart';
class PortsElement extends HtmlElement implements Renderable {
- static const tag = const Tag<PortsElement>('ports-page',
- dependencies: const [
- NavTopMenuElement.tag,
- NavVMMenuElement.tag,
- NavIsolateMenuElement.tag,
- NavRefreshElement.tag,
- NavNotifyElement.tag,
- InstanceRefElement.tag,
- ViewFooterElement.tag
- ]);
+ static const tag = const Tag<PortsElement>('ports-page', dependencies: const [
+ NavTopMenuElement.tag,
+ NavVMMenuElement.tag,
+ NavIsolateMenuElement.tag,
+ NavRefreshElement.tag,
+ NavNotifyElement.tag,
+ InstanceRefElement.tag,
+ ViewFooterElement.tag
+ ]);
RenderingScheduler<PortsElement> _r;
@@ -42,18 +41,19 @@
M.InstanceRepository _instances;
M.Ports _isolatePorts;
-
M.IsolateRef get isolate => _isolate;
M.NotificationRepository get notifications => _notifications;
M.PortsRepository get ports => _ports;
M.VMRef get vm => _vm;
- factory PortsElement(M.VM vm, M.IsolateRef isolate,
- M.EventRepository events,
- M.NotificationRepository notifications,
- M.PortsRepository ports,
- M.InstanceRepository instances,
- {RenderingQueue queue}) {
+ factory PortsElement(
+ M.VM vm,
+ M.IsolateRef isolate,
+ M.EventRepository events,
+ M.NotificationRepository notifications,
+ M.PortsRepository ports,
+ M.InstanceRepository instances,
+ {RenderingQueue queue}) {
assert(vm != null);
assert(isolate != null);
assert(events != null);
@@ -102,9 +102,9 @@
..classes = ['content-centered']
..children = [
new HeadingElement.h1()..text = 'Ports',
- new BRElement(), new HRElement(),
- new DivElement()
- ..children = _createList(),
+ new BRElement(),
+ new HRElement(),
+ new DivElement()..children = _createList(),
new HRElement()
],
new ViewFooterElement(queue: _r.queue)
@@ -116,21 +116,25 @@
return const [];
}
int i = 0;
- return _isolatePorts.elements.map((port) =>
- new DivElement()..classes = ['memberItem']
- ..children = [
- new DivElement()..classes = ['memberName']
- ..children = [
- new SpanElement()..classes = ['port-number']
- ..text = '[ ${++i} ] ',
- new SpanElement()..text = '${port.name}'
- ],
- new DivElement()..classes = ['memberValue']
- ..children = [
- anyRef(_isolate, port.handler, _instances, queue: _r.queue)
- ]
- ]
- ).toList();
+ return _isolatePorts.elements
+ .map((port) => new DivElement()
+ ..classes = ['memberItem']
+ ..children = [
+ new DivElement()
+ ..classes = ['memberName']
+ ..children = [
+ new SpanElement()
+ ..classes = ['port-number']
+ ..text = '[ ${++i} ] ',
+ new SpanElement()..text = '${port.name}'
+ ],
+ new DivElement()
+ ..classes = ['memberValue']
+ ..children = [
+ anyRef(_isolate, port.handler, _instances, queue: _r.queue)
+ ]
+ ])
+ .toList();
}
Future _refresh() async {
diff --git a/runtime/observatory/lib/src/elements/retaining_path.dart b/runtime/observatory/lib/src/elements/retaining_path.dart
index 2fea22c..547b573 100644
--- a/runtime/observatory/lib/src/elements/retaining_path.dart
+++ b/runtime/observatory/lib/src/elements/retaining_path.dart
@@ -13,15 +13,11 @@
class RetainingPathElement extends HtmlElement implements Renderable {
static const tag = const Tag<RetainingPathElement>('retaining-path',
- dependencies: const [
- CurlyBlockElement.tag,
- InstanceRefElement.tag
- ]);
+ dependencies: const [CurlyBlockElement.tag, InstanceRefElement.tag]);
RenderingScheduler<RetainingPathElement> _r;
- Stream<RenderedEvent<RetainingPathElement>> get onRendered =>
- _r.onRendered;
+ Stream<RenderedEvent<RetainingPathElement>> get onRendered => _r.onRendered;
M.IsolateRef _isolate;
M.ObjectRef _object;
@@ -87,9 +83,7 @@
List<Element> _createContent() {
if (_path == null) {
- return [
- new SpanElement()..text = 'Loading'
- ];
+ return [new SpanElement()..text = 'Loading'];
}
return _path.elements.map(_createItem).toList();
}
@@ -98,30 +92,26 @@
final content = <Element>[];
if (item.parentField != null) {
- content.add(
- new SpanElement()
- ..children = [
- new SpanElement()..text = 'from ',
- anyRef(_isolate, item.parentField, _instances, queue: _r.queue),
- new SpanElement()..text = ' of ',
- ]);
+ content.add(new SpanElement()
+ ..children = [
+ new SpanElement()..text = 'from ',
+ anyRef(_isolate, item.parentField, _instances, queue: _r.queue),
+ new SpanElement()..text = ' of ',
+ ]);
} else if (item.parentListIndex != null) {
content.add(
- new SpanElement()
- ..text = 'from [ ${item.parentListIndex} ] of ');
+ new SpanElement()..text = 'from [ ${item.parentListIndex} ] of ');
} else if (item.parentWordOffset != null) {
- content.add(
- new SpanElement()
- ..text = 'from word [ ${item.parentWordOffset} ] of ');
+ content.add(new SpanElement()
+ ..text = 'from word [ ${item.parentWordOffset} ] of ');
} else {
content.add(new SpanElement()..text = 'from ');
}
- content.add(
- anyRef(_isolate, item.source, _instances, queue: _r.queue)
- );
+ content.add(anyRef(_isolate, item.source, _instances, queue: _r.queue));
- return new DivElement()..classes = ['indent']
- ..children = content;
+ return new DivElement()
+ ..classes = ['indent']
+ ..children = content;
}
}
diff --git a/runtime/observatory/lib/src/elements/sample_buffer_control.dart b/runtime/observatory/lib/src/elements/sample_buffer_control.dart
index dde5eb8..ecc7284 100644
--- a/runtime/observatory/lib/src/elements/sample_buffer_control.dart
+++ b/runtime/observatory/lib/src/elements/sample_buffer_control.dart
@@ -22,7 +22,7 @@
RenderingScheduler<SampleBufferControlElement> _r;
Stream<RenderedEvent<SampleBufferControlElement>> get onRendered =>
- _r.onRendered;
+ _r.onRendered;
StreamController<SampleBufferControlChangedElement> _onTagChange =
new StreamController<SampleBufferControlChangedElement>.broadcast();
@@ -46,11 +46,11 @@
set showTag(bool value) => _showTag = _r.checkAndReact(_showTag, value);
set profileVM(bool value) => _profileVM = _r.checkAndReact(_profileVM, value);
-
factory SampleBufferControlElement(M.SampleProfileLoadingProgress progress,
Stream<M.SampleProfileLoadingProgressEvent> progressStream,
{M.SampleProfileTag selectedTag: M.SampleProfileTag.none,
- bool showTag: true, RenderingQueue queue}) {
+ bool showTag: true,
+ RenderingQueue queue}) {
assert(progress != null);
assert(progressStream != null);
assert(selectedTag != null);
@@ -78,7 +78,8 @@
@override
void detached() {
- super.detached(); _r.disable(notify: true);
+ super.detached();
+ _r.disable(notify: true);
children = const [];
_subscription.cancel();
}
@@ -89,14 +90,14 @@
new HRElement()
];
switch (_progress.status) {
- case M.SampleProfileLoadingStatus.fetching :
+ case M.SampleProfileLoadingStatus.fetching:
content.addAll(_createStatusMessage('Fetching profile from VM...'));
break;
- case M.SampleProfileLoadingStatus.loading :
+ case M.SampleProfileLoadingStatus.loading:
content.addAll(_createStatusMessage('Loading profile...',
progress: _progress.progress));
break;
- case M.SampleProfileLoadingStatus.disabled :
+ case M.SampleProfileLoadingStatus.disabled:
content.addAll(_createDisabledMessage());
break;
case M.SampleProfileLoadingStatus.loaded:
@@ -104,41 +105,47 @@
break;
}
children = [
- new DivElement()..classes = ['content-centered-big']
+ new DivElement()
+ ..classes = ['content-centered-big']
..children = content
];
}
static List<Element> _createStatusMessage(String message,
{double progress: 0.0}) {
- return [new DivElement()..classes = ['statusBox', 'shadow', 'center']
- ..children = [
- new DivElement()..classes = ['statusMessage']
- ..text = message,
- new DivElement()..style.background = '#0489c3'
- ..style.width = '$progress%'
- ..style.height = '15px'
- ..style.borderRadius = '4px'
- ]
+ return [
+ new DivElement()
+ ..classes = ['statusBox', 'shadow', 'center']
+ ..children = [
+ new DivElement()
+ ..classes = ['statusMessage']
+ ..text = message,
+ new DivElement()
+ ..style.background = '#0489c3'
+ ..style.width = '$progress%'
+ ..style.height = '15px'
+ ..style.borderRadius = '4px'
+ ]
];
}
static List<Element> _createDisabledMessage() {
- return [new DivElement()..classes = ['statusBox' 'shadow' 'center']
- ..children = [
- new DivElement()
- ..children = [
- new HeadingElement.h1()
- ..text = 'Profiling is disabled',
- new BRElement(),
- new DivElement()
- ..innerHtml = 'Perhaps the <b>profile</b> '
- 'flag has been disabled for this VM.',
- new BRElement(),
- new SpanElement()..text = 'See all',
- new AnchorElement(href: Uris.flags())..text = 'vm flags'
- ]
- ]
+ return [
+ new DivElement()
+ ..classes = ['statusBox' 'shadow' 'center']
+ ..children = [
+ new DivElement()
+ ..children = [
+ new HeadingElement.h1()..text = 'Profiling is disabled',
+ new BRElement(),
+ new DivElement()
+ ..innerHtml = 'Perhaps the <b>profile</b> '
+ 'flag has been disabled for this VM.',
+ new BRElement(),
+ new SpanElement()..text = 'See all',
+ new AnchorElement(href: Uris.flags())..text = 'vm flags'
+ ]
+ ]
];
}
@@ -149,45 +156,57 @@
final refreshT = new DateTime.now();
final stackDepth = _progress.profile.stackDepth;
final sampleRate = _progress.profile.sampleRate.toStringAsFixed(0);
- final timeSpan = _progress.profile.sampleCount == 0 ? '0s'
+ final timeSpan = _progress.profile.sampleCount == 0
+ ? '0s'
: Utils.formatTimePrecise(_progress.profile.timeSpan);
var content = <Element>[
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'Refreshed at',
- new DivElement()..classes = ['memberValue']
+ new DivElement()
+ ..classes = ['memberValue']
..text = '$refreshT (fetched in ${fetchT}s) (loaded in ${loadT}s)'
],
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'Profile contains ',
- new DivElement()..classes = ['memberValue']
+ new DivElement()
+ ..classes = ['memberValue']
..text = '$sampleCount samples (spanning $timeSpan)'
],
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'Sampling',
- new DivElement()..classes = ['memberValue']
+ new DivElement()
+ ..classes = ['memberValue']
..text = '$stackDepth stack frames @ ${sampleRate}Hz'
],
];
if (_showTag) {
- content.add(
- new DivElement()..classes = ['memberItem']
- ..children = [
- new DivElement()..classes = ['memberName']
- ..text = 'Tag Order',
- new DivElement()..classes = ['memberValue']
- ..children = _createTagSelect()
- ]
- );
+ content.add(new DivElement()
+ ..classes = ['memberItem']
+ ..children = [
+ new DivElement()
+ ..classes = ['memberName']
+ ..text = 'Tag Order',
+ new DivElement()
+ ..classes = ['memberValue']
+ ..children = _createTagSelect()
+ ]);
}
return [
- new DivElement()..classes = ['memberList']
+ new DivElement()
+ ..classes = ['memberList']
..children = content
];
}
@@ -199,27 +218,33 @@
}
var s;
return [
- s = new SelectElement()..classes = ['tag-select']
+ s = new SelectElement()
+ ..classes = ['tag-select']
..value = tagToString(_tag)
..children = values.map((tag) {
- return new OptionElement(value : tagToString(tag),
- selected: _tag == tag)
- ..text = tagToString(tag);
- }).toList(growable: false)
+ return new OptionElement(
+ value: tagToString(tag),
+ selected: _tag == tag)..text = tagToString(tag);
+ }).toList(growable: false)
..onChange.listen((_) {
- _tag = values[s.selectedIndex];
- })
+ _tag = values[s.selectedIndex];
+ })
..onChange.map(_toEvent).listen(_triggerModeChange),
];
}
static String tagToString(M.SampleProfileTag tag) {
switch (tag) {
- case M.SampleProfileTag.userVM: return 'User > VM';
- case M.SampleProfileTag.userOnly: return 'User';
- case M.SampleProfileTag.vmUser: return 'VM > User';
- case M.SampleProfileTag.vmOnly: return 'VM';
- case M.SampleProfileTag.none: return 'None';
+ case M.SampleProfileTag.userVM:
+ return 'User > VM';
+ case M.SampleProfileTag.userOnly:
+ return 'User';
+ case M.SampleProfileTag.vmUser:
+ return 'VM > User';
+ case M.SampleProfileTag.vmOnly:
+ return 'VM';
+ case M.SampleProfileTag.none:
+ return 'None';
}
throw new Exception('Unknown tagToString');
}
diff --git a/runtime/observatory/lib/src/elements/script_inset.dart b/runtime/observatory/lib/src/elements/script_inset.dart
index a4beb89..69a64ea 100644
--- a/runtime/observatory/lib/src/elements/script_inset.dart
+++ b/runtime/observatory/lib/src/elements/script_inset.dart
@@ -23,7 +23,6 @@
Stream<RenderedEvent<ScriptInsetElement>> get onRendered => _r.onRendered;
-
M.IsolateRef _isolate;
M.ScriptRef _script;
M.Script _loadedScript;
@@ -40,14 +39,18 @@
M.IsolateRef get isolate => _isolate;
M.ScriptRef get script => _script;
- factory ScriptInsetElement(M.IsolateRef isolate, M.ScriptRef script,
- M.ScriptRepository scripts,
- M.InstanceRepository instances,
- M.EventRepository events,
- {int startPos, int endPos, int currentPos,
- bool inDebuggerContext: false,
- Iterable variables: const [],
- RenderingQueue queue}) {
+ factory ScriptInsetElement(
+ M.IsolateRef isolate,
+ M.ScriptRef script,
+ M.ScriptRepository scripts,
+ M.InstanceRepository instances,
+ M.EventRepository events,
+ {int startPos,
+ int endPos,
+ int currentPos,
+ bool inDebuggerContext: false,
+ Iterable variables: const [],
+ RenderingQueue queue}) {
assert(isolate != null);
assert(script != null);
assert(scripts != null);
@@ -72,31 +75,34 @@
ScriptInsetElement.created() : super.created();
+ bool get noSource => _startPos == -1;
+
@override
void attached() {
super.attached();
_r.enable();
_subscription = _events.onDebugEvent
- .where((e) => (e is M.BreakpointAddedEvent) ||
- (e is M.BreakpointResolvedEvent) ||
- (e is M.BreakpointRemovedEvent))
- .map((e) => e.breakpoint)
- .listen((M.Breakpoint b) {
- final loc = b.location;
- int line;
- if (loc.script.id == script.id) {
- if (loc.tokenPos != null) {
- line = _loadedScript.tokenToLine(loc.tokenPos);
- } else {
- line = loc.line;
- }
- } else {
- line = loc.line;
- }
- if ((line == null) || ((line >= _startLine) && (line <= _endLine))) {
- _r.dirty();
- }
- });
+ .where((e) =>
+ (e is M.BreakpointAddedEvent) ||
+ (e is M.BreakpointResolvedEvent) ||
+ (e is M.BreakpointRemovedEvent))
+ .map((e) => e.breakpoint)
+ .listen((M.Breakpoint b) {
+ final loc = b.location;
+ int line;
+ if (loc.script.id == script.id) {
+ if (loc.tokenPos != null) {
+ line = _loadedScript.tokenToLine(loc.tokenPos);
+ } else {
+ line = loc.line;
+ }
+ } else {
+ line = loc.line;
+ }
+ if ((line == null) || ((line >= _startLine) && (line <= _endLine))) {
+ _r.dirty();
+ }
+ });
_refresh();
}
@@ -109,7 +115,9 @@
}
void render() {
- if (_loadedScript == null) {
+ if (noSource) {
+ children = [new SpanElement()..text = 'No source'];
+ } else if (_loadedScript == null) {
children = [new SpanElement()..text = 'Loading...'];
} else {
final table = linesTable();
@@ -174,26 +182,31 @@
element.title = "";
return element;
}
+
Element hitsUnknown(Element element) {
element.classes.add('hitsNone');
element.title = "";
return element;
}
+
Element hitsNotExecuted(Element element) {
element.classes.add('hitsNotExecuted');
element.title = "Line did not execute";
return element;
}
+
Element hitsExecuted(Element element) {
element.classes.add('hitsExecuted');
element.title = "Line did execute";
return element;
}
+
Element hitsCompiled(Element element) {
element.classes.add('hitsCompiled');
element.title = "Line in compiled function";
return element;
}
+
Element hitsNotCompiled(Element element) {
element.classes.add('hitsNotCompiled');
element.title = "Line in uncompiled function";
@@ -204,17 +217,20 @@
// Build _rangeMap and _callSites from a source report.
Future _refreshSourceReport() async {
- var reports = [S.Isolate.kCallSitesReport,
- S.Isolate.kPossibleBreakpointsReport];
+ if (noSource) return;
+
+ var reports = [
+ S.Isolate.kCallSitesReport,
+ S.Isolate.kPossibleBreakpointsReport
+ ];
if (_includeProfile) {
reports.add(S.Isolate.kProfileReport);
}
S.Isolate isolate = _isolate as S.Isolate;
- var sourceReport = await isolate.getSourceReport(
- reports,
- script, _startPos, _endPos);
- _possibleBreakpointLines = S.getPossibleBreakpointLines(sourceReport,
- script);
+ var sourceReport =
+ await isolate.getSourceReport(reports, script, _startPos, _endPos);
+ _possibleBreakpointLines =
+ S.getPossibleBreakpointLines(sourceReport, script);
_rangeMap.clear();
_callSites.clear();
_profileMap.clear();
@@ -267,23 +283,21 @@
Future _computeAnnotations() async {
_startLine = (_startPos != null
- ? _loadedScript.tokenToLine(_startPos)
- : 1 + _loadedScript.lineOffset);
- _currentLine = (_currentPos != null
- ? _loadedScript.tokenToLine(_currentPos)
- : null);
- _currentCol = (_currentPos != null
- ? (_loadedScript.tokenToCol(_currentPos))
- : null);
+ ? _loadedScript.tokenToLine(_startPos)
+ : 1 + _loadedScript.lineOffset);
+ _currentLine =
+ (_currentPos != null ? _loadedScript.tokenToLine(_currentPos) : null);
+ _currentCol =
+ (_currentPos != null ? (_loadedScript.tokenToCol(_currentPos)) : null);
if (_currentCol != null) {
- _currentCol--; // make this 0-based.
+ _currentCol--; // make this 0-based.
}
S.Script script = _loadedScript as S.Script;
_endLine = (_endPos != null
- ? _loadedScript.tokenToLine(_endPos)
- : script.lines.length + _loadedScript.lineOffset);
+ ? _loadedScript.tokenToLine(_endPos)
+ : script.lines.length + _loadedScript.lineOffset);
if (_startLine == null || _endLine == null) {
return;
@@ -332,8 +346,8 @@
if (bpts != null) {
for (var bpt in bpts) {
if (bpt.location != null) {
- _annotations.add(new BreakpointAnnotation(_isolate, _instances,
- _r.queue, bpt));
+ _annotations.add(
+ new BreakpointAnnotation(_isolate, _instances, _r.queue, bpt));
}
}
}
@@ -376,9 +390,12 @@
var pattern = new RegExp("library ${script.library.name}");
var match = pattern.firstMatch(line.text);
if (match != null) {
- var anno = new LibraryAnnotation(_isolate, _instances, _r.queue,
- _loadedScript.library,
- Uris.inspect(isolate, object: _loadedScript.library));
+ var anno = new LibraryAnnotation(
+ _isolate,
+ _instances,
+ _r.queue,
+ _loadedScript.library,
+ Uris.inspect(isolate, object: _loadedScript.library));
anno.line = line.line;
anno.columnStart = match.start + 8;
anno.columnStop = match.end;
@@ -388,9 +405,12 @@
pattern = new RegExp("part of ${script.library.name}");
match = pattern.firstMatch(line.text);
if (match != null) {
- var anno = new LibraryAnnotation(_isolate, _instances, _r.queue,
- _loadedScript.library,
- Uris.inspect(isolate, object: _loadedScript.library));
+ var anno = new LibraryAnnotation(
+ _isolate,
+ _instances,
+ _r.queue,
+ _loadedScript.library,
+ Uris.inspect(isolate, object: _loadedScript.library));
anno.line = line.line;
anno.columnStart = match.start + 8;
anno.columnStop = match.end;
@@ -439,7 +459,7 @@
M.Library target = resolveDependency(match[1]);
if (target != null) {
var anno = new LibraryAnnotation(_isolate, _instances, _r.queue,
- target, Uris.inspect(isolate, object: target));
+ target, Uris.inspect(isolate, object: target));
anno.line = line.line;
anno.columnStart = match.start + 8;
anno.columnStop = match.end - 1;
@@ -481,7 +501,7 @@
S.Script part = resolvePart(match[1]);
if (part != null) {
var anno = new PartAnnotation(_isolate, _instances, _r.queue, part,
- Uris.inspect(isolate, object: part));
+ Uris.inspect(isolate, object: part));
anno.line = line.line;
anno.columnStart = match.start + 6;
anno.columnStop = match.end - 1;
@@ -497,7 +517,7 @@
for (var cls in script.library.classes) {
if ((cls.location != null) && (cls.location.script == script)) {
var a = new ClassDeclarationAnnotation(_isolate, _instances, _r.queue,
- cls, Uris.inspect(isolate, object: cls));
+ cls, Uris.inspect(isolate, object: cls));
_annotations.add(a);
}
}
@@ -508,7 +528,7 @@
for (var field in script.library.variables) {
if ((field.location != null) && (field.location.script == script)) {
var a = new FieldDeclarationAnnotation(_isolate, _instances, _r.queue,
- field, Uris.inspect(isolate, object: field));
+ field, Uris.inspect(isolate, object: field));
_annotations.add(a);
}
}
@@ -516,7 +536,7 @@
for (var field in cls.fields) {
if ((field.location != null) && (field.location.script == script)) {
var a = new FieldDeclarationAnnotation(_isolate, _instances, _r.queue,
- field, Uris.inspect(isolate, object: field));
+ field, Uris.inspect(isolate, object: field));
_annotations.add(a);
}
}
@@ -533,7 +553,7 @@
// We annotate a field declaration with the field instead of the
// implicit getter or setter.
var a = new FunctionDeclarationAnnotation(_isolate, _instances,
- _r.queue, func, Uris.inspect(isolate, object: func));
+ _r.queue, func, Uris.inspect(isolate, object: func));
_annotations.add(a);
}
}
@@ -547,7 +567,7 @@
// We annotate a field declaration with the field instead of the
// implicit getter or setter.
var a = new FunctionDeclarationAnnotation(_isolate, _instances,
- _r.queue, func, Uris.inspect(isolate, object: func));
+ _r.queue, func, Uris.inspect(isolate, object: func));
_annotations.add(a);
}
}
@@ -556,8 +576,8 @@
void addCallSiteAnnotations() {
for (var callSite in _callSites) {
- _annotations.add(new CallSiteAnnotation(_isolate, _instances, _r.queue,
- callSite));
+ _annotations.add(
+ new CallSiteAnnotation(_isolate, _instances, _r.queue, callSite));
}
}
@@ -569,15 +589,12 @@
for (var variable in _variables) {
// Find variable usage locations.
var locations = script.scanForLocalVariableLocations(
- variable['name'],
- variable['_tokenPos'],
- variable['_endTokenPos']);
+ variable['name'], variable['_tokenPos'], variable['_endTokenPos']);
// Annotate locations.
for (var location in locations) {
- _annotations.add(new LocalVariableAnnotation(_isolate, _instances,
- _r.queue, location,
- variable['value']));
+ _annotations.add(new LocalVariableAnnotation(
+ _isolate, _instances, _r.queue, location, variable['value']));
}
}
}
@@ -592,16 +609,14 @@
button.disabled = false;
});
button.title = 'Refresh coverage';
- button.children = [
- _iconRefresh.clone(true)
- ];
+ button.children = [_iconRefresh.clone(true)];
return button;
}
ButtonElement _newToggleProfileButton() {
ButtonElement button = new ButtonElement();
- button.classes = _includeProfile ? ['toggle-profile', 'enabled']
- : ['toggle-profile'];
+ button.classes =
+ _includeProfile ? ['toggle-profile', 'enabled'] : ['toggle-profile'];
button.title = 'Toggle CPU profile information';
button.onClick.listen((_) async {
_includeProfile = !_includeProfile;
@@ -610,9 +625,7 @@
_refresh();
button.disabled = false;
});
- button.children = [
- _iconWhatsHot.clone(true)
- ];
+ button.children = [_iconWhatsHot.clone(true)];
return button;
}
@@ -631,8 +644,8 @@
}
var endLine = (_endPos != null
- ? _loadedScript.tokenToLine(_endPos)
- : script.lines.length + _loadedScript.lineOffset);
+ ? _loadedScript.tokenToLine(_endPos)
+ : script.lines.length + _loadedScript.lineOffset);
var lineNumPad = endLine.toString().length;
_annotationsCursor = 0;
@@ -650,7 +663,7 @@
int lastBlank = i - 1;
if (blankLineCount < 4) {
// Too few blank lines for an elipsis.
- for (int j = firstBlank; j <= lastBlank; j++) {
+ for (int j = firstBlank; j <= lastBlank; j++) {
table.append(lineElement(script.getLine(j), lineNumPad));
}
} else {
@@ -787,17 +800,18 @@
busy = true;
if (line.breakpoints == null) {
// No breakpoint. Add it.
- line.script.isolate.addBreakpoint(line.script, line.line)
- .catchError((e, st) {
- if (e is! S.ServerRpcException ||
- (e as S.ServerRpcException).code !=
- S.ServerRpcException.kCannotAddBreakpoint) {
- ObservatoryApplication.app.handleException(e, st);
- }})
- .whenComplete(() {
- busy = false;
- update();
- });
+ line.script.isolate
+ .addBreakpoint(line.script, line.line)
+ .catchError((e, st) {
+ if (e is! S.ServerRpcException ||
+ (e as S.ServerRpcException).code !=
+ S.ServerRpcException.kCannotAddBreakpoint) {
+ ObservatoryApplication.app.handleException(e, st);
+ }
+ }).whenComplete(() {
+ busy = false;
+ update();
+ });
} else {
// Existing breakpoint. Remove it.
List pending = [];
@@ -880,7 +894,7 @@
var position = 0;
consumeUntil(var stop) {
if (stop <= position) {
- return null; // Empty gap between annotations/boundries.
+ return null; // Empty gap between annotations/boundries.
}
if (stop > line.text.length) {
// Approximated token length can run past the end of the line.
@@ -954,9 +968,10 @@
infoBox.style.whiteSpace = 'normal';
content.append(infoBox);
}
+
content.onClick.listen((event) {
show = !show;
- if (infoBox == null) buildInfoBox(); // Created lazily on the first click.
+ if (infoBox == null) buildInfoBox(); // Created lazily on the first click.
infoBox.style.display = show ? 'block' : 'none';
content.style.backgroundColor = show ? 'white' : originalBackground;
});
@@ -966,7 +981,6 @@
content.style.cursor = 'pointer';
}
-
void addLink(Element content, String target) {
// Ick, destructive but still compatible with also adding an info box.
var a = new AnchorElement(href: target);
@@ -975,7 +989,6 @@
content.append(a);
}
-
abstract class Annotation implements Comparable<Annotation> {
M.IsolateRef _isolate;
M.InstanceRepository _instances;
@@ -1030,16 +1043,15 @@
}
class CurrentExecutionAnnotation extends Annotation {
- int priority = 0; // highest priority.
+ int priority = 0; // highest priority.
CurrentExecutionAnnotation(M.IsolateRef isolate,
- M.InstanceRepository instances,
- RenderingQueue queue)
- : super(isolate, instances, queue);
+ M.InstanceRepository instances, RenderingQueue queue)
+ : super(isolate, instances, queue);
void applyStyleTo(element) {
if (element == null) {
- return; // TODO(rmacnak): Handling overlapping annotations.
+ return; // TODO(rmacnak): Handling overlapping annotations.
}
element.classes.add("currentCol");
element.title = "Current execution";
@@ -1051,14 +1063,14 @@
int priority = 1;
BreakpointAnnotation(M.IsolateRef isolate, M.InstanceRepository instances,
- RenderingQueue queue, this.bpt)
- : super(isolate, instances, queue) {
+ RenderingQueue queue, this.bpt)
+ : super(isolate, instances, queue) {
var script = bpt.location.script;
var location = bpt.location;
if (location.tokenPos != null) {
var pos = location.tokenPos;
line = script.tokenToLine(pos);
- columnStart = script.tokenToCol(pos) - 1; // tokenToCol is 1-origin.
+ columnStart = script.tokenToCol(pos) - 1; // tokenToCol is 1-origin.
} else if (location is M.UnresolvedSourceLocation) {
line = location.line;
columnStart = location.column;
@@ -1075,7 +1087,7 @@
void applyStyleTo(element) {
if (element == null) {
- return; // TODO(rmacnak): Handling overlapping annotations.
+ return; // TODO(rmacnak): Handling overlapping annotations.
}
var script = bpt.location.script;
var pos = bpt.location.tokenPos;
@@ -1096,12 +1108,12 @@
int priority = 2;
LibraryAnnotation(M.IsolateRef isolate, M.InstanceRepository instances,
- RenderingQueue queue, this.target, this.url)
- : super(isolate, instances, queue);
+ RenderingQueue queue, this.target, this.url)
+ : super(isolate, instances, queue);
void applyStyleTo(element) {
if (element == null) {
- return; // TODO(rmacnak): Handling overlapping annotations.
+ return; // TODO(rmacnak): Handling overlapping annotations.
}
element.title = "library ${target.uri}";
addLink(element, url);
@@ -1114,12 +1126,12 @@
int priority = 2;
PartAnnotation(M.IsolateRef isolate, M.InstanceRepository instances,
- RenderingQueue queue, this.part, this.url)
- : super(isolate, instances, queue);
+ RenderingQueue queue, this.part, this.url)
+ : super(isolate, instances, queue);
void applyStyleTo(element) {
if (element == null) {
- return; // TODO(rmacnak): Handling overlapping annotations.
+ return; // TODO(rmacnak): Handling overlapping annotations.
}
element.title = "script ${part.uri}";
addLink(element, url);
@@ -1131,8 +1143,8 @@
int priority = 2;
LocalVariableAnnotation(M.IsolateRef isolate, M.InstanceRepository instances,
- RenderingQueue queue, S.LocalVarLocation location,
- this.value): super(isolate, instances, queue) {
+ RenderingQueue queue, S.LocalVarLocation location, this.value)
+ : super(isolate, instances, queue) {
line = location.line;
columnStart = location.column;
columnStop = location.endColumn;
@@ -1140,7 +1152,7 @@
void applyStyleTo(element) {
if (element == null) {
- return; // TODO(rmacnak): Handling overlapping annotations.
+ return; // TODO(rmacnak): Handling overlapping annotations.
}
element.style.fontWeight = "bold";
element.title = "${value.shortName}";
@@ -1152,22 +1164,22 @@
int priority = 2;
CallSiteAnnotation(M.IsolateRef isolate, M.InstanceRepository instances,
- RenderingQueue queue, this.callSite)
- : super(isolate, instances, queue) {
+ RenderingQueue queue, this.callSite)
+ : super(isolate, instances, queue) {
line = callSite.line;
- columnStart = callSite.column - 1; // Call site is 1-origin.
+ columnStart = callSite.column - 1; // Call site is 1-origin.
var tokenLength = callSite.script.guessTokenLength(line, columnStart);
if (tokenLength == null) {
- tokenLength = callSite.name.length; // Approximate.
- if (callSite.name.startsWith("get:") ||
- callSite.name.startsWith("set:")) tokenLength -= 4;
+ tokenLength = callSite.name.length; // Approximate.
+ if (callSite.name.startsWith("get:") || callSite.name.startsWith("set:"))
+ tokenLength -= 4;
}
columnStop = columnStart + tokenLength;
}
void applyStyleTo(element) {
if (element == null) {
- return; // TODO(rmacnak): Handling overlapping annotations.
+ return; // TODO(rmacnak): Handling overlapping annotations.
}
element.style.fontWeight = "bold";
element.title = "Call site: ${callSite.name}";
@@ -1205,8 +1217,8 @@
int priority = 2;
DeclarationAnnotation(M.IsolateRef isolate, M.InstanceRepository instances,
- RenderingQueue queue, decl, this.url)
- : super(isolate, instances, queue) {
+ RenderingQueue queue, decl, this.url)
+ : super(isolate, instances, queue) {
assert(decl.loaded);
S.SourceLocation location = decl.location;
if (location == null) {
@@ -1243,15 +1255,18 @@
class ClassDeclarationAnnotation extends DeclarationAnnotation {
S.Class klass;
- ClassDeclarationAnnotation(M.IsolateRef isolate,
- M.InstanceRepository instances,
- RenderingQueue queue, S.Class cls, String url)
- : klass = cls,
- super(isolate, instances, queue, cls, url);
+ ClassDeclarationAnnotation(
+ M.IsolateRef isolate,
+ M.InstanceRepository instances,
+ RenderingQueue queue,
+ S.Class cls,
+ String url)
+ : klass = cls,
+ super(isolate, instances, queue, cls, url);
void applyStyleTo(element) {
if (element == null) {
- return; // TODO(rmacnak): Handling overlapping annotations.
+ return; // TODO(rmacnak): Handling overlapping annotations.
}
element.title = "class ${klass.name}";
addLink(element, url);
@@ -1261,15 +1276,18 @@
class FieldDeclarationAnnotation extends DeclarationAnnotation {
S.Field field;
- FieldDeclarationAnnotation(M.IsolateRef isolate,
- M.InstanceRepository instances,
- RenderingQueue queue, S.Field fld, String url)
- : field = fld,
- super(isolate, instances, queue, fld, url);
+ FieldDeclarationAnnotation(
+ M.IsolateRef isolate,
+ M.InstanceRepository instances,
+ RenderingQueue queue,
+ S.Field fld,
+ String url)
+ : field = fld,
+ super(isolate, instances, queue, fld, url);
void applyStyleTo(element) {
if (element == null) {
- return; // TODO(rmacnak): Handling overlapping annotations.
+ return; // TODO(rmacnak): Handling overlapping annotations.
}
var tooltip = "field ${field.name}";
element.title = tooltip;
@@ -1280,16 +1298,18 @@
class FunctionDeclarationAnnotation extends DeclarationAnnotation {
S.ServiceFunction function;
- FunctionDeclarationAnnotation(M.IsolateRef isolate,
- M.InstanceRepository instances,
- RenderingQueue queue, S.ServiceFunction func,
- String url)
- : function = func,
- super(isolate, instances, queue, func, url);
+ FunctionDeclarationAnnotation(
+ M.IsolateRef isolate,
+ M.InstanceRepository instances,
+ RenderingQueue queue,
+ S.ServiceFunction func,
+ String url)
+ : function = func,
+ super(isolate, instances, queue, func, url);
void applyStyleTo(element) {
if (element == null) {
- return; // TODO(rmacnak): Handling overlapping annotations.
+ return; // TODO(rmacnak): Handling overlapping annotations.
}
var tooltip = "method ${function.name}";
if (function.isOptimizable == false) {
@@ -1305,8 +1325,8 @@
if (function.isOptimizable == false ||
function.isInlinable == false ||
- function.deoptimizations >0) {
- element.style.backgroundColor = "#EEA7A7"; // Low-saturation red.
+ function.deoptimizations > 0) {
+ element.style.backgroundColor = "#EEA7A7"; // Low-saturation red.
}
addLink(element, url);
@@ -1316,8 +1336,8 @@
class ScriptLineProfile {
ScriptLineProfile(this.line, this.sampleCount);
- static const kHotThreshold = 0.05; // 5%.
- static const kMediumThreshold = 0.02; // 2%.
+ static const kHotThreshold = 0.05; // 5%.
+ static const kMediumThreshold = 0.02; // 2%.
final int line;
final int sampleCount;
@@ -1354,27 +1374,31 @@
}
final SvgSvgElement _iconRefresh = new SvgSvgElement()
- ..setAttribute('width', '24')
- ..setAttribute('height', '24')
- ..children = [
- new PathElement()
- ..setAttribute('d', 'M17.65 6.35C16.2 4.9 14.21 4 12 4c-4.42 0-7.99 '
- '3.58-7.99 8s3.57 8 7.99 8c3.73 0 6.84-2.55 '
- '7.73-6h-2.08c-.82 2.33-3.04 4-5.65 4-3.31 '
- '0-6-2.69-6-6s2.69-6 6-6c1.66 0 3.14.69 4.22 '
- '1.78L13 11h7V4l-2.35 2.35z')
- ];
+ ..setAttribute('width', '24')
+ ..setAttribute('height', '24')
+ ..children = [
+ new PathElement()
+ ..setAttribute(
+ 'd',
+ 'M17.65 6.35C16.2 4.9 14.21 4 12 4c-4.42 0-7.99 '
+ '3.58-7.99 8s3.57 8 7.99 8c3.73 0 6.84-2.55 '
+ '7.73-6h-2.08c-.82 2.33-3.04 4-5.65 4-3.31 '
+ '0-6-2.69-6-6s2.69-6 6-6c1.66 0 3.14.69 4.22 '
+ '1.78L13 11h7V4l-2.35 2.35z')
+ ];
final SvgSvgElement _iconWhatsHot = new SvgSvgElement()
- ..setAttribute('width', '24')
- ..setAttribute('height', '24')
- ..children = [
- new PathElement()
- ..setAttribute('d', 'M13.5.67s.74 2.65.74 4.8c0 2.06-1.35 3.73-3.41 '
- '3.73-2.07 0-3.63-1.67-3.63-3.73l.03-.36C5.21 7.51 '
- '4 10.62 4 14c0 4.42 3.58 8 8 8s8-3.58 8-8C20 8.61 '
- '17.41 3.8 13.5.67zM11.71 19c-1.78 '
- '0-3.22-1.4-3.22-3.14 0-1.62 1.05-2.76 2.81-3.12 '
- '1.77-.36 3.6-1.21 4.62-2.58.39 1.29.59 2.65.59 '
- '4.04 0 2.65-2.15 4.8-4.8 4.8z')
- ];
+ ..setAttribute('width', '24')
+ ..setAttribute('height', '24')
+ ..children = [
+ new PathElement()
+ ..setAttribute(
+ 'd',
+ 'M13.5.67s.74 2.65.74 4.8c0 2.06-1.35 3.73-3.41 '
+ '3.73-2.07 0-3.63-1.67-3.63-3.73l.03-.36C5.21 7.51 '
+ '4 10.62 4 14c0 4.42 3.58 8 8 8s8-3.58 8-8C20 8.61 '
+ '17.41 3.8 13.5.67zM11.71 19c-1.78 '
+ '0-3.22-1.4-3.22-3.14 0-1.62 1.05-2.76 2.81-3.12 '
+ '1.77-.36 3.6-1.21 4.62-2.58.39 1.29.59 2.65.59 '
+ '4.04 0 2.65-2.15 4.8-4.8 4.8z')
+ ];
diff --git a/runtime/observatory/lib/src/elements/script_ref.dart b/runtime/observatory/lib/src/elements/script_ref.dart
index b9b3ddb..78d8fda 100644
--- a/runtime/observatory/lib/src/elements/script_ref.dart
+++ b/runtime/observatory/lib/src/elements/script_ref.dart
@@ -18,7 +18,6 @@
Stream<RenderedEvent<ScriptRefElement>> get onRendered => _r.onRendered;
-
M.IsolateRef _isolate;
M.ScriptRef _script;
@@ -26,7 +25,7 @@
M.ScriptRef get script => _script;
factory ScriptRefElement(M.IsolateRef isolate, M.ScriptRef script,
- {RenderingQueue queue}) {
+ {RenderingQueue queue}) {
assert(isolate != null);
assert(script != null);
ScriptRefElement e = document.createElement(tag.name);
diff --git a/runtime/observatory/lib/src/elements/script_view.dart b/runtime/observatory/lib/src/elements/script_view.dart
index 98f0731..b4bf99c 100644
--- a/runtime/observatory/lib/src/elements/script_view.dart
+++ b/runtime/observatory/lib/src/elements/script_view.dart
@@ -24,25 +24,24 @@
import 'package:observatory/src/elements/view_footer.dart';
class ScriptViewElement extends HtmlElement implements Renderable {
- static const tag = const Tag<ScriptViewElement>('script-view',
- dependencies: const [
- ContextRefElement.tag,
- CurlyBlockElement.tag,
- NavTopMenuElement.tag,
- NavVMMenuElement.tag,
- NavIsolateMenuElement.tag,
- NavLibraryMenuElement.tag,
- NavRefreshElement.tag,
- NavNotifyElement.tag,
- ObjectCommonElement.tag,
- ScriptInsetElement.tag,
- ViewFooterElement.tag
- ]);
+ static const tag =
+ const Tag<ScriptViewElement>('script-view', dependencies: const [
+ ContextRefElement.tag,
+ CurlyBlockElement.tag,
+ NavTopMenuElement.tag,
+ NavVMMenuElement.tag,
+ NavIsolateMenuElement.tag,
+ NavLibraryMenuElement.tag,
+ NavRefreshElement.tag,
+ NavNotifyElement.tag,
+ ObjectCommonElement.tag,
+ ScriptInsetElement.tag,
+ ViewFooterElement.tag
+ ]);
RenderingScheduler<ScriptViewElement> _r;
- Stream<RenderedEvent<ScriptViewElement>> get onRendered =>
- _r.onRendered;
+ Stream<RenderedEvent<ScriptViewElement>> get onRendered => _r.onRendered;
M.VM _vm;
M.IsolateRef _isolate;
@@ -57,23 +56,25 @@
M.InstanceRepository _instances;
int _pos;
-
M.VMRef get vm => _vm;
M.IsolateRef get isolate => _isolate;
M.NotificationRepository get notifications => _notifications;
M.Script get script => _script;
- factory ScriptViewElement(M.VM vm, M.IsolateRef isolate,
- M.Script script,
- M.EventRepository events,
- M.NotificationRepository notifications,
- M.ScriptRepository scripts,
- M.RetainedSizeRepository retainedSizes,
- M.ReachableSizeRepository reachableSizes,
- M.InboundReferencesRepository references,
- M.RetainingPathRepository retainingPaths,
- M.InstanceRepository instances,
- {int pos, RenderingQueue queue}) {
+ factory ScriptViewElement(
+ M.VM vm,
+ M.IsolateRef isolate,
+ M.Script script,
+ M.EventRepository events,
+ M.NotificationRepository notifications,
+ M.ScriptRepository scripts,
+ M.RetainedSizeRepository retainedSizes,
+ M.ReachableSizeRepository reachableSizes,
+ M.InboundReferencesRepository references,
+ M.RetainingPathRepository retainingPaths,
+ M.InstanceRepository instances,
+ {int pos,
+ RenderingQueue queue}) {
assert(vm != null);
assert(isolate != null);
assert(events != null);
@@ -126,34 +127,40 @@
new NavLibraryMenuElement(_isolate, _script.library, queue: _r.queue),
navMenu('object'),
new NavRefreshElement(queue: _r.queue)
- ..onRefresh.listen((e) async {
- e.element.disabled = true;
- _script = await _scripts.get(_isolate, _script.id);
- _r.dirty();
- }),
+ ..onRefresh.listen((e) async {
+ e.element.disabled = true;
+ _script = await _scripts.get(_isolate, _script.id);
+ _r.dirty();
+ }),
new NavNotifyElement(_notifications, queue: _r.queue)
]),
- new DivElement()..classes = ['content-centered-big']
+ new DivElement()
+ ..classes = ['content-centered-big']
..children = [
new HeadingElement.h2()..text = 'Script',
new HRElement(),
new ObjectCommonElement(_isolate, _script, _retainedSizes,
- _reachableSizes, _references, _retainingPaths,
- _instances, queue: _r.queue),
+ _reachableSizes, _references, _retainingPaths, _instances,
+ queue: _r.queue),
new BRElement(),
- new DivElement()..classes = ['memberList']
+ new DivElement()
+ ..classes = ['memberList']
..children = [
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'load time',
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = '${_script.loadTime}'
],
],
new HRElement(),
- new ScriptInsetElement(_isolate, _script, _scripts, _instances,
- _events, currentPos: _pos, queue: _r.queue),
+ new ScriptInsetElement(
+ _isolate, _script, _scripts, _instances, _events,
+ currentPos: _pos, queue: _r.queue),
new ViewFooterElement(queue: _r.queue)
]
];
diff --git a/runtime/observatory/lib/src/elements/sentinel_value.dart b/runtime/observatory/lib/src/elements/sentinel_value.dart
index 70f6489..7e1483f 100644
--- a/runtime/observatory/lib/src/elements/sentinel_value.dart
+++ b/runtime/observatory/lib/src/elements/sentinel_value.dart
@@ -54,19 +54,18 @@
return 'This object has been reclaimed by the garbage collector.';
case M.SentinelKind.expired:
return 'The handle to this object has expired. '
- 'Consider refreshing the page.';
+ 'Consider refreshing the page.';
case M.SentinelKind.notInitialized:
return 'This object will be initialized once it is accessed by '
- 'the program.';
+ 'the program.';
case M.SentinelKind.initializing:
return 'This object is currently being initialized.';
case M.SentinelKind.optimizedOut:
return 'This object is no longer needed and has been removed by the '
- 'optimizing compiler.';
+ 'optimizing compiler.';
case M.SentinelKind.free:
return '';
}
throw new Exception('Unknown SentinelKind: $kind');
}
-
}
diff --git a/runtime/observatory/lib/src/elements/sentinel_view.dart b/runtime/observatory/lib/src/elements/sentinel_view.dart
index eb8cd90..c470758 100644
--- a/runtime/observatory/lib/src/elements/sentinel_view.dart
+++ b/runtime/observatory/lib/src/elements/sentinel_view.dart
@@ -15,16 +15,15 @@
import 'package:observatory/src/elements/nav/vm_menu.dart';
import 'package:observatory/src/elements/view_footer.dart';
-
class SentinelViewElement extends HtmlElement implements Renderable {
- static const tag = const Tag<SentinelViewElement>('sentinel-view',
- dependencies: const [
- NavTopMenuElement.tag,
- NavVMMenuElement.tag,
- NavIsolateMenuElement.tag,
- NavNotifyElement.tag,
- ViewFooterElement.tag
- ]);
+ static const tag =
+ const Tag<SentinelViewElement>('sentinel-view', dependencies: const [
+ NavTopMenuElement.tag,
+ NavVMMenuElement.tag,
+ NavIsolateMenuElement.tag,
+ NavNotifyElement.tag,
+ ViewFooterElement.tag
+ ]);
RenderingScheduler<SentinelViewElement> _r;
@@ -38,10 +37,13 @@
M.Sentinel get sentinel => _sentinel;
- factory SentinelViewElement(M.VM vm, M.IsolateRef isolate, M.Sentinel sentinel,
- M.EventRepository events,
- M.NotificationRepository notifications,
- {RenderingQueue queue}) {
+ factory SentinelViewElement(
+ M.VM vm,
+ M.IsolateRef isolate,
+ M.Sentinel sentinel,
+ M.EventRepository events,
+ M.NotificationRepository notifications,
+ {RenderingQueue queue}) {
assert(vm != null);
assert(isolate != null);
assert(sentinel != null);
@@ -82,13 +84,13 @@
navMenu('sentinel'),
new NavNotifyElement(_notifications, queue: _r.queue)
]),
- new DivElement()..classes = ['content-centered-big']
+ new DivElement()
+ ..classes = ['content-centered-big']
..children = [
new HeadingElement.h2()
..text = 'Sentinel: #{_sentinel.valueAsString}',
new HRElement(),
- new DivElement()
- ..text = _sentinelKindToDescription(_sentinel.kind),
+ new DivElement()..text = _sentinelKindToDescription(_sentinel.kind),
new HRElement(),
new ViewFooterElement(queue: _r.queue)
]
@@ -101,19 +103,18 @@
return 'This object has been reclaimed by the garbage collector.';
case M.SentinelKind.expired:
return 'The handle to this object has expired. '
- 'Consider refreshing the page.';
+ 'Consider refreshing the page.';
case M.SentinelKind.notInitialized:
return 'This object will be initialized once it is accessed by '
- 'the program.';
+ 'the program.';
case M.SentinelKind.initializing:
return 'This object is currently being initialized.';
case M.SentinelKind.optimizedOut:
return 'This object is no longer needed and has been removed by the '
- 'optimizing compiler.';
+ 'optimizing compiler.';
case M.SentinelKind.free:
return '';
}
throw new Exception('Unknown SentinelKind: $kind');
}
-
}
diff --git a/runtime/observatory/lib/src/elements/source_inset.dart b/runtime/observatory/lib/src/elements/source_inset.dart
index 69be9b3..a51cc1e 100644
--- a/runtime/observatory/lib/src/elements/source_inset.dart
+++ b/runtime/observatory/lib/src/elements/source_inset.dart
@@ -18,7 +18,6 @@
Stream<RenderedEvent<SourceInsetElement>> get onRendered => _r.onRendered;
-
M.IsolateRef _isolate;
M.SourceLocation _location;
M.ScriptRepository _scripts;
@@ -31,14 +30,16 @@
M.IsolateRef get isolate => _isolate;
M.SourceLocation get location => _location;
- factory SourceInsetElement(M.IsolateRef isolate, M.SourceLocation location,
- M.ScriptRepository scripts,
- M.InstanceRepository instances,
- M.EventRepository events,
- {int currentPos,
- bool inDebuggerContext: false,
- Iterable variables: const [],
- RenderingQueue queue}) {
+ factory SourceInsetElement(
+ M.IsolateRef isolate,
+ M.SourceLocation location,
+ M.ScriptRepository scripts,
+ M.InstanceRepository instances,
+ M.EventRepository events,
+ {int currentPos,
+ bool inDebuggerContext: false,
+ Iterable variables: const [],
+ RenderingQueue queue}) {
assert(isolate != null);
assert(location != null);
assert(scripts != null);
@@ -76,14 +77,14 @@
void render() {
children = [
- new ScriptInsetElement(_isolate, _location.script,
- _scripts, _instances, _events,
- startPos: _location.tokenPos,
- endPos: _location.endTokenPos,
- currentPos: _currentPos,
- inDebuggerContext: _inDebuggerContext,
- variables: _variables,
- queue: _r.queue)
+ new ScriptInsetElement(
+ _isolate, _location.script, _scripts, _instances, _events,
+ startPos: _location.tokenPos,
+ endPos: _location.endTokenPos,
+ currentPos: _currentPos,
+ inDebuggerContext: _inDebuggerContext,
+ variables: _variables,
+ queue: _r.queue)
];
}
}
diff --git a/runtime/observatory/lib/src/elements/source_link.dart b/runtime/observatory/lib/src/elements/source_link.dart
index 77ef2fe..5c6b7a0 100644
--- a/runtime/observatory/lib/src/elements/source_link.dart
+++ b/runtime/observatory/lib/src/elements/source_link.dart
@@ -7,7 +7,7 @@
import 'dart:html';
import 'dart:async';
import 'package:observatory/models.dart'
- show IsolateRef, SourceLocation, Script, ScriptRepository;
+ show IsolateRef, SourceLocation, Script, ScriptRepository;
import 'package:observatory/src/elements/helpers/rendering_scheduler.dart';
import 'package:observatory/src/elements/helpers/tag.dart';
import 'package:observatory/src/elements/helpers/uris.dart';
@@ -27,8 +27,9 @@
IsolateRef get isolate => _isolate;
SourceLocation get location => _location;
- factory SourceLinkElement(IsolateRef isolate, SourceLocation location,
- ScriptRepository repository, {RenderingQueue queue}) {
+ factory SourceLinkElement(
+ IsolateRef isolate, SourceLocation location, ScriptRepository repository,
+ {RenderingQueue queue}) {
assert(isolate != null);
assert(location != null);
SourceLinkElement e = document.createElement(tag.name);
diff --git a/runtime/observatory/lib/src/elements/stack_trace_tree_config.dart b/runtime/observatory/lib/src/elements/stack_trace_tree_config.dart
index b1f2f4e..1e9e239 100644
--- a/runtime/observatory/lib/src/elements/stack_trace_tree_config.dart
+++ b/runtime/observatory/lib/src/elements/stack_trace_tree_config.dart
@@ -8,10 +8,7 @@
import 'package:observatory/src/elements/helpers/rendering_scheduler.dart';
import 'package:observatory/src/elements/helpers/tag.dart';
-enum ProfileTreeMode {
- code,
- function,
-}
+enum ProfileTreeMode { code, function, }
class StackTraceTreeConfigChangedEvent {
final StackTraceTreeConfigElement element;
@@ -25,7 +22,7 @@
RenderingScheduler<StackTraceTreeConfigElement> _r;
Stream<RenderedEvent<StackTraceTreeConfigElement>> get onRendered =>
- _r.onRendered;
+ _r.onRendered;
StreamController<StackTraceTreeConfigChangedEvent> _onModeChange =
new StreamController<StackTraceTreeConfigChangedEvent>.broadcast();
@@ -64,8 +61,11 @@
_direction = _r.checkAndReact(_direction, value);
set filter(String value) => _filter = _r.checkAndReact(_filter, value);
- factory StackTraceTreeConfigElement({bool showMode: true,
- bool showDirection: true, bool showFilter: true, String filter: '',
+ factory StackTraceTreeConfigElement(
+ {bool showMode: true,
+ bool showDirection: true,
+ bool showFilter: true,
+ String filter: '',
ProfileTreeMode mode: ProfileTreeMode.function,
M.ProfileTreeDirection direction: M.ProfileTreeDirection.exclusive,
RenderingQueue queue}) {
@@ -96,19 +96,23 @@
@override
void detached() {
- super.detached(); _r.disable(notify: true);
+ super.detached();
+ _r.disable(notify: true);
children = const [];
}
void render() {
children = [
- new DivElement()..classes = ['content-centered-big']
+ new DivElement()
+ ..classes = ['content-centered-big']
..children = [
new HeadingElement.h2()..text = 'Tree display',
new HRElement(),
- new DivElement()..classes = ['row']
+ new DivElement()
+ ..classes = ['row']
..children = [
- new DivElement()..classes = ['memberList']
+ new DivElement()
+ ..classes = ['memberList']
..children = _createMembers()
]
]
@@ -118,37 +122,41 @@
List<Element> _createMembers() {
var members = <Element>[];
if (_showMode) {
- members.add(
- new DivElement()..classes = ['memberItem']
- ..children = [
- new DivElement()..classes = ['memberName']..text = 'Mode',
- new DivElement()..classes = ['memberValue']
- ..children = _createModeSelect()
- ]
- );
+ members.add(new DivElement()
+ ..classes = ['memberItem']
+ ..children = [
+ new DivElement()
+ ..classes = ['memberName']
+ ..text = 'Mode',
+ new DivElement()
+ ..classes = ['memberValue']
+ ..children = _createModeSelect()
+ ]);
}
if (_showDirection) {
- members.add(
- new DivElement()..classes = ['memberItem']
- ..children = [
- new DivElement()..classes = ['memberName']
- ..text = 'Call Tree Direction',
- new SpanElement()..classes = ['memberValue']
- ..children = _createDirectionSelect()
- ]
- );
+ members.add(new DivElement()
+ ..classes = ['memberItem']
+ ..children = [
+ new DivElement()
+ ..classes = ['memberName']
+ ..text = 'Call Tree Direction',
+ new SpanElement()
+ ..classes = ['memberValue']
+ ..children = _createDirectionSelect()
+ ]);
}
if (showFilter) {
- members.add(
- new DivElement()..classes = ['memberItem']
- ..children = [
- new DivElement()..classes = ['memberName']
- ..text = 'Call Tree Filter'
- ..title = 'case-sensitive substring match',
- new SpanElement()..classes = ['memberValue']
- ..children = _createFilter()
- ]
- );
+ members.add(new DivElement()
+ ..classes = ['memberItem']
+ ..children = [
+ new DivElement()
+ ..classes = ['memberName']
+ ..text = 'Call Tree Filter'
+ ..title = 'case-sensitive substring match',
+ new SpanElement()
+ ..classes = ['memberValue']
+ ..children = _createFilter()
+ ]);
}
return members;
}
@@ -156,16 +164,17 @@
List<Element> _createModeSelect() {
var s;
return [
- s = new SelectElement()..classes = ['mode-select']
+ s = new SelectElement()
+ ..classes = ['mode-select']
..value = modeToString(_mode)
..children = ProfileTreeMode.values.map((mode) {
- return new OptionElement(value : modeToString(mode),
- selected: _mode == mode)
- ..text = modeToString(mode);
- }).toList(growable: false)
+ return new OptionElement(
+ value: modeToString(mode),
+ selected: _mode == mode)..text = modeToString(mode);
+ }).toList(growable: false)
..onChange.listen((_) {
- _mode = ProfileTreeMode.values[s.selectedIndex];
- })
+ _mode = ProfileTreeMode.values[s.selectedIndex];
+ })
..onChange.map(_toEvent).listen(_triggerModeChange),
];
}
@@ -173,45 +182,55 @@
List<Element> _createDirectionSelect() {
var s;
return [
- s = new SelectElement()..classes = ['direction-select']
+ s = new SelectElement()
+ ..classes = ['direction-select']
..value = directionToString(_direction)
..children = M.ProfileTreeDirection.values.map((direction) {
- return new OptionElement(value: directionToString(direction),
- selected: _direction == direction)
- ..text = directionToString(direction);
- }).toList(growable: false)
+ return new OptionElement(
+ value: directionToString(direction),
+ selected: _direction == direction)
+ ..text = directionToString(direction);
+ }).toList(growable: false)
..onChange.listen((_) {
- _direction = M.ProfileTreeDirection.values[s.selectedIndex];
- })
+ _direction = M.ProfileTreeDirection.values[s.selectedIndex];
+ })
..onChange.map(_toEvent).listen(_triggerDirectionChange),
- new SpanElement()..text = 'Tree is rooted at ' +
- (_direction == 'Down' ? '"main"' : 'function / code') +
- '. Child nodes are callers.'
+ new SpanElement()
+ ..text = 'Tree is rooted at ' +
+ (_direction == 'Down' ? '"main"' : 'function / code') +
+ '. Child nodes are callers.'
];
}
- List<Element> _createFilter(){
+ List<Element> _createFilter() {
var t;
return [
- t = new TextInputElement()..placeholder = 'Search filter'
- ..value = filter
- ..onChange.listen((_) { _filter = t.value; })
- ..onChange.map(_toEvent).listen(_triggerFilterChange)
+ t = new TextInputElement()
+ ..placeholder = 'Search filter'
+ ..value = filter
+ ..onChange.listen((_) {
+ _filter = t.value;
+ })
+ ..onChange.map(_toEvent).listen(_triggerFilterChange)
];
}
static String modeToString(ProfileTreeMode mode) {
switch (mode) {
- case ProfileTreeMode.code: return 'Code';
- case ProfileTreeMode.function: return 'Function';
+ case ProfileTreeMode.code:
+ return 'Code';
+ case ProfileTreeMode.function:
+ return 'Function';
}
throw new Exception('Unknown ProfileTreeMode');
}
static String directionToString(M.ProfileTreeDirection direction) {
switch (direction) {
- case M.ProfileTreeDirection.inclusive: return 'Top down';
- case M.ProfileTreeDirection.exclusive: return 'Bottom up';
+ case M.ProfileTreeDirection.inclusive:
+ return 'Top down';
+ case M.ProfileTreeDirection.exclusive:
+ return 'Bottom up';
}
throw new Exception('Unknown ProfileTreeDirection');
}
@@ -223,6 +242,4 @@
void _triggerModeChange(e) => _onModeChange.add(e);
void _triggerDirectionChange(e) => _onDirectionChange.add(e);
void _triggerFilterChange(e) => _onFilterChange.add(e);
-
-
}
diff --git a/runtime/observatory/lib/src/elements/strongly_reachable_instances.dart b/runtime/observatory/lib/src/elements/strongly_reachable_instances.dart
index c4b85ad..c4167ad 100644
--- a/runtime/observatory/lib/src/elements/strongly_reachable_instances.dart
+++ b/runtime/observatory/lib/src/elements/strongly_reachable_instances.dart
@@ -12,18 +12,15 @@
import 'package:observatory/src/elements/helpers/tag.dart';
class StronglyReachableInstancesElement extends HtmlElement
- implements Renderable {
+ implements Renderable {
static const tag = const Tag<StronglyReachableInstancesElement>(
- 'strongly-reachable-instances',
- dependencies: const [
- CurlyBlockElement.tag,
- InstanceRefElement.tag
- ]);
+ 'strongly-reachable-instances',
+ dependencies: const [CurlyBlockElement.tag, InstanceRefElement.tag]);
RenderingScheduler<StronglyReachableInstancesElement> _r;
Stream<RenderedEvent<StronglyReachableInstancesElement>> get onRendered =>
- _r.onRendered;
+ _r.onRendered;
M.IsolateRef _isolate;
M.ClassRef _cls;
@@ -35,7 +32,8 @@
M.IsolateRef get isolate => _isolate;
M.ClassRef get cls => _cls;
- factory StronglyReachableInstancesElement(M.IsolateRef isolate,
+ factory StronglyReachableInstancesElement(
+ M.IsolateRef isolate,
M.ClassRef cls,
M.StronglyReachableInstancesRepository stronglyReachable,
M.InstanceRepository instances,
@@ -89,21 +87,16 @@
List<Element> _createContent() {
if (_result == null) {
- return [
- new SpanElement()..text = 'Loading...'
- ];
+ return [new SpanElement()..text = 'Loading...'];
}
- final content = _result.samples.map((sample) =>
- new DivElement()
- ..children = [
- anyRef(_isolate, sample, _instances, queue: _r.queue)
- ]
- ).toList();
+ final content = _result.samples
+ .map((sample) => new DivElement()
+ ..children = [anyRef(_isolate, sample, _instances, queue: _r.queue)])
+ .toList();
content.add(new DivElement()
..children = ([]
..addAll(_createShowMoreButton())
- ..add(new SpanElement()..text = ' of total ${_result.count}'))
- );
+ ..add(new SpanElement()..text = ' of total ${_result.count}')));
return content;
}
@@ -113,12 +106,11 @@
return [];
}
final count = samples.length;
- final button = new ButtonElement()
- ..text = 'show next ${count}';
+ final button = new ButtonElement()..text = 'show next ${count}';
button.onClick.listen((_) async {
button.disabled = true;
_result = await _stronglyReachableInstances.get(_isolate, _cls,
- limit: count * 2);
+ limit: count * 2);
_r.dirty();
});
return [button];
diff --git a/runtime/observatory/lib/src/elements/timeline_page.dart b/runtime/observatory/lib/src/elements/timeline_page.dart
index 373ed44..ba93c70 100644
--- a/runtime/observatory/lib/src/elements/timeline_page.dart
+++ b/runtime/observatory/lib/src/elements/timeline_page.dart
@@ -18,22 +18,16 @@
import 'package:observatory/src/elements/nav/top_menu.dart';
import 'package:observatory/src/elements/nav/vm_menu.dart';
-enum _Profile {
- none,
- dart,
- vm,
- all,
- custom
-}
+enum _Profile { none, dart, vm, all, custom }
class TimelinePageElement extends HtmlElement implements Renderable {
- static const tag = const Tag<TimelinePageElement>('timeline-page',
- dependencies: const [
- NavTopMenuElement.tag,
- NavVMMenuElement.tag,
- NavRefreshElement.tag,
- NavNotifyElement.tag
- ]);
+ static const tag =
+ const Tag<TimelinePageElement>('timeline-page', dependencies: const [
+ NavTopMenuElement.tag,
+ NavVMMenuElement.tag,
+ NavRefreshElement.tag,
+ NavNotifyElement.tag
+ ]);
RenderingScheduler<TimelinePageElement> _r;
@@ -50,9 +44,9 @@
M.VMRef get vm => _vm;
M.NotificationRepository get notifications => _notifications;
- factory TimelinePageElement(M.VM vm, M.EventRepository events,
- M.NotificationRepository notifications,
- {RenderingQueue queue}) {
+ factory TimelinePageElement(
+ M.VM vm, M.EventRepository events, M.NotificationRepository notifications,
+ {RenderingQueue queue}) {
assert(vm != null);
assert(events != null);
assert(notifications != null);
@@ -64,7 +58,7 @@
return e;
}
- TimelinePageElement.created() : super.created();
+ TimelinePageElement.created() : super.created();
@override
attached() {
@@ -92,29 +86,38 @@
}
_content.children = [
new HeadingElement.h1()..text = 'Timeline settings',
- new DivElement()..classes = ['memberList']
+ new DivElement()
+ ..classes = ['memberList']
..children = [
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'Recorder:',
- new DivElement()..classes = ['memberValue']
+ new DivElement()
+ ..classes = ['memberValue']
..text = _recorderName
],
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'Recorded Streams Profile:',
- new DivElement()..classes = ['memberValue']
+ new DivElement()
+ ..classes = ['memberValue']
..children = _createProfileSelect()
],
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'Recorded Streams:',
- new DivElement()..classes = ['memberValue']
- ..children =
- _availableStreams.map(_makeStreamToggle).toList()
+ new DivElement()
+ ..classes = ['memberValue']
+ ..children = _availableStreams.map(_makeStreamToggle).toList()
]
]
];
@@ -124,36 +127,35 @@
new NavTopMenuElement(queue: _r.queue),
new NavVMMenuElement(_vm, _events, queue: _r.queue),
new NavRefreshElement(queue: _r.queue)
- ..onRefresh.listen((e) async {
- e.element.disabled = true;
- await _refresh();
- e.element.disabled = false;
- }),
+ ..onRefresh.listen((e) async {
+ e.element.disabled = true;
+ await _refresh();
+ e.element.disabled = false;
+ }),
new NavRefreshElement(label: 'clear', queue: _r.queue)
- ..onRefresh.listen((e) async {
- e.element.disabled = true;
- await _clear();
- e.element.disabled = false;
- }),
+ ..onRefresh.listen((e) async {
+ e.element.disabled = true;
+ await _clear();
+ e.element.disabled = false;
+ }),
new NavRefreshElement(label: 'save', queue: _r.queue)
- ..onRefresh.listen((e) async {
- e.element.disabled = true;
- await _save();
- e.element.disabled = false;
- }),
+ ..onRefresh.listen((e) async {
+ e.element.disabled = true;
+ await _save();
+ e.element.disabled = false;
+ }),
new NavRefreshElement(label: 'load', queue: _r.queue)
- ..onRefresh.listen((e) async {
- e.element.disabled = true;
- await _load();
- e.element.disabled = false;
- }),
+ ..onRefresh.listen((e) async {
+ e.element.disabled = true;
+ await _load();
+ e.element.disabled = false;
+ }),
new NavNotifyElement(_notifications, queue: _r.queue)
]),
_content,
- new DivElement()..classes = ['iframe']
- ..children = [
- _frame
- ]
+ new DivElement()
+ ..classes = ['iframe']
+ ..children = [_frame]
];
}
}
@@ -161,28 +163,35 @@
List<Element> _createProfileSelect() {
var s;
return [
- s = new SelectElement()..classes = ['direction-select']
+ s = new SelectElement()
+ ..classes = ['direction-select']
..value = _profileToString(_profile)
..children = _Profile.values.map((direction) {
- return new OptionElement(value: _profileToString(direction),
- selected: _profile == direction)
- ..text = _profileToString(direction);
- }).toList(growable: false)
+ return new OptionElement(
+ value: _profileToString(direction),
+ selected: _profile == direction)
+ ..text = _profileToString(direction);
+ }).toList(growable: false)
..onChange.listen((_) {
- _profile = _Profile.values[s.selectedIndex];
- _applyPreset();
- _r.dirty();
- })
+ _profile = _Profile.values[s.selectedIndex];
+ _applyPreset();
+ _r.dirty();
+ })
];
}
String _profileToString(_Profile profile) {
switch (profile) {
- case _Profile.none: return 'none';
- case _Profile.dart: return 'Dart Developer';
- case _Profile.vm: return 'VM Developer';
- case _Profile.all: return 'All';
- case _Profile.custom: return 'Custom';
+ case _Profile.none:
+ return 'none';
+ case _Profile.dart:
+ return 'Dart Developer';
+ case _Profile.vm:
+ return 'VM Developer';
+ case _Profile.all:
+ return 'All';
+ case _Profile.custom:
+ return 'Custom';
}
throw new Exception('Unkown Profile ${profile}');
}
@@ -221,7 +230,8 @@
'isolateIds': isolateIds
}
};
- _frame.contentWindow.postMessage(JSON.encode(message), window.location.href);
+ _frame.contentWindow
+ .postMessage(JSON.encode(message), window.location.href);
return null;
}
@@ -231,12 +241,18 @@
}
// Dart developers care about the following streams:
- List<String> _dartPreset =
- ['GC', 'Compiler', 'Dart'];
+ List<String> _dartPreset = ['GC', 'Compiler', 'Dart'];
// VM developers care about the following streams:
- List<String> _vmPreset =
- ['GC', 'Compiler', 'Dart', 'Debugger', 'Embedder', 'Isolate', 'VM'];
+ List<String> _vmPreset = [
+ 'GC',
+ 'Compiler',
+ 'Dart',
+ 'Debugger',
+ 'Embedder',
+ 'Isolate',
+ 'VM'
+ ];
void _applyPreset() {
switch (_profile) {
@@ -307,12 +323,12 @@
_recorderName = response['recorderName'];
// Update the set of available streams.
_availableStreams.clear();
- response['availableStreams'].forEach(
- (String streamName) => _availableStreams.add(streamName));
+ response['availableStreams']
+ .forEach((String streamName) => _availableStreams.add(streamName));
// Update the set of recorded streams.
_recordedStreams.clear();
- response['recordedStreams'].forEach(
- (String streamName) => _recordedStreams.add(streamName));
+ response['recordedStreams']
+ .forEach((String streamName) => _recordedStreams.add(streamName));
_r.dirty();
}
}
diff --git a/runtime/observatory/lib/src/elements/token_stream_ref.dart b/runtime/observatory/lib/src/elements/token_stream_ref.dart
index 8fcaac6..7bb2364 100644
--- a/runtime/observatory/lib/src/elements/token_stream_ref.dart
+++ b/runtime/observatory/lib/src/elements/token_stream_ref.dart
@@ -4,8 +4,7 @@
import 'dart:html';
import 'dart:async';
-import 'package:observatory/models.dart' as M
- show IsolateRef, TokenStreamRef;
+import 'package:observatory/models.dart' as M show IsolateRef, TokenStreamRef;
import 'package:observatory/src/elements/helpers/rendering_scheduler.dart';
import 'package:observatory/src/elements/helpers/tag.dart';
import 'package:observatory/src/elements/helpers/uris.dart';
@@ -51,8 +50,8 @@
void render() {
final text = (_token.name == null || _token.name == '')
- ? 'TokenStream'
- : _token.name;
+ ? 'TokenStream'
+ : _token.name;
children = [
new AnchorElement(href: Uris.inspect(_isolate, object: _token))
..text = text
diff --git a/runtime/observatory/lib/src/elements/top_retaining_instances.dart b/runtime/observatory/lib/src/elements/top_retaining_instances.dart
index 3f72d3b..0d32404 100644
--- a/runtime/observatory/lib/src/elements/top_retaining_instances.dart
+++ b/runtime/observatory/lib/src/elements/top_retaining_instances.dart
@@ -14,16 +14,13 @@
class TopRetainingInstancesElement extends HtmlElement implements Renderable {
static const tag = const Tag<TopRetainingInstancesElement>(
- 'top-retainig-instances',
- dependencies: const [
- CurlyBlockElement.tag,
- InstanceRefElement.tag
- ]);
+ 'top-retainig-instances',
+ dependencies: const [CurlyBlockElement.tag, InstanceRefElement.tag]);
RenderingScheduler<TopRetainingInstancesElement> _r;
Stream<RenderedEvent<TopRetainingInstancesElement>> get onRendered =>
- _r.onRendered;
+ _r.onRendered;
M.IsolateRef _isolate;
M.ClassRef _cls;
@@ -35,7 +32,9 @@
M.IsolateRef get isolate => _isolate;
M.ClassRef get cls => _cls;
- factory TopRetainingInstancesElement(M.IsolateRef isolate, M.ClassRef cls,
+ factory TopRetainingInstancesElement(
+ M.IsolateRef isolate,
+ M.ClassRef cls,
M.TopRetainingInstancesRepository topRetainingInstances,
M.InstanceRepository instances,
{RenderingQueue queue}) {
@@ -71,7 +70,8 @@
children = [
new CurlyBlockElement(expanded: _expanded, queue: _r.queue)
..content = [
- new DivElement()..classes = ['memberList']
+ new DivElement()
+ ..classes = ['memberList']
..children = _createContent()
]
..onToggle.listen((e) async {
@@ -93,20 +93,21 @@
List<Element> _createContent() {
if (_topRetaining == null) {
- return [
- new SpanElement()..text = 'Loading...'
- ];
+ return [new SpanElement()..text = 'Loading...'];
}
- return _topRetaining.map((r) =>
- new DivElement()..classes = ['memberItem']
- ..children = [
- new DivElement()..classes = ['memberName']
- ..text = '${Utils.formatSize(r.retainedSize)} ',
- new DivElement()..classes = ['memberValue']
- ..children = [
- anyRef(_isolate, r.object, _instances, queue: _r.queue)
- ]
- ]
- ).toList();
+ return _topRetaining
+ .map((r) => new DivElement()
+ ..classes = ['memberItem']
+ ..children = [
+ new DivElement()
+ ..classes = ['memberName']
+ ..text = '${Utils.formatSize(r.retainedSize)} ',
+ new DivElement()
+ ..classes = ['memberValue']
+ ..children = [
+ anyRef(_isolate, r.object, _instances, queue: _r.queue)
+ ]
+ ])
+ .toList();
}
}
diff --git a/runtime/observatory/lib/src/elements/type_arguments_ref.dart b/runtime/observatory/lib/src/elements/type_arguments_ref.dart
index f6f004c..46a254b 100644
--- a/runtime/observatory/lib/src/elements/type_arguments_ref.dart
+++ b/runtime/observatory/lib/src/elements/type_arguments_ref.dart
@@ -14,7 +14,8 @@
RenderingScheduler<TypeArgumentsRefElement> _r;
- Stream<RenderedEvent<TypeArgumentsRefElement>> get onRendered => _r.onRendered;
+ Stream<RenderedEvent<TypeArgumentsRefElement>> get onRendered =>
+ _r.onRendered;
M.IsolateRef _isolate;
M.TypeArgumentsRef _arguments;
@@ -50,8 +51,8 @@
void render() {
final text = (_arguments.name == null || _arguments.name == '')
- ? 'TypeArguments'
- : _arguments.name;
+ ? 'TypeArguments'
+ : _arguments.name;
children = [
new AnchorElement(href: Uris.inspect(_isolate, object: _arguments))
..text = text
diff --git a/runtime/observatory/lib/src/elements/unknown_ref.dart b/runtime/observatory/lib/src/elements/unknown_ref.dart
index cc4d278..3165877 100644
--- a/runtime/observatory/lib/src/elements/unknown_ref.dart
+++ b/runtime/observatory/lib/src/elements/unknown_ref.dart
@@ -4,8 +4,7 @@
import 'dart:html';
import 'dart:async';
-import 'package:observatory/models.dart' as M
- show IsolateRef, UnknownObjectRef;
+import 'package:observatory/models.dart' as M show IsolateRef, UnknownObjectRef;
import 'package:observatory/src/elements/helpers/rendering_scheduler.dart';
import 'package:observatory/src/elements/helpers/tag.dart';
import 'package:observatory/src/elements/helpers/uris.dart';
@@ -24,8 +23,8 @@
M.IsolateRef get isolate => _isolate;
M.UnknownObjectRef get obj => _obj;
- factory UnknownObjectRefElement(M.IsolateRef isolate,
- M.UnknownObjectRef obj, {RenderingQueue queue}) {
+ factory UnknownObjectRefElement(M.IsolateRef isolate, M.UnknownObjectRef obj,
+ {RenderingQueue queue}) {
assert(isolate != null);
assert(obj != null);
UnknownObjectRefElement e = document.createElement(tag.name);
diff --git a/runtime/observatory/lib/src/elements/view_footer.dart b/runtime/observatory/lib/src/elements/view_footer.dart
index 8498090..f85b1d9 100644
--- a/runtime/observatory/lib/src/elements/view_footer.dart
+++ b/runtime/observatory/lib/src/elements/view_footer.dart
@@ -39,12 +39,13 @@
void render() {
children = [
- new AnchorElement()
- ..href = 'https://www.dartlang.org/tools/observatory'
- ..text = 'View documentation',
- new AnchorElement()
- ..href = 'https://github.com/dart-lang/sdk/issues/new?title=Observatory:&body=Observatory%20Feedback'
- ..text = 'File a bug report'
+ new AnchorElement()
+ ..href = 'https://www.dartlang.org/tools/observatory'
+ ..text = 'View documentation',
+ new AnchorElement()
+ ..href =
+ 'https://github.com/dart-lang/sdk/issues/new?title=Observatory:&body=Observatory%20Feedback'
+ ..text = 'File a bug report'
];
}
}
diff --git a/runtime/observatory/lib/src/elements/vm_connect.dart b/runtime/observatory/lib/src/elements/vm_connect.dart
index 3f20e26..49282a5 100644
--- a/runtime/observatory/lib/src/elements/vm_connect.dart
+++ b/runtime/observatory/lib/src/elements/vm_connect.dart
@@ -8,6 +8,7 @@
import 'dart:async';
import 'dart:convert';
import 'package:observatory/models.dart' as M;
+import 'package:observatory/app.dart';
import 'package:observatory/src/elements/helpers/tag.dart';
import 'package:observatory/src/elements/helpers/rendering_scheduler.dart';
import 'package:observatory/src/elements/helpers/nav_bar.dart';
@@ -19,11 +20,13 @@
typedef void CrashDumpLoadCallback(Map dump);
class VMConnectElement extends HtmlElement implements Renderable {
- static const tag = const Tag<VMConnectElement>('vm-connect',
- dependencies: const [NavTopMenuElement.tag,
- NavNotifyElement.tag,
- ViewFooterElement.tag,
- VMConnectTargetElement.tag]);
+ static const tag =
+ const Tag<VMConnectElement>('vm-connect', dependencies: const [
+ NavTopMenuElement.tag,
+ NavNotifyElement.tag,
+ ViewFooterElement.tag,
+ VMConnectTargetElement.tag
+ ]);
RenderingScheduler _r;
@@ -37,9 +40,8 @@
String _address;
factory VMConnectElement(M.TargetRepository targets,
- CrashDumpLoadCallback loadDump,
- M.NotificationRepository notifications,
- {String address: '', RenderingQueue queue}) {
+ CrashDumpLoadCallback loadDump, M.NotificationRepository notifications,
+ {String address: '', RenderingQueue queue}) {
assert(address != null);
assert(loadDump != null);
assert(notifications != null);
@@ -82,7 +84,8 @@
..classes = ['content-centered']
..children = [
new HeadingElement.h1()..text = 'Connect to a Dart VM',
- new BRElement(), new HRElement(),
+ new BRElement(),
+ new HRElement(),
new DivElement()
..classes = ['flex-row']
..children = [
@@ -93,13 +96,18 @@
new BRElement(),
new UListElement()
..children = _targets.list().map((target) {
+ final ObservatoryApplication app =
+ ObservatoryApplication.app;
+ final bool current = (app != null) ?
+ app.isConnectedVMTarget(target) : false;
return new LIElement()
- ..children = [new VMConnectTargetElement(target,
- current: target == _targets.current, queue: _r.queue)
- ..onConnect.listen(_connect)
- ..onDelete.listen(_delete)
+ ..children = [
+ new VMConnectTargetElement(target,
+ current: current, queue: _r.queue)
+ ..onConnect.listen(_connect)
+ ..onDelete.listen(_delete)
];
- }).toList(),
+ }).toList(),
new HRElement(),
new FormElement()
..autocomplete = 'on'
@@ -110,7 +118,9 @@
..classes = ['vm_connect']
..text = 'Connect'
..onClick.listen((e) {
- e.preventDefault(); _create(); }),
+ e.preventDefault();
+ _create();
+ }),
],
new BRElement(),
new PreElement()
@@ -118,19 +128,19 @@
..text = 'Run Standalone with: \'--observe\'',
new HRElement()
],
- new DivElement()
- ..classes = ['flex-item-20-percent'],
+ new DivElement()..classes = ['flex-item-20-percent'],
new DivElement()
..classes = ['flex-item-40-percent']
..children = [
new HeadingElement.h2()..text = 'Crash dump',
new BRElement(),
_createCrushDumpLoader(),
- new BRElement(), new BRElement(),
+ new BRElement(),
+ new BRElement(),
new PreElement()
..classes = ['well']
..text = 'Request a crash dump with:\n'
- '\'curl $host:$port/_getCrashDump > dump.json\'',
+ '\'curl $host:$port/_getCrashDump > dump.json\'',
new HRElement()
]
],
@@ -144,9 +154,10 @@
..classes = ['textbox']
..placeholder = 'localhost:8181'
..value = _address
- ..onKeyUp
- .where((e) => e.key == '\n')
- .listen((e) { e.preventDefault(); _create(); });
+ ..onKeyUp.where((e) => e.key == '\n').listen((e) {
+ e.preventDefault();
+ _create();
+ });
textbox.onInput.listen((e) {
_address = textbox.value;
});
@@ -166,17 +177,30 @@
});
return e;
}
+
void _create() {
if (_address == null || _address.isEmpty) return;
_targets.add(_normalizeStandaloneAddress(_address));
}
- void _connect(TargetEvent e) => _targets.setCurrent(e.target);
+
+ void _connect(TargetEvent e) {
+ _targets.setCurrent(e.target);
+ }
+
void _delete(TargetEvent e) => _targets.delete(e.target);
static String _normalizeStandaloneAddress(String networkAddress) {
- if (networkAddress.startsWith('ws://')) {
+ if (!networkAddress.startsWith('http') &&
+ !networkAddress.startsWith('ws')) {
+ networkAddress = 'http://$networkAddress';
+ }
+ try {
+ Uri uri = Uri.parse(networkAddress);
+ print('returning ${uri.host} ${uri.port}');
+ return 'ws://${uri.host}:${uri.port}/ws';
+ } catch (e) {
+ print('caught exception with: $networkAddress -- $e');
return networkAddress;
}
- return 'ws://${networkAddress}/ws';
}
}
diff --git a/runtime/observatory/lib/src/elements/vm_connect_target.dart b/runtime/observatory/lib/src/elements/vm_connect_target.dart
index 43a0cec..c7c71ec 100644
--- a/runtime/observatory/lib/src/elements/vm_connect_target.dart
+++ b/runtime/observatory/lib/src/elements/vm_connect_target.dart
@@ -16,9 +16,7 @@
}
class VMConnectTargetElement extends HtmlElement implements Renderable {
-
- static const tag =
- const Tag<VMConnectTargetElement>('vm-connect-target');
+ static const tag = const Tag<VMConnectTargetElement>('vm-connect-target');
RenderingScheduler<VMConnectTargetElement> _r;
@@ -37,8 +35,8 @@
M.Target get target => _target;
bool get current => _current;
- factory VMConnectTargetElement(M.Target target, {bool current: false,
- RenderingQueue queue}) {
+ factory VMConnectTargetElement(M.Target target,
+ {bool current: false, RenderingQueue queue}) {
assert(target != null);
assert(current != null);
VMConnectTargetElement e = document.createElement(tag.name);
@@ -77,7 +75,8 @@
..text = current ? '${target.name} (Connected)' : '${target.name}'
..onClick.where(_filter).map(_toEvent).listen(_connect),
new ButtonElement()
- ..text = '✖ Remove' ..classes = ['delete-button']
+ ..text = '✖ Remove'
+ ..classes = ['delete-button']
..onClick.map(_toEvent).listen(_delete)
];
}
@@ -95,7 +94,10 @@
}
static bool _filter(MouseEvent event) {
- return !(event.button > 0 || event.metaKey || event.ctrlKey ||
- event.shiftKey || event.altKey);
+ return !(event.button > 0 ||
+ event.metaKey ||
+ event.ctrlKey ||
+ event.shiftKey ||
+ event.altKey);
}
}
diff --git a/runtime/observatory/lib/src/elements/vm_view.dart b/runtime/observatory/lib/src/elements/vm_view.dart
index 9b28c5e..b1ea5ea 100644
--- a/runtime/observatory/lib/src/elements/vm_view.dart
+++ b/runtime/observatory/lib/src/elements/vm_view.dart
@@ -20,15 +20,14 @@
import 'package:observatory/utils.dart';
class VMViewElement extends HtmlElement implements Renderable {
- static const tag = const Tag<VMViewElement>('vm-view',
- dependencies: const [
- IsolateSummaryElement.tag,
- NavTopMenuElement.tag,
- NavVMMenuElement.tag,
- NavRefreshElement.tag,
- NavNotifyElement.tag,
- ViewFooterElement.tag
- ]);
+ static const tag = const Tag<VMViewElement>('vm-view', dependencies: const [
+ IsolateSummaryElement.tag,
+ NavTopMenuElement.tag,
+ NavVMMenuElement.tag,
+ NavRefreshElement.tag,
+ NavNotifyElement.tag,
+ ViewFooterElement.tag
+ ]);
RenderingScheduler<VMViewElement> _r;
@@ -46,11 +45,13 @@
M.VMRef get vm => _vm;
M.NotificationRepository get notifications => _notifications;
- factory VMViewElement(M.VM vm, M.EventRepository events,
- M.NotificationRepository notifications,
- M.IsolateRepository isolates,
- M.ScriptRepository scripts,
- {RenderingQueue queue}) {
+ factory VMViewElement(
+ M.VM vm,
+ M.EventRepository events,
+ M.NotificationRepository notifications,
+ M.IsolateRepository isolates,
+ M.ScriptRepository scripts,
+ {RenderingQueue queue}) {
assert(vm != null);
assert(events != null);
assert(notifications != null);
@@ -96,94 +97,126 @@
new NavTopMenuElement(queue: _r.queue),
new NavVMMenuElement(_vm, _events, queue: _r.queue),
new NavRefreshElement(queue: _r.queue)
- ..onRefresh.listen((e) async {
- e.element.disabled = true;
- _r.dirty();
- }),
+ ..onRefresh.listen((e) async {
+ e.element.disabled = true;
+ _r.dirty();
+ }),
new NavNotifyElement(_notifications, queue: _r.queue)
]),
- new DivElement()..classes = ['content-centered-big']
+ new DivElement()
+ ..classes = ['content-centered-big']
..children = [
new HeadingElement.h1()..text = 'VM',
new HRElement(),
- new DivElement()..classes = ['memberList']
+ new DivElement()
+ ..classes = ['memberList']
..children = [
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'name',
- new DivElement()..classes = ['memberValue']
+ new DivElement()
+ ..classes = ['memberValue']
..text = _vm.displayName
],
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'version',
- new DivElement()..classes = ['memberValue']
+ new DivElement()
+ ..classes = ['memberValue']
..text = _vm.version
],
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'started at',
- new DivElement()..classes = ['memberValue']
+ new DivElement()
+ ..classes = ['memberValue']
..text = '${_vm.startTime}'
],
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'uptime',
- new DivElement()..classes = ['memberValue']
+ new DivElement()
+ ..classes = ['memberValue']
..text = '$uptime'
],
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'refreshed at',
- new DivElement()..classes = ['memberValue']
+ new DivElement()
+ ..classes = ['memberValue']
..text = '${new DateTime.now()}'
],
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'pid',
- new DivElement()..classes = ['memberValue']
+ new DivElement()
+ ..classes = ['memberValue']
..text = '${_vm.pid}'
],
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..text = 'peak memory',
- new DivElement()..classes = ['memberValue']
+ new DivElement()
+ ..classes = ['memberValue']
..text = Utils.formatSize(_vm.maxRSS)
],
new BRElement(),
- new DivElement()..classes = ['memberItem']
+ new DivElement()
+ ..classes = ['memberItem']
..children = [
- new DivElement()..classes = ['memberName']
+ new DivElement()
+ ..classes = ['memberName']
..children = [
new SpanElement()..text = 'see ',
new AnchorElement(href: Uris.flags())..text = 'flags'
],
- new DivElement()..classes = ['memberValue']
+ new DivElement()
+ ..classes = ['memberValue']
..children = [
new SpanElement()..text = 'view ',
- new AnchorElement(href: Uris.timeline())..text = 'timeline'
+ new AnchorElement(href: Uris.timeline())
+ ..text = 'timeline'
]
]
],
new BRElement(),
new HeadingElement.h1()..text = 'Isolates (${isolates.length})',
new HRElement(),
- new UListElement()..classes = ['list-group']
- ..children = isolates.expand((i) => [
- new LIElement()..classes = ['list-group-item']
- ..children = [
- new IsolateSummaryElement(i, _isolates, _events, _scripts,
- queue: _r.queue)
- ],
- new HRElement()
- ]).toList(),
+ new UListElement()
+ ..classes = ['list-group']
+ ..children = isolates
+ .expand((i) => [
+ new LIElement()
+ ..classes = ['list-group-item']
+ ..children = [
+ new IsolateSummaryElement(
+ i, _isolates, _events, _scripts,
+ queue: _r.queue)
+ ],
+ new HRElement()
+ ])
+ .toList(),
new ViewFooterElement(queue: _r.queue)
]
];
diff --git a/runtime/observatory/lib/src/heap_snapshot/heap_snapshot.dart b/runtime/observatory/lib/src/heap_snapshot/heap_snapshot.dart
index 06241f9..5345d8c 100644
--- a/runtime/observatory/lib/src/heap_snapshot/heap_snapshot.dart
+++ b/runtime/observatory/lib/src/heap_snapshot/heap_snapshot.dart
@@ -15,7 +15,7 @@
static Future sleep([Duration duration = const Duration(microseconds: 0)]) {
final Completer completer = new Completer();
- new Timer(duration, () => completer.complete() );
+ new Timer(duration, () => completer.complete());
return completer.future;
}
@@ -42,9 +42,8 @@
return progress.stream;
}
- Future<List<MergedVertex>> buildMergedVertices(S.Isolate isolate,
- ObjectGraph graph,
- signal) async {
+ Future<List<MergedVertex>> buildMergedVertices(
+ S.Isolate isolate, ObjectGraph graph, signal) async {
final cidToMergedVertex = {};
int count = 0;
@@ -99,12 +98,12 @@
}
List<Future<S.ServiceObject>> getMostRetained(S.Isolate isolate,
- {int classId, int limit}) {
+ {int classId, int limit}) {
var result = [];
- for (ObjectVertex v in graph.getMostRetained(classId: classId,
- limit: limit)) {
- result.add(isolate.getObjectByAddress(v.address)
- .then((S.ServiceObject obj) {
+ for (ObjectVertex v
+ in graph.getMostRetained(classId: classId, limit: limit)) {
+ result.add(
+ isolate.getObjectByAddress(v.address).then((S.ServiceObject obj) {
if (obj is S.HeapObject) {
obj.retainedSize = v.retainedSize;
} else {
@@ -131,24 +130,25 @@
});
}
}
+
Iterable<HeapSnapshotDominatorNode> _children;
Iterable<HeapSnapshotDominatorNode> get children {
if (_children != null) {
return _children;
} else {
- return _children = new List.unmodifiable(
- v.dominatorTreeChildren().map((v) {
- return new HeapSnapshotDominatorNode(isolate, v);
- })
- );
+ return _children =
+ new List.unmodifiable(v.dominatorTreeChildren().map((v) {
+ return new HeapSnapshotDominatorNode(isolate, v);
+ }));
}
}
+
int get retainedSize => v.retainedSize;
int get shallowSize => v.shallowSize;
HeapSnapshotDominatorNode(S.Isolate isolate, ObjectVertex vertex)
- : isolate = isolate,
- v = vertex;
+ : isolate = isolate,
+ v = vertex;
}
class MergedEdge {
@@ -180,10 +180,9 @@
// It is important to keep the template.
// https://github.com/dart-lang/sdk/issues/27144
return _inbounds = new List<HeapSnapshotClassInbound>.unmodifiable(
- incomingEdges.map((edge) {
- return new HeapSnapshotClassInbound(this, edge);
- })
- );
+ incomingEdges.map((edge) {
+ return new HeapSnapshotClassInbound(this, edge);
+ }));
}
}
@@ -195,10 +194,9 @@
// It is important to keep the template.
// https://github.com/dart-lang/sdk/issues/27144
return _outbounds = new List<HeapSnapshotClassOutbound>.unmodifiable(
- outgoingEdges.values.map((edge) {
- return new HeapSnapshotClassOutbound(this, edge);
- })
- );
+ outgoingEdges.values.map((edge) {
+ return new HeapSnapshotClassOutbound(this, edge);
+ }));
}
}
@@ -208,8 +206,9 @@
class HeapSnapshotClassInbound implements M.HeapSnapshotClassInbound {
final MergedVertex vertex;
final MergedEdge edge;
- S.Class get source => edge.sourceVertex != vertex ? edge.sourceVertex.clazz
- : edge.targetVertex.clazz;
+ S.Class get source => edge.sourceVertex != vertex
+ ? edge.sourceVertex.clazz
+ : edge.targetVertex.clazz;
int get count => edge.count;
int get shallowSize => edge.shallowSize;
int get retainedSize => edge.retainedSize;
@@ -220,8 +219,9 @@
class HeapSnapshotClassOutbound implements M.HeapSnapshotClassOutbound {
final MergedVertex vertex;
final MergedEdge edge;
- S.Class get target => edge.sourceVertex != vertex ? edge.sourceVertex.clazz
- : edge.targetVertex.clazz;
+ S.Class get target => edge.sourceVertex != vertex
+ ? edge.sourceVertex.clazz
+ : edge.targetVertex.clazz;
int get count => edge.count;
int get shallowSize => edge.shallowSize;
int get retainedSize => edge.retainedSize;
diff --git a/runtime/observatory/lib/src/models/objects/breakpoint.dart b/runtime/observatory/lib/src/models/objects/breakpoint.dart
index de9e65a..28ed56c 100644
--- a/runtime/observatory/lib/src/models/objects/breakpoint.dart
+++ b/runtime/observatory/lib/src/models/objects/breakpoint.dart
@@ -7,11 +7,14 @@
abstract class Breakpoint extends Object {
/// A number identifying this breakpoint to the user.
int get number;
+
/// Has this breakpoint been assigned to a specific program location?
bool get resolved;
+
/// [optional]Is this a breakpoint that was added synthetically as part of a
/// step OverAsyncSuspension resume command?
bool get isSyntheticAsyncContinuation;
+
/// SourceLocation when breakpoint is resolved, UnresolvedSourceLocation
/// when a breakpoint is not resolved.
Location get location;
diff --git a/runtime/observatory/lib/src/models/objects/class.dart b/runtime/observatory/lib/src/models/objects/class.dart
index a801a32..464956c 100644
--- a/runtime/observatory/lib/src/models/objects/class.dart
+++ b/runtime/observatory/lib/src/models/objects/class.dart
@@ -72,5 +72,4 @@
Iterable<ObjectRef> get samples;
}
-abstract class TopRetainedInstances {
-}
+abstract class TopRetainedInstances {}
diff --git a/runtime/observatory/lib/src/models/objects/code.dart b/runtime/observatory/lib/src/models/objects/code.dart
index 7345716..12d84df 100644
--- a/runtime/observatory/lib/src/models/objects/code.dart
+++ b/runtime/observatory/lib/src/models/objects/code.dart
@@ -4,13 +4,7 @@
part of models;
-enum CodeKind {
- dart,
- native,
- stub,
- tag,
- collected
-}
+enum CodeKind { dart, native, stub, tag, collected }
bool isSyntheticCode(CodeKind kind) {
switch (kind) {
diff --git a/runtime/observatory/lib/src/models/objects/error.dart b/runtime/observatory/lib/src/models/objects/error.dart
index 06c6e61..d59ab6c 100644
--- a/runtime/observatory/lib/src/models/objects/error.dart
+++ b/runtime/observatory/lib/src/models/objects/error.dart
@@ -7,11 +7,14 @@
enum ErrorKind {
/// The isolate has encountered an unhandled Dart exception.
unhandledException,
+
/// The isolate has encountered a Dart language error in the program.
languageError,
+
/// The isolate has encounted an internal error. These errors should be
/// reported as bugs.
internalError,
+
/// The isolate has been terminated by an external source.
terminationError
}
@@ -21,6 +24,4 @@
String get message;
}
-abstract class Error extends Object implements ErrorRef {
-
-}
+abstract class Error extends Object implements ErrorRef {}
diff --git a/runtime/observatory/lib/src/models/objects/event.dart b/runtime/observatory/lib/src/models/objects/event.dart
index 65f2248..18f491e 100644
--- a/runtime/observatory/lib/src/models/objects/event.dart
+++ b/runtime/observatory/lib/src/models/objects/event.dart
@@ -11,9 +11,12 @@
/// event was created.
DateTime get timestamp;
static bool isPauseEvent(Event event) {
- return event is PauseStartEvent || event is PauseExitEvent ||
- event is PauseBreakpointEvent || event is PauseInterruptedEvent ||
- event is PauseExceptionEvent || event is NoneEvent;
+ return event is PauseStartEvent ||
+ event is PauseExitEvent ||
+ event is PauseBreakpointEvent ||
+ event is PauseInterruptedEvent ||
+ event is PauseExceptionEvent ||
+ event is NoneEvent;
}
}
@@ -60,6 +63,7 @@
abstract class PauseBreakpointEvent extends DebugEvent {
/// [optional] The breakpoint at which we are currently paused.
Breakpoint get breakpoint;
+
/// The list of breakpoints at which we are currently paused
/// for a PauseBreakpoint event.
///
@@ -69,6 +73,7 @@
/// If there is more than one breakpoint set at the program position,
/// then all of them will be provided.
Iterable<Breakpoint> get pauseBreakpoints;
+
/// The top stack frame associated with this event.
Frame get topFrame;
bool get atAsyncSuspension;
@@ -78,6 +83,7 @@
/// [optional] The top stack frame associated with this event. There will be
/// no top frame if the isolate is idle (waiting in the message loop).
Frame get topFrame;
+
/// Is the isolate paused at an await, yield, or yield* statement?
bool get atAsyncSuspension;
}
@@ -85,6 +91,7 @@
abstract class PauseExceptionEvent extends DebugEvent {
/// The top stack frame associated with this event.
Frame get topFrame;
+
/// The exception associated with this event
InstanceRef get exception;
}
@@ -126,8 +133,10 @@
abstract class ExtensionEvent extends Event {
/// The isolate with which this event is associated.
IsolateRef get isolate;
+
/// The extension event kind.
String get extensionKind;
+
/// The extension event data.
ExtensionData get extensionData;
}
@@ -143,6 +152,7 @@
abstract class TimelineEventsEvent extends Event {
/// The isolate with which this event is associated.
IsolateRef get isolate;
+
/// An array of TimelineEvents
Iterable<TimelineEvent> get timelineEvents;
}
diff --git a/runtime/observatory/lib/src/models/objects/field.dart b/runtime/observatory/lib/src/models/objects/field.dart
index 188f223..8ac61ee 100644
--- a/runtime/observatory/lib/src/models/objects/field.dart
+++ b/runtime/observatory/lib/src/models/objects/field.dart
@@ -28,11 +28,7 @@
bool get isStatic;
}
-enum GuardClassKind {
- unknown,
- single,
- dynamic
-}
+enum GuardClassKind { unknown, single, dynamic }
abstract class Field extends Object implements FieldRef {
/// [optional] The value of this field, if the field is static.
diff --git a/runtime/observatory/lib/src/models/objects/function.dart b/runtime/observatory/lib/src/models/objects/function.dart
index 0b4ef60..2352b71 100644
--- a/runtime/observatory/lib/src/models/objects/function.dart
+++ b/runtime/observatory/lib/src/models/objects/function.dart
@@ -43,9 +43,7 @@
isDartFunction(kind) || isStubFunction(kind);
String getFunctionFullName(FunctionRef function) {
- var content = <String>[
- function.name
- ];
+ var content = <String>[function.name];
ObjectRef owner = function.dartOwner;
while (owner is FunctionRef) {
FunctionRef function = (owner as FunctionRef);
@@ -82,8 +80,10 @@
/// The compiled code associated with this function. [optional]
CodeRef get code;
+
/// [optional]
CodeRef get unoptimizedCode;
+
/// [optional]
FieldRef get field;
int get usageCounter;
diff --git a/runtime/observatory/lib/src/models/objects/inbound_references.dart b/runtime/observatory/lib/src/models/objects/inbound_references.dart
index 13c3c03..ea18744 100644
--- a/runtime/observatory/lib/src/models/objects/inbound_references.dart
+++ b/runtime/observatory/lib/src/models/objects/inbound_references.dart
@@ -10,10 +10,13 @@
abstract class InboundReference {
ObjectRef get source;
+
/// [optional]
ObjectRef get parentField;
+
/// [optional]
int get parentListIndex;
+
/// [optional]
int get parentWordOffset;
}
diff --git a/runtime/observatory/lib/src/models/objects/instance.dart b/runtime/observatory/lib/src/models/objects/instance.dart
index 8401684..e85e861f 100644
--- a/runtime/observatory/lib/src/models/objects/instance.dart
+++ b/runtime/observatory/lib/src/models/objects/instance.dart
@@ -7,87 +7,120 @@
enum InstanceKind {
/// A general instance of the Dart class Object.
plainInstance,
+
/// null instance.
vNull,
+
/// true or false.
bool,
+
/// An instance of the Dart class double.
double,
+
/// An instance of the Dart class int.
int,
+
/// An instance of the Dart class String.
string,
+
/// An instance of the built-in VM List implementation. User-defined
/// Lists will be PlainInstance.
list,
+
/// An instance of the built-in VM Map implementation. User-defined
/// Maps will be PlainInstance.
map,
+
/// Vector instance kinds.
float32x4,
+
/// Vector instance kinds.
float64x2,
+
/// Vector instance kinds.
int32x4,
+
/// An instance of the built-in VM TypedData implementations. User-defined
/// TypedDatas will be PlainInstance.
uint8ClampedList,
+
/// An instance of the built-in VM TypedData implementations. User-defined
/// TypedDatas will be PlainInstance.
uint8List,
+
/// An instance of the built-in VM TypedData implementations. User-defined
/// TypedDatas will be PlainInstance.
uint16List,
+
/// An instance of the built-in VM TypedData implementations. User-defined
/// TypedDatas will be PlainInstance.
uint32List,
+
/// An instance of the built-in VM TypedData implementations. User-defined
/// TypedDatas will be PlainInstance.
uint64List,
+
/// An instance of the built-in VM TypedData implementations. User-defined
/// TypedDatas will be PlainInstance.
int8List,
+
/// An instance of the built-in VM TypedData implementations. User-defined
/// TypedDatas will be PlainInstance.
int16List,
+
/// An instance of the built-in VM TypedData implementations. User-defined
/// TypedDatas will be PlainInstance.
int32List,
+
/// An instance of the built-in VM TypedData implementations. User-defined
/// TypedDatas will be PlainInstance.
int64List,
+
/// An instance of the built-in VM TypedData implementations. User-defined
/// TypedDatas will be PlainInstance.
float32List,
+
/// An instance of the built-in VM TypedData implementations. User-defined
/// TypedDatas will be PlainInstance.
float64List,
+
/// An instance of the built-in VM TypedData implementations. User-defined
/// TypedDatas will be PlainInstance.
int32x4List,
+
/// An instance of the built-in VM TypedData implementations. User-defined
/// TypedDatas will be PlainInstance.
float32x4List,
+
/// An instance of the built-in VM TypedData implementations. User-defined
/// TypedDatas will be PlainInstance.
float64x2List,
+
/// An instance of the Dart class StackTrace.
stackTrace,
+
/// An instance of the built-in VM Closure implementation. User-defined
/// Closures will be PlainInstance.
closure,
+
/// An instance of the Dart class MirrorReference.
mirrorReference,
+
/// An instance of the Dart class RegExp.
regExp,
+
/// An instance of the Dart class WeakProperty.
weakProperty,
+
/// An instance of the Dart class Type.
type,
+
/// An instance of the Dart class TypeParameter.
typeParameter,
+
/// An instance of the Dart class TypeRef.
typeRef,
+
/// An instance of the Dart class BoundedType.
boundedType,
}
@@ -110,7 +143,7 @@
case InstanceKind.float64x2List:
return true;
default:
- return false;
+ return false;
}
}
@@ -121,7 +154,7 @@
case InstanceKind.int32x4:
return true;
default:
- return false;
+ return false;
}
}
@@ -133,7 +166,7 @@
case InstanceKind.boundedType:
return true;
default:
- return false;
+ return false;
}
}
diff --git a/runtime/observatory/lib/src/models/objects/isolate.dart b/runtime/observatory/lib/src/models/objects/isolate.dart
index 9b34828..f114941 100644
--- a/runtime/observatory/lib/src/models/objects/isolate.dart
+++ b/runtime/observatory/lib/src/models/objects/isolate.dart
@@ -16,12 +16,7 @@
String get name;
}
-enum IsolateStatus {
- loading,
- idle,
- running,
- paused
-}
+enum IsolateStatus { loading, idle, running, paused }
abstract class Isolate extends IsolateRef {
/// The time that the VM started in milliseconds since the epoch.
diff --git a/runtime/observatory/lib/src/models/objects/library.dart b/runtime/observatory/lib/src/models/objects/library.dart
index b0046fb..83bab54 100644
--- a/runtime/observatory/lib/src/models/objects/library.dart
+++ b/runtime/observatory/lib/src/models/objects/library.dart
@@ -39,6 +39,7 @@
bool get isImport;
bool get isDeferred;
LibraryRef get target;
+
/// [optional]
String get prefix;
}
diff --git a/runtime/observatory/lib/src/models/objects/notification.dart b/runtime/observatory/lib/src/models/objects/notification.dart
index 3a2ae9a..1f46766 100644
--- a/runtime/observatory/lib/src/models/objects/notification.dart
+++ b/runtime/observatory/lib/src/models/objects/notification.dart
@@ -6,12 +6,13 @@
abstract class Notification {}
-abstract class ExceptionNotification implements Notification{
- Exception get exception;
+abstract class ExceptionNotification implements Notification {
+ get exception;
+
/// [optional]
StackTrace get stacktrace;
}
-abstract class EventNotification implements Notification{
+abstract class EventNotification implements Notification {
Event get event;
}
diff --git a/runtime/observatory/lib/src/models/objects/objectpool.dart b/runtime/observatory/lib/src/models/objects/objectpool.dart
index 1f0b738..fb99d60 100644
--- a/runtime/observatory/lib/src/models/objects/objectpool.dart
+++ b/runtime/observatory/lib/src/models/objects/objectpool.dart
@@ -12,11 +12,7 @@
Iterable<ObjectPoolEntry> get entries;
}
-enum ObjectPoolEntryKind {
- object,
- immediate,
- nativeEntry
-}
+enum ObjectPoolEntryKind { object, immediate, nativeEntry }
abstract class ObjectPoolEntry {
int get offset;
diff --git a/runtime/observatory/lib/src/models/objects/retaining_path.dart b/runtime/observatory/lib/src/models/objects/retaining_path.dart
index d16112e..f68eecd 100644
--- a/runtime/observatory/lib/src/models/objects/retaining_path.dart
+++ b/runtime/observatory/lib/src/models/objects/retaining_path.dart
@@ -10,11 +10,14 @@
abstract class RetainingPathItem {
ObjectRef get source;
+
/// [optional]
/// FieldRef or InstanceRef (null)
ObjectRef get parentField;
+
/// [optional]
int get parentListIndex;
+
/// [optional]
int get parentWordOffset;
}
diff --git a/runtime/observatory/lib/src/models/objects/sample_profile.dart b/runtime/observatory/lib/src/models/objects/sample_profile.dart
index cd0a805..1a71bc2 100644
--- a/runtime/observatory/lib/src/models/objects/sample_profile.dart
+++ b/runtime/observatory/lib/src/models/objects/sample_profile.dart
@@ -4,10 +4,7 @@
part of models;
-enum ProfileTreeDirection {
- inclusive,
- exclusive
-}
+enum ProfileTreeDirection { inclusive, exclusive }
abstract class SampleProfile {
int get sampleCount;
diff --git a/runtime/observatory/lib/src/models/objects/sentinel.dart b/runtime/observatory/lib/src/models/objects/sentinel.dart
index f45e431..ca6747a 100644
--- a/runtime/observatory/lib/src/models/objects/sentinel.dart
+++ b/runtime/observatory/lib/src/models/objects/sentinel.dart
@@ -7,14 +7,19 @@
enum SentinelKind {
/// Indicates that the object referred to has been collected by the GC.
collected,
+
/// Indicates that an object id has expired.
expired,
+
/// Indicates that a variable or field has not been initialized.
notInitialized,
+
/// Indicates that a variable or field is in the process of being initialized.
initializing,
+
/// Indicates that a variable has been eliminated by the optimizing compiler.
optimizedOut,
+
/// Reserved for future use.
free,
}
diff --git a/runtime/observatory/lib/src/models/objects/source_location.dart b/runtime/observatory/lib/src/models/objects/source_location.dart
index 5fc8b6c..1e1188b 100644
--- a/runtime/observatory/lib/src/models/objects/source_location.dart
+++ b/runtime/observatory/lib/src/models/objects/source_location.dart
@@ -7,6 +7,7 @@
abstract class Location {
/// The script containing the source location.
ScriptRef get script;
+
/// The last token of the location if this is a range. [optional]
int get tokenPos;
}
@@ -14,6 +15,7 @@
abstract class SourceLocation implements Location {
/// The last token of the location if this is a range.
int get tokenPos;
+
/// The last token of the location if this is a range. [optional]
int get endTokenPos;
}
@@ -22,9 +24,11 @@
// [optional] The uri of the script containing the source location if the
// script has yet to be loaded.
String get scriptUri;
+
/// [optional] An approximate line number for the source location. This may
/// change when the location is resolved.
int get line;
+
/// [optional] An approximate column number for the source location. This may
/// change when the location is resolved.
int get column;
diff --git a/runtime/observatory/lib/src/models/repositories/allocation_profile.dart b/runtime/observatory/lib/src/models/repositories/allocation_profile.dart
index 5b917ef..2a760cf 100644
--- a/runtime/observatory/lib/src/models/repositories/allocation_profile.dart
+++ b/runtime/observatory/lib/src/models/repositories/allocation_profile.dart
@@ -5,6 +5,6 @@
part of models;
abstract class AllocationProfileRepository {
- Future<AllocationProfile> get(IsolateRef isolate, {bool gc: false,
- bool reset: false});
+ Future<AllocationProfile> get(IsolateRef isolate,
+ {bool gc: false, bool reset: false});
}
diff --git a/runtime/observatory/lib/src/models/repositories/breakpoint.dart b/runtime/observatory/lib/src/models/repositories/breakpoint.dart
index fcf9906..1727dd3 100644
--- a/runtime/observatory/lib/src/models/repositories/breakpoint.dart
+++ b/runtime/observatory/lib/src/models/repositories/breakpoint.dart
@@ -4,7 +4,7 @@
part of models;
-abstract class BreakpointRepository{
+abstract class BreakpointRepository {
Future addOnActivation(IsolateRef isolate, Instance closure);
Future remove(IsolateRef isolate, Breakpoint breakpoint);
}
diff --git a/runtime/observatory/lib/src/models/repositories/class.dart b/runtime/observatory/lib/src/models/repositories/class.dart
index 6394377..3695527 100644
--- a/runtime/observatory/lib/src/models/repositories/class.dart
+++ b/runtime/observatory/lib/src/models/repositories/class.dart
@@ -4,7 +4,7 @@
part of models;
-abstract class ClassRepository{
+abstract class ClassRepository {
Future<Class> getObject(IsolateRef isolate);
Future<Class> get(IsolateRef isolate, String id);
}
diff --git a/runtime/observatory/lib/src/models/repositories/context.dart b/runtime/observatory/lib/src/models/repositories/context.dart
index 7565d68..1c3fcf9 100644
--- a/runtime/observatory/lib/src/models/repositories/context.dart
+++ b/runtime/observatory/lib/src/models/repositories/context.dart
@@ -4,6 +4,6 @@
part of models;
-abstract class ContextRepository{
+abstract class ContextRepository {
Future<Context> get(IsolateRef isolate, String id);
}
diff --git a/runtime/observatory/lib/src/models/repositories/eval.dart b/runtime/observatory/lib/src/models/repositories/eval.dart
index af38e4e..e127d84 100644
--- a/runtime/observatory/lib/src/models/repositories/eval.dart
+++ b/runtime/observatory/lib/src/models/repositories/eval.dart
@@ -4,7 +4,7 @@
part of models;
-abstract class EvalRepository{
- Future<ObjectRef> evaluate(IsolateRef isolate, ObjectRef context,
- String expression);
+abstract class EvalRepository {
+ Future<ObjectRef> evaluate(
+ IsolateRef isolate, ObjectRef context, String expression);
}
diff --git a/runtime/observatory/lib/src/models/repositories/field.dart b/runtime/observatory/lib/src/models/repositories/field.dart
index 8412ac9..6892b17 100644
--- a/runtime/observatory/lib/src/models/repositories/field.dart
+++ b/runtime/observatory/lib/src/models/repositories/field.dart
@@ -4,6 +4,6 @@
part of models;
-abstract class FieldRepository{
+abstract class FieldRepository {
Future<Field> get(IsolateRef isolate, String id);
}
diff --git a/runtime/observatory/lib/src/models/repositories/function.dart b/runtime/observatory/lib/src/models/repositories/function.dart
index 8ae36f3..38b7cc4 100644
--- a/runtime/observatory/lib/src/models/repositories/function.dart
+++ b/runtime/observatory/lib/src/models/repositories/function.dart
@@ -4,6 +4,6 @@
part of models;
-abstract class FunctionRepository{
+abstract class FunctionRepository {
Future<Function> get(IsolateRef isolate, String id);
}
diff --git a/runtime/observatory/lib/src/models/repositories/heap_snapshot.dart b/runtime/observatory/lib/src/models/repositories/heap_snapshot.dart
index 66dc5b8..da71fe9 100644
--- a/runtime/observatory/lib/src/models/repositories/heap_snapshot.dart
+++ b/runtime/observatory/lib/src/models/repositories/heap_snapshot.dart
@@ -4,11 +4,7 @@
part of models;
-enum HeapSnapshotLoadingStatus {
- fetching,
- loading,
- loaded
-}
+enum HeapSnapshotLoadingStatus { fetching, loading, loaded }
bool isHeapSnapshotProgressRunning(HeapSnapshotLoadingStatus status) {
switch (status) {
@@ -35,5 +31,5 @@
abstract class HeapSnapshotRepository {
Stream<HeapSnapshotLoadingProgressEvent> get(IsolateRef isolate,
- {bool gc: false});
+ {bool gc: false});
}
diff --git a/runtime/observatory/lib/src/models/repositories/instance.dart b/runtime/observatory/lib/src/models/repositories/instance.dart
index ab30965..4da307f 100644
--- a/runtime/observatory/lib/src/models/repositories/instance.dart
+++ b/runtime/observatory/lib/src/models/repositories/instance.dart
@@ -4,6 +4,6 @@
part of models;
-abstract class InstanceRepository{
+abstract class InstanceRepository {
Future<Instance> get(IsolateRef isolate, String id, {int count});
}
diff --git a/runtime/observatory/lib/src/models/repositories/isolate.dart b/runtime/observatory/lib/src/models/repositories/isolate.dart
index 9eed647..c6e97f1 100644
--- a/runtime/observatory/lib/src/models/repositories/isolate.dart
+++ b/runtime/observatory/lib/src/models/repositories/isolate.dart
@@ -4,7 +4,7 @@
part of models;
-abstract class IsolateRepository{
+abstract class IsolateRepository {
Future<Isolate> get(IsolateRef isolate);
Future reloadSources(IsolateRef isolate);
}
diff --git a/runtime/observatory/lib/src/models/repositories/megamorphiccache.dart b/runtime/observatory/lib/src/models/repositories/megamorphiccache.dart
index 9734e3e..cfddc73 100644
--- a/runtime/observatory/lib/src/models/repositories/megamorphiccache.dart
+++ b/runtime/observatory/lib/src/models/repositories/megamorphiccache.dart
@@ -4,6 +4,6 @@
part of models;
-abstract class MegamorphicCacheRepository{
+abstract class MegamorphicCacheRepository {
Future<MegamorphicCache> get(IsolateRef isolate, String id);
}
diff --git a/runtime/observatory/lib/src/models/repositories/metric.dart b/runtime/observatory/lib/src/models/repositories/metric.dart
index a009fe1..ee10fdb 100644
--- a/runtime/observatory/lib/src/models/repositories/metric.dart
+++ b/runtime/observatory/lib/src/models/repositories/metric.dart
@@ -4,20 +4,9 @@
part of models;
-enum MetricBufferSize {
- n10samples,
- n100samples,
- n1000samples
-}
+enum MetricBufferSize { n10samples, n100samples, n1000samples }
-enum MetricSamplingRate {
- off,
- e100ms,
- e1s,
- e2s,
- e4s,
- e8s
-}
+enum MetricSamplingRate { off, e100ms, e1s, e2s, e4s, e8s }
abstract class MetricRepository {
Future<Iterable<Metric>> list(IsolateRef isolate);
diff --git a/runtime/observatory/lib/src/models/repositories/object.dart b/runtime/observatory/lib/src/models/repositories/object.dart
index 2827da0..61d04b5 100644
--- a/runtime/observatory/lib/src/models/repositories/object.dart
+++ b/runtime/observatory/lib/src/models/repositories/object.dart
@@ -4,6 +4,6 @@
part of models;
-abstract class ObjectRepository{
+abstract class ObjectRepository {
Future<Object> get(IsolateRef isolate, String id);
}
diff --git a/runtime/observatory/lib/src/models/repositories/sample_profile.dart b/runtime/observatory/lib/src/models/repositories/sample_profile.dart
index 075203f..9f8e80e 100644
--- a/runtime/observatory/lib/src/models/repositories/sample_profile.dart
+++ b/runtime/observatory/lib/src/models/repositories/sample_profile.dart
@@ -4,20 +4,9 @@
part of models;
-enum SampleProfileTag {
- userVM,
- userOnly,
- vmUser,
- vmOnly,
- none
-}
+enum SampleProfileTag { userVM, userOnly, vmUser, vmOnly, none }
-enum SampleProfileLoadingStatus {
- disabled,
- fetching,
- loading,
- loaded
-}
+enum SampleProfileLoadingStatus { disabled, fetching, loading, loaded }
bool isSampleProcessRunning(SampleProfileLoadingStatus status) {
switch (status) {
@@ -42,13 +31,14 @@
}
abstract class ClassSampleProfileRepository {
- Stream<SampleProfileLoadingProgressEvent> get(IsolateRef isolate,
- ClassRef cls, SampleProfileTag tag);
+ Stream<SampleProfileLoadingProgressEvent> get(
+ IsolateRef isolate, ClassRef cls, SampleProfileTag tag);
Future enable(IsolateRef isolate, ClassRef cls);
Future disable(IsolateRef isolate, ClassRef cls);
}
abstract class IsolateSampleProfileRepository {
- Stream<SampleProfileLoadingProgressEvent> get(IsolateRef isolate,
- SampleProfileTag tag, {bool clear: false, bool forceFetch: false});
+ Stream<SampleProfileLoadingProgressEvent> get(
+ IsolateRef isolate, SampleProfileTag tag,
+ {bool clear: false, bool forceFetch: false});
}
diff --git a/runtime/observatory/lib/src/repositories/allocation_profile.dart b/runtime/observatory/lib/src/repositories/allocation_profile.dart
index 4b1a73d..aedfb3a 100644
--- a/runtime/observatory/lib/src/repositories/allocation_profile.dart
+++ b/runtime/observatory/lib/src/repositories/allocation_profile.dart
@@ -7,8 +7,8 @@
class AllocationProfileRepository implements M.AllocationProfileRepository {
static const _api = '_getAllocationProfile';
- Future<M.AllocationProfile> get(M.IsolateRef i, {bool gc: false,
- bool reset: false}) async {
+ Future<M.AllocationProfile> get(M.IsolateRef i,
+ {bool gc: false, bool reset: false}) async {
assert(gc != null);
assert(reset != null);
S.Isolate isolate = i as S.Isolate;
diff --git a/runtime/observatory/lib/src/repositories/breakpoint.dart b/runtime/observatory/lib/src/repositories/breakpoint.dart
index db1e9c7..99a66ca 100644
--- a/runtime/observatory/lib/src/repositories/breakpoint.dart
+++ b/runtime/observatory/lib/src/repositories/breakpoint.dart
@@ -5,12 +5,13 @@
part of repositories;
class BreakpointRepository extends M.BreakpointRepository {
- Future addOnActivation(M.IsolateRef i, M.Instance closure) async{
+ Future addOnActivation(M.IsolateRef i, M.Instance closure) async {
S.Isolate isolate = i as S.Isolate;
assert(isolate != null);
await isolate.addBreakOnActivation(closure);
}
- Future remove(M.IsolateRef i, M.Breakpoint breakpoint) async{
+
+ Future remove(M.IsolateRef i, M.Breakpoint breakpoint) async {
S.Isolate isolate = i as S.Isolate;
assert(isolate != null);
await isolate.removeBreakpoint(breakpoint);
diff --git a/runtime/observatory/lib/src/repositories/class.dart b/runtime/observatory/lib/src/repositories/class.dart
index 4d80729..5f8f391 100644
--- a/runtime/observatory/lib/src/repositories/class.dart
+++ b/runtime/observatory/lib/src/repositories/class.dart
@@ -10,6 +10,7 @@
assert(isolate != null);
return isolate.getClassHierarchy();
}
+
Future<M.Class> get(M.IsolateRef i, String id) async {
final isolate = i as S.Isolate;
assert(isolate != null);
diff --git a/runtime/observatory/lib/src/repositories/context.dart b/runtime/observatory/lib/src/repositories/context.dart
index 5bb12e6..a861f6a 100644
--- a/runtime/observatory/lib/src/repositories/context.dart
+++ b/runtime/observatory/lib/src/repositories/context.dart
@@ -5,7 +5,7 @@
part of repositories;
class ContextRepository extends M.ContextRepository {
- Future<M.Context> get(M.IsolateRef i, String id) async{
+ Future<M.Context> get(M.IsolateRef i, String id) async {
S.Isolate isolate = i as S.Isolate;
assert(isolate != null);
return (await isolate.getObject(id)) as S.Context;
diff --git a/runtime/observatory/lib/src/repositories/event.dart b/runtime/observatory/lib/src/repositories/event.dart
index 6995f16..4c07f94 100644
--- a/runtime/observatory/lib/src/repositories/event.dart
+++ b/runtime/observatory/lib/src/repositories/event.dart
@@ -36,56 +36,64 @@
EventRepository() : this._(new StreamController.broadcast());
- EventRepository._(StreamController controller) : this.__(controller,
- controller.stream.where((e) => e is M.VMEvent),
- controller.stream.where((e) => e is M.IsolateEvent),
- controller.stream.where((e) => e is M.DebugEvent),
- controller.stream.where((e) => e is M.GCEvent),
- controller.stream.where((e) => e is M.LoggingEvent),
- controller.stream.where((e) => e is M.ExtensionEvent),
- controller.stream.where((e) => e is M.TimelineEventsEvent),
- controller.stream.where((e) => e is M.ConnectionClosedEvent));
+ EventRepository._(StreamController controller)
+ : this.__(
+ controller,
+ controller.stream.where((e) => e is M.VMEvent),
+ controller.stream.where((e) => e is M.IsolateEvent),
+ controller.stream.where((e) => e is M.DebugEvent),
+ controller.stream.where((e) => e is M.GCEvent),
+ controller.stream.where((e) => e is M.LoggingEvent),
+ controller.stream.where((e) => e is M.ExtensionEvent),
+ controller.stream.where((e) => e is M.TimelineEventsEvent),
+ controller.stream.where((e) => e is M.ConnectionClosedEvent));
- EventRepository.__(StreamController controller,
- Stream<M.VMEvent> onVMEvent, Stream<M.IsolateEvent> onIsolateEvent,
- Stream<M.DebugEvent> onDebugEvent, Stream<M.GCEvent> onGCEvent,
- Stream<M.LoggingEvent> onLoggingEvent,
- Stream<M.ExtensionEvent> onExtensionEvent,
- Stream<M.TimelineEventsEvent> onTimelineEvents,
- Stream<M.ConnectionClosedEvent> onConnectionClosed)
- : _onEvent = controller,
- onVMEvent = onVMEvent,
- onVMUpdate = onVMEvent.where((e) => e is M.VMUpdateEvent),
- onIsolateEvent = onIsolateEvent,
- onIsolateStart = onIsolateEvent.where((e) => e is M.IsolateStartEvent),
- onIsolateRunnable =
- onIsolateEvent.where((e) => e is M.IsolateRunnableEvent),
- onIsolateExit = onIsolateEvent.where((e) => e is M.IsolateExitEvent),
- onIsolateUpdate = onIsolateEvent.where((e) => e is M.IsolateUpdateEvent),
- onIsolateReload = onIsolateEvent.where((e) => e is M.IsolateReloadEvent),
- onServiceExtensionAdded =
- onIsolateEvent.where((e) => e is M.IsolateReloadEvent),
- onDebugEvent = onDebugEvent,
- onPauseStart = onDebugEvent.where((e) => e is M.PauseStartEvent),
- onPauseExit = onDebugEvent.where((e) => e is M.PauseExitEvent),
- onPauseBreakpoint =
- onDebugEvent.where((e) => e is M.PauseBreakpointEvent),
- onPauseInterrupted =
- onDebugEvent.where((e) => e is M.PauseInterruptedEvent),
- onPauseException = onDebugEvent.where((e) => e is M.PauseExceptionEvent),
- onResume = onDebugEvent.where((e) => e is M.ResumeEvent),
- onBreakpointAdded =
- onDebugEvent.where((e) => e is M.BreakpointAddedEvent),
- onBreakpointResolved =
- onDebugEvent.where((e) => e is M.BreakpointResolvedEvent),
- onBreakpointRemoved =
- onDebugEvent.where((e) => e is M.BreakpointRemovedEvent),
- onInspect = onDebugEvent.where((e) => e is M.InspectEvent),
- onGCEvent = onGCEvent,
- onLoggingEvent = onLoggingEvent,
- onExtensionEvent = onExtensionEvent,
- onTimelineEvents = onTimelineEvents,
- onConnectionClosed = onConnectionClosed;
+ EventRepository.__(
+ StreamController controller,
+ Stream<M.VMEvent> onVMEvent,
+ Stream<M.IsolateEvent> onIsolateEvent,
+ Stream<M.DebugEvent> onDebugEvent,
+ Stream<M.GCEvent> onGCEvent,
+ Stream<M.LoggingEvent> onLoggingEvent,
+ Stream<M.ExtensionEvent> onExtensionEvent,
+ Stream<M.TimelineEventsEvent> onTimelineEvents,
+ Stream<M.ConnectionClosedEvent> onConnectionClosed)
+ : _onEvent = controller,
+ onVMEvent = onVMEvent,
+ onVMUpdate = onVMEvent.where((e) => e is M.VMUpdateEvent),
+ onIsolateEvent = onIsolateEvent,
+ onIsolateStart = onIsolateEvent.where((e) => e is M.IsolateStartEvent),
+ onIsolateRunnable =
+ onIsolateEvent.where((e) => e is M.IsolateRunnableEvent),
+ onIsolateExit = onIsolateEvent.where((e) => e is M.IsolateExitEvent),
+ onIsolateUpdate =
+ onIsolateEvent.where((e) => e is M.IsolateUpdateEvent),
+ onIsolateReload =
+ onIsolateEvent.where((e) => e is M.IsolateReloadEvent),
+ onServiceExtensionAdded =
+ onIsolateEvent.where((e) => e is M.IsolateReloadEvent),
+ onDebugEvent = onDebugEvent,
+ onPauseStart = onDebugEvent.where((e) => e is M.PauseStartEvent),
+ onPauseExit = onDebugEvent.where((e) => e is M.PauseExitEvent),
+ onPauseBreakpoint =
+ onDebugEvent.where((e) => e is M.PauseBreakpointEvent),
+ onPauseInterrupted =
+ onDebugEvent.where((e) => e is M.PauseInterruptedEvent),
+ onPauseException =
+ onDebugEvent.where((e) => e is M.PauseExceptionEvent),
+ onResume = onDebugEvent.where((e) => e is M.ResumeEvent),
+ onBreakpointAdded =
+ onDebugEvent.where((e) => e is M.BreakpointAddedEvent),
+ onBreakpointResolved =
+ onDebugEvent.where((e) => e is M.BreakpointResolvedEvent),
+ onBreakpointRemoved =
+ onDebugEvent.where((e) => e is M.BreakpointRemovedEvent),
+ onInspect = onDebugEvent.where((e) => e is M.InspectEvent),
+ onGCEvent = onGCEvent,
+ onLoggingEvent = onLoggingEvent,
+ onExtensionEvent = onExtensionEvent,
+ onTimelineEvents = onTimelineEvents,
+ onConnectionClosed = onConnectionClosed;
void add(M.Event e) {
_onEvent.add(e);
diff --git a/runtime/observatory/lib/src/repositories/field.dart b/runtime/observatory/lib/src/repositories/field.dart
index fce37d0..932a84d 100644
--- a/runtime/observatory/lib/src/repositories/field.dart
+++ b/runtime/observatory/lib/src/repositories/field.dart
@@ -5,7 +5,7 @@
part of repositories;
class FieldRepository extends M.FieldRepository {
- Future<M.Field> get(M.IsolateRef i, String id) async{
+ Future<M.Field> get(M.IsolateRef i, String id) async {
S.Isolate isolate = i as S.Isolate;
assert(isolate != null);
return (await isolate.getObject(id)) as S.Field;
diff --git a/runtime/observatory/lib/src/repositories/flag.dart b/runtime/observatory/lib/src/repositories/flag.dart
index 0072c0e..b1b5349 100644
--- a/runtime/observatory/lib/src/repositories/flag.dart
+++ b/runtime/observatory/lib/src/repositories/flag.dart
@@ -21,15 +21,13 @@
FlagsRepository(this.vm);
- Future<Iterable<Flag>> list() async{
+ Future<Iterable<Flag>> list() async {
List<Map> flags = ((await vm.getFlagList()) as S.ServiceMap)['flags'];
return flags.map(_toFlag);
}
- static _toFlag(Map map){
- return new Flag(map['name'],
- map['comment'],
- map['modified'],
- map['valueAsString']);
+ static _toFlag(Map map) {
+ return new Flag(
+ map['name'], map['comment'], map['modified'], map['valueAsString']);
}
}
diff --git a/runtime/observatory/lib/src/repositories/function.dart b/runtime/observatory/lib/src/repositories/function.dart
index 2ab1682..5906a2a 100644
--- a/runtime/observatory/lib/src/repositories/function.dart
+++ b/runtime/observatory/lib/src/repositories/function.dart
@@ -5,7 +5,7 @@
part of repositories;
class FunctionRepository extends M.FunctionRepository {
- Future<M.Function> get(M.IsolateRef i, String id) async{
+ Future<M.Function> get(M.IsolateRef i, String id) async {
S.Isolate isolate = i as S.Isolate;
assert(isolate != null);
return (await isolate.getObject(id)) as S.ServiceFunction;
diff --git a/runtime/observatory/lib/src/repositories/heap_snapshot.dart b/runtime/observatory/lib/src/repositories/heap_snapshot.dart
index 0489197..e56b352 100644
--- a/runtime/observatory/lib/src/repositories/heap_snapshot.dart
+++ b/runtime/observatory/lib/src/repositories/heap_snapshot.dart
@@ -5,7 +5,7 @@
part of repositories;
class HeapSnapshotLoadingProgressEvent
- implements M.HeapSnapshotLoadingProgressEvent {
+ implements M.HeapSnapshotLoadingProgressEvent {
final HeapSnapshotLoadingProgress progress;
HeapSnapshotLoadingProgressEvent(this.progress);
}
@@ -13,8 +13,7 @@
class HeapSnapshotLoadingProgress extends M.HeapSnapshotLoadingProgress {
StreamController<HeapSnapshotLoadingProgressEvent> _onProgress =
new StreamController<HeapSnapshotLoadingProgressEvent>.broadcast();
- Stream<HeapSnapshotLoadingProgressEvent> get onProgress =>
- _onProgress.stream;
+ Stream<HeapSnapshotLoadingProgressEvent> get onProgress => _onProgress.stream;
final S.Isolate isolate;
final bool gc;
@@ -23,7 +22,7 @@
String _stepDescription = '';
double _progress = 0.0;
final Stopwatch _fetchingTime = new Stopwatch();
- final Stopwatch _loadingTime = new Stopwatch();
+ final Stopwatch _loadingTime = new Stopwatch();
HeapSnapshot _snapshot;
M.HeapSnapshotLoadingStatus get status => _status;
@@ -34,7 +33,7 @@
HeapSnapshot get snapshot => _snapshot;
HeapSnapshotLoadingProgress(this.isolate, this.gc) {
- _run();
+ _run();
}
Future _run() async {
@@ -51,7 +50,7 @@
if (status is List) {
_progress = status[0] * 100.0 / status[1];
_stepDescription = 'Receiving snapshot chunk ${status[0] + 1}'
- ' of ${status[1]}...';
+ ' of ${status[1]}...';
_triggerOnProgress();
}
});
@@ -91,7 +90,7 @@
void reuse() {
_onProgress =
- new StreamController<HeapSnapshotLoadingProgressEvent>.broadcast();
+ new StreamController<HeapSnapshotLoadingProgressEvent>.broadcast();
(() async {
_triggerOnProgress();
_onProgress.close();
@@ -99,11 +98,9 @@
}
}
-class HeapSnapshotRepository
- implements M.HeapSnapshotRepository {
-
+class HeapSnapshotRepository implements M.HeapSnapshotRepository {
Stream<HeapSnapshotLoadingProgressEvent> get(M.IsolateRef i,
- {bool gc: false}) {
+ {bool gc: false}) {
S.Isolate isolate = i as S.Isolate;
assert(isolate != null);
assert(gc != null);
diff --git a/runtime/observatory/lib/src/repositories/icdata.dart b/runtime/observatory/lib/src/repositories/icdata.dart
index cf6165d..dd02f66 100644
--- a/runtime/observatory/lib/src/repositories/icdata.dart
+++ b/runtime/observatory/lib/src/repositories/icdata.dart
@@ -5,7 +5,7 @@
part of repositories;
class ICDataRepository extends M.ICDataRepository {
- Future<M.ICData> get(M.IsolateRef i, String id) async{
+ Future<M.ICData> get(M.IsolateRef i, String id) async {
S.Isolate isolate = i as S.Isolate;
assert(isolate != null);
return (await isolate.getObject(id)) as S.ICData;
diff --git a/runtime/observatory/lib/src/repositories/inbound_references.dart b/runtime/observatory/lib/src/repositories/inbound_references.dart
index 28fd850..be1e1f4 100644
--- a/runtime/observatory/lib/src/repositories/inbound_references.dart
+++ b/runtime/observatory/lib/src/repositories/inbound_references.dart
@@ -8,10 +8,8 @@
Future<M.InboundReferences> get(M.IsolateRef i, String id) async {
S.Isolate isolate = i as S.Isolate;
assert(isolate != null);
- final response = await isolate.invokeRpc('_getInboundReferences', {
- 'targetId' : id,
- 'limit': 100
- });
+ final response = await isolate
+ .invokeRpc('_getInboundReferences', {'targetId': id, 'limit': 100});
return new S.InboundReferences(response);
}
}
diff --git a/runtime/observatory/lib/src/repositories/instance.dart b/runtime/observatory/lib/src/repositories/instance.dart
index ad365d6..b62b140 100644
--- a/runtime/observatory/lib/src/repositories/instance.dart
+++ b/runtime/observatory/lib/src/repositories/instance.dart
@@ -6,7 +6,7 @@
class InstanceRepository extends M.InstanceRepository {
Future<M.Instance> get(M.IsolateRef i, String id,
- {int count: S.kDefaultFieldLimit}) async{
+ {int count: S.kDefaultFieldLimit}) async {
S.Isolate isolate = i as S.Isolate;
assert(isolate != null);
assert(count != null);
diff --git a/runtime/observatory/lib/src/repositories/isolate.dart b/runtime/observatory/lib/src/repositories/isolate.dart
index 4c7712b..9294c7d 100644
--- a/runtime/observatory/lib/src/repositories/isolate.dart
+++ b/runtime/observatory/lib/src/repositories/isolate.dart
@@ -5,14 +5,18 @@
part of repositories;
class IsolateRepository extends M.IsolateRepository {
- Future<M.Isolate> get(M.IsolateRef i) async{
+ Future<M.Isolate> get(M.IsolateRef i) async {
S.Isolate isolate = i as S.Isolate;
assert(isolate != null);
- await isolate.reload();
+ try {
+ await isolate.reload();
+ } on SC.NetworkRpcException catch (_) {
+ /* ignore */
+ }
return isolate;
}
- Future reloadSources(M.IsolateRef i) async{
+ Future reloadSources(M.IsolateRef i) async {
S.Isolate isolate = i as S.Isolate;
assert(isolate != null);
await isolate.reloadSources();
diff --git a/runtime/observatory/lib/src/repositories/library.dart b/runtime/observatory/lib/src/repositories/library.dart
index 987097e..74d8b48 100644
--- a/runtime/observatory/lib/src/repositories/library.dart
+++ b/runtime/observatory/lib/src/repositories/library.dart
@@ -7,7 +7,7 @@
class LibraryRepository extends M.LibraryRepository {
LibraryRepository();
- Future<M.Library> get(M.IsolateRef i, String id) async{
+ Future<M.Library> get(M.IsolateRef i, String id) async {
S.Isolate isolate = i as S.Isolate;
assert(isolate != null);
return (await isolate.getObject(id)) as S.Library;
diff --git a/runtime/observatory/lib/src/repositories/megamorphiccache.dart b/runtime/observatory/lib/src/repositories/megamorphiccache.dart
index 59adbe3..8672e32 100644
--- a/runtime/observatory/lib/src/repositories/megamorphiccache.dart
+++ b/runtime/observatory/lib/src/repositories/megamorphiccache.dart
@@ -5,7 +5,7 @@
part of repositories;
class MegamorphicCacheRepository extends M.MegamorphicCacheRepository {
- Future<M.MegamorphicCache> get(M.IsolateRef i, String id) async{
+ Future<M.MegamorphicCache> get(M.IsolateRef i, String id) async {
S.Isolate isolate = i as S.Isolate;
assert(isolate != null);
return (await isolate.getObject(id)) as S.MegamorphicCache;
diff --git a/runtime/observatory/lib/src/repositories/metric.dart b/runtime/observatory/lib/src/repositories/metric.dart
index 5e81b75..2d90187 100644
--- a/runtime/observatory/lib/src/repositories/metric.dart
+++ b/runtime/observatory/lib/src/repositories/metric.dart
@@ -20,16 +20,16 @@
}
class MetricRepository implements M.MetricRepository {
- final Map<S.Isolate, Map<Metric, List<M.MetricSample>>> _samples
- = <S.Isolate, Map<Metric, List<M.MetricSample>>>{};
- final Map<S.Isolate, Map<Metric, int>> _rates
- = <S.Isolate, Map<Metric, int>>{};
- final Map<S.Isolate, Map<Metric, int>> _sizes
- = <S.Isolate, Map<Metric, int>>{};
+ final Map<S.Isolate, Map<Metric, List<M.MetricSample>>> _samples =
+ <S.Isolate, Map<Metric, List<M.MetricSample>>>{};
+ final Map<S.Isolate, Map<Metric, int>> _rates =
+ <S.Isolate, Map<Metric, int>>{};
+ final Map<S.Isolate, Map<Metric, int>> _sizes =
+ <S.Isolate, Map<Metric, int>>{};
Timer _timer;
int count = 0;
- Future<Iterable<Metric>> list(M.IsolateRef i) async{
+ Future<Iterable<Metric>> list(M.IsolateRef i) async {
S.Isolate isolate = i as S.Isolate;
assert(isolate != null);
if (_samples.containsKey(isolate)) {
@@ -47,10 +47,12 @@
final rates = _rates[isolate] = <Metric, int>{};
final sizes = _sizes[isolate] = <Metric, int>{};
final metrics = []
- ..addAll(isolate.dartMetrics.keys.map((name) =>
- new Metric(name, isolate.dartMetrics[name])).toList())
- ..addAll(isolate.nativeMetrics.keys.map((name) =>
- new Metric(name, isolate.nativeMetrics[name])).toList());
+ ..addAll(isolate.dartMetrics.keys
+ .map((name) => new Metric(name, isolate.dartMetrics[name]))
+ .toList())
+ ..addAll(isolate.nativeMetrics.keys
+ .map((name) => new Metric(name, isolate.nativeMetrics[name]))
+ .toList());
for (final metric in metrics) {
samples[metric] = [new MetricSample(metric.internal.value)];
rates[metric] = _rateToInteger(M.MetricSamplingRate.off);
@@ -79,12 +81,18 @@
final metrics = _rates[i];
if (metrics.containsKey(m)) {
switch (metrics[m]) {
- case 0: return M.MetricSamplingRate.off;
- case 1: return M.MetricSamplingRate.e100ms;
- case 10: return M.MetricSamplingRate.e1s;
- case 20: return M.MetricSamplingRate.e2s;
- case 40: return M.MetricSamplingRate.e4s;
- case 80: return M.MetricSamplingRate.e8s;
+ case 0:
+ return M.MetricSamplingRate.off;
+ case 1:
+ return M.MetricSamplingRate.e100ms;
+ case 10:
+ return M.MetricSamplingRate.e1s;
+ case 20:
+ return M.MetricSamplingRate.e2s;
+ case 40:
+ return M.MetricSamplingRate.e4s;
+ case 80:
+ return M.MetricSamplingRate.e8s;
}
}
}
@@ -107,9 +115,12 @@
final metrics = _sizes[i];
if (metrics.containsKey(m)) {
switch (metrics[m]) {
- case 10: return M.MetricBufferSize.n10samples;
- case 100: return M.MetricBufferSize.n100samples;
- case 1000: return M.MetricBufferSize.n1000samples;
+ case 10:
+ return M.MetricBufferSize.n10samples;
+ case 100:
+ return M.MetricBufferSize.n100samples;
+ case 1000:
+ return M.MetricBufferSize.n1000samples;
}
}
}
@@ -129,21 +140,30 @@
static int _rateToInteger(M.MetricSamplingRate r) {
switch (r) {
- case M.MetricSamplingRate.off: return 0;
- case M.MetricSamplingRate.e100ms: return 1;
- case M.MetricSamplingRate.e1s: return 10;
- case M.MetricSamplingRate.e2s: return 20;
- case M.MetricSamplingRate.e4s: return 40;
- case M.MetricSamplingRate.e8s: return 80;
+ case M.MetricSamplingRate.off:
+ return 0;
+ case M.MetricSamplingRate.e100ms:
+ return 1;
+ case M.MetricSamplingRate.e1s:
+ return 10;
+ case M.MetricSamplingRate.e2s:
+ return 20;
+ case M.MetricSamplingRate.e4s:
+ return 40;
+ case M.MetricSamplingRate.e8s:
+ return 80;
}
throw new Exception('Unknown MetricSamplingRate ($r)');
}
static int _sizeToInteger(M.MetricBufferSize s) {
switch (s) {
- case M.MetricBufferSize.n10samples: return 10;
- case M.MetricBufferSize.n100samples: return 100;
- case M.MetricBufferSize.n1000samples: return 1000;
+ case M.MetricBufferSize.n10samples:
+ return 10;
+ case M.MetricBufferSize.n100samples:
+ return 100;
+ case M.MetricBufferSize.n1000samples:
+ return 1000;
}
throw new Exception('Unknown MetricBufferSize ($s)');
}
diff --git a/runtime/observatory/lib/src/repositories/notification.dart b/runtime/observatory/lib/src/repositories/notification.dart
index 80c25f2..8d952d1 100644
--- a/runtime/observatory/lib/src/repositories/notification.dart
+++ b/runtime/observatory/lib/src/repositories/notification.dart
@@ -25,8 +25,7 @@
Iterable<M.Notification> list() => _list;
void delete(M.Notification notification) {
- if (_list.remove(notification))
- _notify();
+ if (_list.remove(notification)) _notify();
}
void deleteAll() {
@@ -52,13 +51,13 @@
if (isolate == null) {
deleteWhere((notification) {
return notification is M.EventNotification &&
- M.Event.isPauseEvent(notification.event);
+ M.Event.isPauseEvent(notification.event);
});
} else {
deleteWhere((notification) {
return notification is M.EventNotification &&
- M.Event.isPauseEvent(notification.event) &&
- notification.event.isolate == isolate;
+ M.Event.isPauseEvent(notification.event) &&
+ notification.event.isolate == isolate;
});
}
}
@@ -66,7 +65,7 @@
void deleteDisconnectEvents() {
deleteWhere((notification) {
return notification is M.EventNotification &&
- notification.event is M.ConnectionClosedEvent;
+ notification.event is M.ConnectionClosedEvent;
});
}
}
diff --git a/runtime/observatory/lib/src/repositories/object.dart b/runtime/observatory/lib/src/repositories/object.dart
index bd6d143..f1efddf 100644
--- a/runtime/observatory/lib/src/repositories/object.dart
+++ b/runtime/observatory/lib/src/repositories/object.dart
@@ -7,7 +7,7 @@
class ObjectRepository extends M.ObjectRepository {
ObjectRepository();
- Future<M.Object> get(M.IsolateRef i, String id) async{
+ Future<M.Object> get(M.IsolateRef i, String id) async {
S.Isolate isolate = i as S.Isolate;
assert(isolate != null);
return (await isolate.getObject(id)) as S.HeapObject;
diff --git a/runtime/observatory/lib/src/repositories/objectpool.dart b/runtime/observatory/lib/src/repositories/objectpool.dart
index b10c9dc..e626f88 100644
--- a/runtime/observatory/lib/src/repositories/objectpool.dart
+++ b/runtime/observatory/lib/src/repositories/objectpool.dart
@@ -5,7 +5,7 @@
part of repositories;
class ObjectPoolRepository extends M.ObjectPoolRepository {
- Future<M.ObjectPool> get(M.IsolateRef i, String id) async{
+ Future<M.ObjectPool> get(M.IsolateRef i, String id) async {
S.Isolate isolate = i as S.Isolate;
assert(isolate != null);
return (await isolate.getObject(id)) as S.ObjectPool;
diff --git a/runtime/observatory/lib/src/repositories/reachable_size.dart b/runtime/observatory/lib/src/repositories/reachable_size.dart
index e670942..d25d359 100644
--- a/runtime/observatory/lib/src/repositories/reachable_size.dart
+++ b/runtime/observatory/lib/src/repositories/reachable_size.dart
@@ -8,9 +8,8 @@
Future<M.Guarded<M.Instance>> get(M.IsolateRef i, String id) async {
S.Isolate isolate = i as S.Isolate;
assert(isolate != null);
- final response = await isolate.invokeRpc('_getReachableSize', {
- 'targetId' : id
- });
+ final response =
+ await isolate.invokeRpc('_getReachableSize', {'targetId': id});
return new S.Guarded<S.Instance>(response);
}
}
diff --git a/runtime/observatory/lib/src/repositories/retained_size.dart b/runtime/observatory/lib/src/repositories/retained_size.dart
index 3869254..6d3cef5 100644
--- a/runtime/observatory/lib/src/repositories/retained_size.dart
+++ b/runtime/observatory/lib/src/repositories/retained_size.dart
@@ -8,9 +8,8 @@
Future<M.Guarded<M.Instance>> get(M.IsolateRef i, String id) async {
S.Isolate isolate = i as S.Isolate;
assert(isolate != null);
- final response = await isolate.invokeRpc('_getRetainedSize', {
- 'targetId' : id
- });
+ final response =
+ await isolate.invokeRpc('_getRetainedSize', {'targetId': id});
return new S.Guarded<S.Instance>(response);
}
}
diff --git a/runtime/observatory/lib/src/repositories/retaining_path.dart b/runtime/observatory/lib/src/repositories/retaining_path.dart
index 1ff9835..68253f7 100644
--- a/runtime/observatory/lib/src/repositories/retaining_path.dart
+++ b/runtime/observatory/lib/src/repositories/retaining_path.dart
@@ -8,10 +8,8 @@
Future<M.RetainingPath> get(M.IsolateRef i, String id) async {
S.Isolate isolate = i as S.Isolate;
assert(isolate != null);
- final response = await isolate.invokeRpc('_getRetainingPath', {
- 'targetId' : id,
- 'limit': 100
- });
+ final response = await isolate
+ .invokeRpc('_getRetainingPath', {'targetId': id, 'limit': 100});
return new S.RetainingPath(response);
}
}
diff --git a/runtime/observatory/lib/src/repositories/sample_profile.dart b/runtime/observatory/lib/src/repositories/sample_profile.dart
index 0cf5b55..5ad8282 100644
--- a/runtime/observatory/lib/src/repositories/sample_profile.dart
+++ b/runtime/observatory/lib/src/repositories/sample_profile.dart
@@ -6,17 +6,22 @@
String _tagToString(M.SampleProfileTag tag) {
switch (tag) {
- case M.SampleProfileTag.userVM: return 'UserVM';
- case M.SampleProfileTag.userOnly: return 'UserOnly';
- case M.SampleProfileTag.vmUser: return 'VMUser';
- case M.SampleProfileTag.vmOnly: return 'VMOnly';
- case M.SampleProfileTag.none: return 'None';
+ case M.SampleProfileTag.userVM:
+ return 'UserVM';
+ case M.SampleProfileTag.userOnly:
+ return 'UserOnly';
+ case M.SampleProfileTag.vmUser:
+ return 'VMUser';
+ case M.SampleProfileTag.vmOnly:
+ return 'VMOnly';
+ case M.SampleProfileTag.none:
+ return 'None';
}
throw new Exception('Unknown SampleProfileTag: $tag');
}
class SampleProfileLoadingProgressEvent
- implements M.SampleProfileLoadingProgressEvent {
+ implements M.SampleProfileLoadingProgressEvent {
final SampleProfileLoadingProgress progress;
SampleProfileLoadingProgressEvent(this.progress);
}
@@ -35,7 +40,7 @@
M.SampleProfileLoadingStatus _status = M.SampleProfileLoadingStatus.fetching;
double _progress = 0.0;
final Stopwatch _fetchingTime = new Stopwatch();
- final Stopwatch _loadingTime = new Stopwatch();
+ final Stopwatch _loadingTime = new Stopwatch();
CpuProfile _profile;
M.SampleProfileLoadingStatus get status => _status;
@@ -44,22 +49,21 @@
Duration get loadingTime => _loadingTime.elapsed;
CpuProfile get profile => _profile;
- SampleProfileLoadingProgress(this.isolate, this.tag,
- this.clear, {this.cls}) {
- _run();
+ SampleProfileLoadingProgress(this.isolate, this.tag, this.clear, {this.cls}) {
+ _run();
}
Future _run() async {
_fetchingTime.start();
try {
if (clear) {
- await isolate.invokeRpc('_clearCpuProfile', { });
+ await isolate.invokeRpc('_clearCpuProfile', {});
}
final response = cls != null
- ? await cls.getAllocationSamples(_tagToString(tag))
- : await isolate.invokeRpc('_getCpuProfile',
- { 'tags': _tagToString(tag) });
+ ? await cls.getAllocationSamples(_tagToString(tag))
+ : await isolate
+ .invokeRpc('_getCpuProfile', {'tags': _tagToString(tag)});
_fetchingTime.stop();
_loadingTime.start();
@@ -69,7 +73,10 @@
CpuProfile profile = new CpuProfile();
Stream<double> progress = profile.loadProgress(isolate, response);
- progress.listen((value) { _progress = value; _triggerOnProgress(); });
+ progress.listen((value) {
+ _progress = value;
+ _triggerOnProgress();
+ });
await progress.drain();
@@ -98,7 +105,7 @@
void reuse() {
_onProgress =
- new StreamController<SampleProfileLoadingProgressEvent>.broadcast();
+ new StreamController<SampleProfileLoadingProgressEvent>.broadcast();
(() async {
_triggerOnProgress();
_onProgress.close();
@@ -110,8 +117,9 @@
implements M.IsolateSampleProfileRepository {
SampleProfileLoadingProgress _last;
- Stream<SampleProfileLoadingProgressEvent> get(M.IsolateRef i,
- M.SampleProfileTag t, {bool clear: false, bool forceFetch: false}) {
+ Stream<SampleProfileLoadingProgressEvent> get(
+ M.IsolateRef i, M.SampleProfileTag t,
+ {bool clear: false, bool forceFetch: false}) {
assert(clear != null);
assert(forceFetch != null);
S.Isolate isolate = i as S.Isolate;
@@ -125,16 +133,15 @@
}
}
-class ClassSampleProfileRepository
- implements M.ClassSampleProfileRepository {
- Stream<SampleProfileLoadingProgressEvent> get(M.Isolate i, M.ClassRef c,
- M.SampleProfileTag t) {
+class ClassSampleProfileRepository implements M.ClassSampleProfileRepository {
+ Stream<SampleProfileLoadingProgressEvent> get(
+ M.Isolate i, M.ClassRef c, M.SampleProfileTag t) {
S.Isolate isolate = i as S.Isolate;
S.Class cls = c as S.Class;
assert(isolate != null);
assert(cls != null);
- return new SampleProfileLoadingProgress(isolate, t,
- false, cls: cls).onProgress;
+ return new SampleProfileLoadingProgress(isolate, t, false, cls: cls)
+ .onProgress;
}
Future enable(M.IsolateRef i, M.ClassRef c) {
diff --git a/runtime/observatory/lib/src/repositories/strongly_reachable_instances.dart b/runtime/observatory/lib/src/repositories/strongly_reachable_instances.dart
index bcfff96..a015928 100644
--- a/runtime/observatory/lib/src/repositories/strongly_reachable_instances.dart
+++ b/runtime/observatory/lib/src/repositories/strongly_reachable_instances.dart
@@ -7,13 +7,12 @@
class StronglyReachableInstancesRepository
implements M.StronglyReachableInstancesRepository {
Future<M.InstanceSet> get(M.IsolateRef i, M.ClassRef c,
- {int limit: 100}) async {
+ {int limit: 100}) async {
S.Isolate isolate = i as S.Isolate;
S.Class cls = c as S.Class;
assert(isolate != null);
assert(cls != null);
assert(limit != null);
- return (await isolate.getInstances(cls, limit))
- as S.InstanceSet;
+ return (await isolate.getInstances(cls, limit)) as S.InstanceSet;
}
}
diff --git a/runtime/observatory/lib/src/repositories/target.dart b/runtime/observatory/lib/src/repositories/target.dart
index ec52128..cad6dc5 100644
--- a/runtime/observatory/lib/src/repositories/target.dart
+++ b/runtime/observatory/lib/src/repositories/target.dart
@@ -6,11 +6,11 @@
class TargetChangeEvent implements M.TargetChangeEvent {
final TargetRepository repository;
- TargetChangeEvent(this.repository);
+ final bool disconnected;
+ TargetChangeEvent(this.repository, [this.disconnected = false]);
}
class TargetRepository implements M.TargetRepository {
-
static const _historyKey = 'history';
final StreamController<TargetChangeEvent> _onChange;
@@ -28,14 +28,18 @@
TargetRepository._(this._onChange, this.onChange) {
_restore();
- if (_list.isEmpty) {
- _list.add(new SC.WebSocketVMTarget(_networkAddressOfDefaultTarget()));
+ // Add the default address if it doesn't already exist.
+ if (_find(_networkAddressOfDefaultTarget()) == null) {
+ add(_networkAddressOfDefaultTarget());
}
- current = _list.first;
+ // Set the current target to the default target.
+ current = _find(_networkAddressOfDefaultTarget());
}
void add(String address) {
- if (_find(address) != null) return;
+ if (_find(address) != null) {
+ return;
+ }
_list.insert(0, new SC.WebSocketVMTarget(address));
_onChange.add(new TargetChangeEvent(this));
_store();
@@ -45,13 +49,19 @@
void setCurrent(M.Target t) {
SC.WebSocketVMTarget target = t as SC.WebSocketVMTarget;
- if (!_list.contains(target)) return;
+ if (!_list.contains(target)) {
+ return;
+ }
current = target;
current.lastConnectionTime = new DateTime.now().millisecondsSinceEpoch;
_onChange.add(new TargetChangeEvent(this));
_store();
}
+ void emitDisconnectEvent() {
+ _onChange.add(new TargetChangeEvent(this, true));
+ }
+
void delete(o) {
if (_list.remove(o)) {
if (o == current) {
@@ -71,13 +81,13 @@
}
_list.addAll(loaded.map((i) => new SC.WebSocketVMTarget.fromMap(i)));
_list.sort((SC.WebSocketVMTarget a, SC.WebSocketVMTarget b) {
- return b.lastConnectionTime.compareTo(a.lastConnectionTime);
+ return b.lastConnectionTime.compareTo(a.lastConnectionTime);
});
}
/// After making a change, update settings.
void _store() {
- _settings.set(_historyKey, _list);
+ _settings.set(_historyKey, _list);
}
/// Find by networkAddress.
diff --git a/runtime/observatory/lib/src/repositories/top_retaining_instances.dart b/runtime/observatory/lib/src/repositories/top_retaining_instances.dart
index 117c679..0094762 100644
--- a/runtime/observatory/lib/src/repositories/top_retaining_instances.dart
+++ b/runtime/observatory/lib/src/repositories/top_retaining_instances.dart
@@ -14,9 +14,8 @@
final raw = await isolate.fetchHeapSnapshot(true).last;
final snapshot = new HeapSnapshot();
await snapshot.loadProgress(isolate, raw).last;
- return (await Future.wait(snapshot.getMostRetained(isolate,
- classId: cls.vmCid,
- limit: 10)))
- .map((object) => new S.RetainingObject(object));
+ return (await Future.wait(
+ snapshot.getMostRetained(isolate, classId: cls.vmCid, limit: 10)))
+ .map((object) => new S.RetainingObject(object));
}
}
diff --git a/runtime/observatory/lib/src/service/object.dart b/runtime/observatory/lib/src/service/object.dart
index a519ed9..51ac8eb 100644
--- a/runtime/observatory/lib/src/service/object.dart
+++ b/runtime/observatory/lib/src/service/object.dart
@@ -31,22 +31,22 @@
/// A ServerRpcException represents an error returned by the VM.
class ServerRpcException extends RpcException implements M.RequestException {
/// A list of well-known server error codes.
- static const kParseError = -32700;
+ static const kParseError = -32700;
static const kInvalidRequest = -32600;
static const kMethodNotFound = -32601;
- static const kInvalidParams = -32602;
- static const kInternalError = -32603;
- static const kFeatureDisabled = 100;
- static const kCannotAddBreakpoint = 102;
+ static const kInvalidParams = -32602;
+ static const kInternalError = -32603;
+ static const kFeatureDisabled = 100;
+ static const kCannotAddBreakpoint = 102;
static const kStreamAlreadySubscribed = 103;
- static const kStreamNotSubscribed = 104;
- static const kIsolateMustBeRunnable = 105;
- static const kIsolateMustBePaused = 106;
- static const kIsolateIsReloading = 1000;
+ static const kStreamNotSubscribed = 104;
+ static const kIsolateMustBeRunnable = 105;
+ static const kIsolateMustBePaused = 106;
+ static const kIsolateIsReloading = 1000;
static const kFileSystemAlreadyExists = 1001;
- static const kFileSystemDoesNotExist = 1002;
- static const kFileDoesNotExist = 1003;
- static const kIsolateReloadFailed = 1004;
+ static const kFileSystemDoesNotExist = 1002;
+ static const kFileDoesNotExist = 1003;
+ static const kIsolateReloadFailed = 1004;
int code;
Map data;
@@ -71,15 +71,22 @@
/// A NetworkRpcException is used to indicate that an rpc has
/// been canceled due to network error.
class NetworkRpcException extends RpcException
- implements M.ConnectionException {
+ implements M.ConnectionException {
NetworkRpcException(String message) : super(message);
String toString() => 'NetworkRpcException(${message})';
}
+Future<ServiceObject> ignoreNetworkErrors(
+ Object error, [ServiceObject resultOnNetworkError = null]) {
+ if (error is NetworkRpcException) {
+ return new Future.value(resultOnNetworkError);
+ }
+ return new Future.error(error);
+}
+
class MalformedResponseRpcException extends RpcException {
- MalformedResponseRpcException(String message, this.response)
- : super(message);
+ MalformedResponseRpcException(String message, this.response) : super(message);
Map response;
@@ -174,8 +181,7 @@
ServiceObject._empty(this._owner);
/// Creates a [ServiceObject] initialized from [map].
- factory ServiceObject._fromMap(ServiceObjectOwner owner,
- Map map) {
+ factory ServiceObject._fromMap(ServiceObjectOwner owner, Map map) {
if (map == null) {
return null;
}
@@ -334,7 +340,6 @@
update(map);
completer.complete(this);
}
-
}).catchError((e, st) {
Logger.root.severe("Unable to reload object: $e\n$st");
_inProgressReload = null;
@@ -403,7 +408,9 @@
// Load the full class object if the isolate is runnable.
if (clazz != null) {
if (clazz.isolate.runnable) {
- clazz.load();
+ // No one awaits on this request so we silence any network errors
+ // that occur here but forward other errors.
+ clazz.load().catchError((error) => ignoreNetworkErrors(error, clazz));
}
}
@@ -436,8 +443,8 @@
}
/// A [SourceLocation] represents a location or range in the source code.
-class SourceLocation extends ServiceObject implements Location,
- M.SourceLocation {
+class SourceLocation extends ServiceObject
+ implements Location, M.SourceLocation {
Script script;
int tokenPos;
int endTokenPos;
@@ -482,8 +489,7 @@
/// An [UnresolvedSourceLocation] represents a location in the source
// code which has not been precisely mapped to a token position.
class UnresolvedSourceLocation extends ServiceObject
- implements Location,
- M.UnresolvedSourceLocation {
+ implements Location, M.UnresolvedSourceLocation {
Script script;
String scriptUri;
int line;
@@ -589,6 +595,8 @@
// No new listeners showed up during cancelation.
_onDone();
}
+ }).catchError((e) {
+ /* ignore */
});
}
// No need to wait for _cancelFuture here.
@@ -597,16 +605,20 @@
Future<Stream> addStream() async {
var controller;
- controller = new StreamController(
- onCancel:() => _cancelController(controller));
+ controller =
+ new StreamController(onCancel: () => _cancelController(controller));
_controllers.add(controller);
if (_cancelFuture != null) {
- await _cancelFuture;
+ try {
+ await _cancelFuture;
+ } on NetworkRpcException catch (_) {/* ignore */}
}
if (_listenFuture == null) {
_listenFuture = _vm._streamListen(streamId);
}
- await _listenFuture;
+ try {
+ await _listenFuture;
+ } on NetworkRpcException catch (_) {/* ignore */}
return controller.stream;
}
@@ -624,13 +636,14 @@
// TODO(turnidge): The connection should not be stored in the VM object.
bool get isDisconnected;
+ bool get isConnected;
// Used for verbose logging.
bool verbose = false;
// TODO(johnmccutchan): Ensure that isolates do not end up in _cache.
- Map<String,ServiceObject> _cache = new Map<String,ServiceObject>();
- final Map<String,Isolate> _isolateCache = <String,Isolate>{};
+ Map<String, ServiceObject> _cache = new Map<String, ServiceObject>();
+ final Map<String, Isolate> _isolateCache = <String, Isolate>{};
// The list of live isolates, ordered by isolate start time.
final List<Isolate> isolates = <Isolate>[];
@@ -654,7 +667,7 @@
}
VM() : super._empty(null) {
- update({'name':'vm', 'type':'@VM'});
+ update({'name': 'vm', 'type': '@VM'});
}
void postServiceEvent(String streamId, Map response, ByteData data) {
@@ -664,8 +677,7 @@
map['_data'] = data;
}
if (map['type'] != 'Event') {
- Logger.root.severe(
- "Expected 'Event' but found '${map['type']}'");
+ Logger.root.severe("Expected 'Event' but found '${map['type']}'");
return;
}
@@ -789,13 +801,12 @@
return invokeRpcRaw(method, params).then((Map response) {
var map = response;
if (Tracer.current != null) {
- Tracer.current.trace("Received response for ${method}/${params}}",
- map:map);
+ Tracer.current
+ .trace("Received response for ${method}/${params}}", map: map);
}
if (!_isServiceMap(map)) {
- var exception =
- new MalformedResponseRpcException(
- "Response is missing the 'type' field", map);
+ var exception = new MalformedResponseRpcException(
+ "Response is missing the 'type' field", map);
return new Future.error(exception);
}
return new Future.value(map);
@@ -813,6 +824,8 @@
_cache.putIfAbsent(objId, () => obj);
}
return obj;
+ }).catchError((e) {
+ return new Future.error(e);
});
}
@@ -838,13 +851,15 @@
await listenEventStream(_kGraphStream, _dispatchEventToIsolate);
} on FakeVMRpcException catch (_) {
// ignore FakeVMRpcExceptions here.
+ } on NetworkRpcException catch (_) {
+ // ignore network errors here.
}
}
return await invokeRpcNoUpgrade('getVM', {});
}
Future setName(String newName) {
- return invokeRpc('setVMName', { 'name': newName });
+ return invokeRpc('setVMName', {'name': newName});
}
Future<ServiceObject> getFlagList() {
@@ -855,18 +870,22 @@
Map params = {
'streamId': streamId,
};
- return invokeRpc('streamListen', params);
+ // Ignore network errors on stream listen.
+ return invokeRpc('streamListen', params).catchError(
+ (e) => ignoreNetworkErrors(e));
}
Future<ServiceObject> _streamCancel(String streamId) {
Map params = {
'streamId': streamId,
};
- return invokeRpc('streamCancel', params);
+ // Ignore network errors on stream cancel.
+ return invokeRpc('streamCancel', params).catchError(
+ (e) => ignoreNetworkErrors(e));
}
// A map from stream id to event stream state.
- Map<String,_EventStreamState> _eventStreams = {};
+ Map<String, _EventStreamState> _eventStreams = {};
// Well-known stream ids.
static const kVMStream = 'VM';
@@ -881,22 +900,26 @@
/// Returns a single-subscription Stream object for a VM event stream.
Future<Stream> getEventStream(String streamId) async {
var eventStream = _eventStreams.putIfAbsent(
- streamId, () => new _EventStreamState(
+ streamId,
+ () => new _EventStreamState(
this, streamId, () => _eventStreams.remove(streamId)));
- return eventStream.addStream();
+ Stream stream = await eventStream.addStream();
+ return stream;
}
/// Helper function for listening to an event stream.
- Future<StreamSubscription> listenEventStream(String streamId,
- Function function) async {
+ Future<StreamSubscription> listenEventStream(
+ String streamId, Function function) async {
var stream = await getEventStream(streamId);
return stream.listen(function);
}
/// Force the VM to disconnect.
void disconnect();
+
/// Completes when the VM first connects.
Future get onConnect;
+
/// Completes when the VM disconnects or there was an error connecting.
Future get onDisconnect;
@@ -987,6 +1010,8 @@
_onConnect = new Future.value(this);
return _onConnect;
}
+
+ bool get isConnected => !isDisconnected;
// Only complete when requested.
Completer _onDisconnect = new Completer();
Future get onDisconnect => _onDisconnect.future;
@@ -1006,7 +1031,6 @@
}
}
-
/// Snapshot in time of tag counters.
class TagProfileSnapshot {
final double seconds;
@@ -1094,8 +1118,8 @@
final Iterable<InboundReference> elements;
InboundReferences(ServiceMap map)
- : this.elements = map['references']
- .map((rmap) => new InboundReference(rmap));
+ : this.elements =
+ map['references'].map((rmap) => new InboundReference(rmap));
}
class InboundReference implements M.InboundReference {
@@ -1105,18 +1129,18 @@
final int parentWordOffset;
InboundReference(ServiceMap map)
- : source = map['source'],
- parentField = map['parentField'],
- parentListIndex = map['parentListIndex'],
- parentWordOffset = map['_parentWordOffset'];
+ : source = map['source'],
+ parentField = map['parentField'],
+ parentListIndex = map['parentListIndex'],
+ parentWordOffset = map['_parentWordOffset'];
}
class RetainingPath implements M.RetainingPath {
final Iterable<RetainingPathItem> elements;
RetainingPath(ServiceMap map)
- : this.elements = map['elements']
- .map((rmap) => new RetainingPathItem(rmap));
+ : this.elements =
+ map['elements'].map((rmap) => new RetainingPathItem(rmap));
}
class RetainingPathItem implements M.RetainingPathItem {
@@ -1126,18 +1150,17 @@
final int parentWordOffset;
RetainingPathItem(ServiceMap map)
- : source = map['value'],
- parentField = map['parentField'],
- parentListIndex = map['parentListIndex'],
- parentWordOffset = map['_parentWordOffset'];
+ : source = map['value'],
+ parentField = map['parentField'],
+ parentListIndex = map['parentListIndex'],
+ parentWordOffset = map['_parentWordOffset'];
}
class Ports implements M.Ports {
final Iterable<Port> elements;
Ports(ServiceMap map)
- : this.elements = map['ports']
- .map((rmap) => new Port(rmap));
+ : this.elements = map['ports'].map((rmap) => new Port(rmap));
}
class Port implements M.Port {
@@ -1145,8 +1168,8 @@
final HeapObject handler;
Port(ServiceMap map)
- : name = map['name'],
- handler = map['handler'];
+ : name = map['name'],
+ handler = map['handler'];
}
class PersistentHandles implements M.PersistentHandles {
@@ -1154,17 +1177,16 @@
final Iterable<WeakPersistentHandle> weakElements;
PersistentHandles(ServiceMap map)
- : this.elements = map['persistentHandles']
- .map((rmap) => new PersistentHandle(rmap)),
- this.weakElements = map['weakPersistentHandles']
- .map((rmap) => new WeakPersistentHandle(rmap));
+ : this.elements =
+ map['persistentHandles'].map((rmap) => new PersistentHandle(rmap)),
+ this.weakElements = map['weakPersistentHandles']
+ .map((rmap) => new WeakPersistentHandle(rmap));
}
class PersistentHandle implements M.PersistentHandle {
final HeapObject object;
- PersistentHandle(ServiceMap map)
- : object = map['object'];
+ PersistentHandle(ServiceMap map) : object = map['object'];
}
class WeakPersistentHandle implements M.WeakPersistentHandle {
@@ -1175,11 +1197,11 @@
final HeapObject object;
WeakPersistentHandle(ServiceMap map)
- : externalSize = int.parse(map['externalSize']),
- peer = map['peer'],
- callbackSymbolName = map['callbackSymbolName'],
- callbackAddress = map['callbackAddress'],
- object = map['object'];
+ : externalSize = int.parse(map['externalSize']),
+ peer = map['peer'],
+ callbackSymbolName = map['callbackSymbolName'],
+ callbackAddress = map['callbackAddress'],
+ object = map['object'];
}
class HeapSpace implements M.HeapSpace {
@@ -1191,8 +1213,9 @@
double averageCollectionPeriodInMillis = 0.0;
Duration get avgCollectionTime {
- final mcs = totalCollectionTimeInSeconds * Duration.MICROSECONDS_PER_SECOND
- / math.max(collections, 1);
+ final mcs = totalCollectionTimeInSeconds *
+ Duration.MICROSECONDS_PER_SECOND /
+ math.max(collections, 1);
return new Duration(microseconds: mcs.ceil());
}
@@ -1202,8 +1225,8 @@
}
Duration get avgCollectionPeriod {
- final mcs = averageCollectionPeriodInMillis
- * Duration.MICROSECONDS_PER_MILLISECOND;
+ final mcs =
+ averageCollectionPeriodInMillis * Duration.MICROSECONDS_PER_MILLISECOND;
return new Duration(microseconds: mcs.ceil());
}
@@ -1244,8 +1267,7 @@
void _updateRunState() {
topFrame = M.topFrame(pauseEvent);
- paused = (pauseEvent != null &&
- !(pauseEvent is M.ResumeEvent));
+ paused = (pauseEvent != null && !(pauseEvent is M.ResumeEvent));
running = (!paused && topFrame != null);
idle = (!paused && topFrame == null);
}
@@ -1273,7 +1295,7 @@
final List<String> extensionRPCs = new List<String>();
- Map<String,ServiceObject> _cache = new Map<String,ServiceObject>();
+ Map<String, ServiceObject> _cache = new Map<String, ServiceObject>();
final TagProfile tagProfile = new TagProfile(20);
Isolate._empty(ServiceObjectOwner owner) : super._empty(owner) {
@@ -1297,10 +1319,8 @@
static const kProfileReport = '_Profile';
Future<ServiceMap> getSourceReport(List<String> report_kinds,
- [Script script,
- int startPos,
- int endPos]) {
- var params = { 'reports' : report_kinds };
+ [Script script, int startPos, int endPos]) {
+ var params = {'reports': report_kinds};
if (script != null) {
params['scriptId'] = script.id;
}
@@ -1428,8 +1448,7 @@
}
Future<ServiceObject> getObject(String objectId,
- {bool reload: true,
- int count: kDefaultFieldLimit}) {
+ {bool reload: true, int count: kDefaultFieldLimit}) {
assert(objectId != null && objectId != '');
var obj = _cache[objectId];
if (obj != null) {
@@ -1497,8 +1516,7 @@
_chunksInProgress = null;
if (_snapshotFetch != null) {
- _snapshotFetch.add(
- new RawHeapSnapshot(loadedChunks, event.nodeCount));
+ _snapshotFetch.add(new RawHeapSnapshot(loadedChunks, event.nodeCount));
_snapshotFetch.close();
}
}
@@ -1507,8 +1525,8 @@
if (_snapshotFetch == null || _snapshotFetch.isClosed) {
_snapshotFetch = new StreamController.broadcast();
// isolate.vm.streamListen('_Graph');
- isolate.invokeRpcNoUpgrade('_requestHeapSnapshot',
- {'collectGarbage': collectGarbage});
+ isolate.invokeRpcNoUpgrade(
+ '_requestHeapSnapshot', {'collectGarbage': collectGarbage});
}
return _snapshotFetch.stream;
}
@@ -1521,7 +1539,7 @@
void _update(Map map, bool mapIsRef) {
name = map['name'];
vmName = map.containsKey('_vmName') ? map['_vmName'] : name;
- number = int.parse(map['number'], onError:(_) => null);
+ number = int.parse(map['number'], onError: (_) => null);
if (mapIsRef) {
return;
}
@@ -1529,7 +1547,7 @@
loading = false;
runnable = map['runnable'] == true;
_upgradeCollection(map, isolate);
- originNumber = int.parse(map['_originNumber'], onError:(_) => null);
+ originNumber = int.parse(map['_originNumber'], onError: (_) => null);
rootLibrary = map['rootLib'];
if (map['entry'] != null) {
entry = map['entry'];
@@ -1570,8 +1588,8 @@
var newPauseEvent = map['pauseEvent'];
assert((pauseEvent == null) ||
- (newPauseEvent == null) ||
- !newPauseEvent.timestamp.isBefore(pauseEvent.timestamp));
+ (newPauseEvent == null) ||
+ !newPauseEvent.timestamp.isBefore(pauseEvent.timestamp));
pauseEvent = createEventFromServiceEvent(newPauseEvent);
_updateRunState();
error = map['error'];
@@ -1590,12 +1608,11 @@
}
Future<TagProfile> updateTagProfile() {
- return isolate.invokeRpcNoUpgrade('_getTagProfile', {}).then(
- (Map map) {
- var seconds = new DateTime.now().millisecondsSinceEpoch / 1000.0;
- tagProfile._processTagProfile(seconds, map);
- return tagProfile;
- });
+ return isolate.invokeRpcNoUpgrade('_getTagProfile', {}).then((Map map) {
+ var seconds = new DateTime.now().millisecondsSinceEpoch / 1000.0;
+ tagProfile._processTagProfile(seconds, map);
+ return tagProfile;
+ });
}
Map<int, Breakpoint> breakpoints = <int, Breakpoint>{};
@@ -1629,7 +1646,7 @@
}
void _onEvent(ServiceEvent event) {
- switch(event.kind) {
+ switch (event.kind) {
case ServiceEvent.kIsolateStart:
case ServiceEvent.kIsolateRunnable:
case ServiceEvent.kIsolateExit:
@@ -1661,7 +1678,7 @@
case ServiceEvent.kNone:
case ServiceEvent.kResume:
assert((pauseEvent == null) ||
- !event.timestamp.isBefore(pauseEvent.timestamp));
+ !event.timestamp.isBefore(pauseEvent.timestamp));
pauseEvent = createEventFromServiceEvent(event);
_updateRunState();
break;
@@ -1692,8 +1709,8 @@
return invokeRpc('addBreakpoint', params);
}
- Future<ServiceObject> addBreakpointByScriptUri(
- String uri, int line, [int col]) {
+ Future<ServiceObject> addBreakpointByScriptUri(String uri, int line,
+ [int col]) {
Map params = {
'scriptUri': uri,
'line': line.toString(),
@@ -1705,18 +1722,15 @@
}
Future<ServiceObject> addBreakpointAtEntry(ServiceFunction function) {
- return invokeRpc('addBreakpointAtEntry',
- { 'functionId': function.id });
+ return invokeRpc('addBreakpointAtEntry', {'functionId': function.id});
}
Future<ServiceObject> addBreakOnActivation(Instance closure) {
- return invokeRpc('_addBreakpointAtActivation',
- { 'objectId': closure.id });
+ return invokeRpc('_addBreakpointAtActivation', {'objectId': closure.id});
}
Future removeBreakpoint(Breakpoint bpt) {
- return invokeRpc('removeBreakpoint',
- { 'breakpointId': bpt.id });
+ return invokeRpc('removeBreakpoint', {'breakpointId': bpt.id});
}
Future pause() {
@@ -1763,8 +1777,7 @@
});
}
- Future<ServiceObject> eval(ServiceObject target,
- String expression) {
+ Future<ServiceObject> eval(ServiceObject target, String expression) {
Map params = {
'targetId': target.id,
'expression': expression,
@@ -1772,8 +1785,7 @@
return invokeRpc('evaluate', params);
}
- Future<ServiceObject> evalFrame(int frameIndex,
- String expression) {
+ Future<ServiceObject> evalFrame(int frameIndex, String expression) {
Map params = {
'frameIndex': frameIndex,
'expression': expression,
@@ -1826,7 +1838,7 @@
return invokeRpc('_getInstances', params);
}
- Future<ServiceObject> getObjectByAddress(String address, [bool ref=true]) {
+ Future<ServiceObject> getObjectByAddress(String address, [bool ref = true]) {
Map params = {
'address': address,
'ref': ref,
@@ -1839,10 +1851,9 @@
final Map<String, ServiceMetric> nativeMetrics = <String, ServiceMetric>{};
Future<Map<String, ServiceMetric>> _refreshMetrics(
- String metricType,
- Map<String, ServiceMetric> metricsMap) {
- return invokeRpc('_getIsolateMetricList',
- { 'type': metricType }).then((result) {
+ String metricType, Map<String, ServiceMetric> metricsMap) {
+ return invokeRpc('_getIsolateMetricList', {'type': metricType})
+ .then((result) {
// Clear metrics map.
metricsMap.clear();
// Repopulate metrics map.
@@ -1869,14 +1880,12 @@
String toString() => "Isolate($name)";
}
-
class NamedField implements M.NamedField {
final String name;
final M.ObjectRef value;
NamedField(this.name, this.value);
}
-
class ObjectStore extends ServiceObject implements M.ObjectStore {
List<NamedField> fields = new List<NamedField>();
@@ -1898,9 +1907,8 @@
}
}
-
/// A [ServiceObject] which implements [Map].
-class ServiceMap extends ServiceObject implements Map, M.UnknownObjectRef {
+class ServiceMap extends ServiceObject implements Map, M.UnknownObjectRef {
final Map _map = {};
static String objectIdRingPrefix = 'objects/';
@@ -1947,11 +1955,15 @@
}
M.ErrorKind stringToErrorKind(String value) {
- switch(value) {
- case 'UnhandledException': return M.ErrorKind.unhandledException;
- case 'LanguageError': return M.ErrorKind.unhandledException;
- case 'InternalError': return M.ErrorKind.internalError;
- case 'TerminationError': return M.ErrorKind.terminationError;
+ switch (value) {
+ case 'UnhandledException':
+ return M.ErrorKind.unhandledException;
+ case 'LanguageError':
+ return M.ErrorKind.unhandledException;
+ case 'InternalError':
+ return M.ErrorKind.internalError;
+ case 'TerminationError':
+ return M.ErrorKind.terminationError;
}
Logger.root.severe('Unrecognized error kind: $value');
throw new FallThroughError();
@@ -1992,31 +2004,31 @@
/// A [ServiceEvent] is an asynchronous event notification from the vm.
class ServiceEvent extends ServiceObject {
/// The possible 'kind' values.
- static const kVMUpdate = 'VMUpdate';
- static const kIsolateStart = 'IsolateStart';
- static const kIsolateRunnable = 'IsolateRunnable';
- static const kIsolateExit = 'IsolateExit';
- static const kIsolateUpdate = 'IsolateUpdate';
- static const kIsolateReload = 'IsolateReload';
- static const kIsolateSpawn = 'IsolateSpawn';
- static const kServiceExtensionAdded = 'ServiceExtensionAdded';
- static const kPauseStart = 'PauseStart';
- static const kPauseExit = 'PauseExit';
- static const kPauseBreakpoint = 'PauseBreakpoint';
- static const kPauseInterrupted = 'PauseInterrupted';
- static const kPauseException = 'PauseException';
- static const kNone = 'None';
- static const kResume = 'Resume';
- static const kBreakpointAdded = 'BreakpointAdded';
- static const kBreakpointResolved = 'BreakpointResolved';
- static const kBreakpointRemoved = 'BreakpointRemoved';
- static const kGraph = '_Graph';
- static const kGC = 'GC';
- static const kInspect = 'Inspect';
+ static const kVMUpdate = 'VMUpdate';
+ static const kIsolateStart = 'IsolateStart';
+ static const kIsolateRunnable = 'IsolateRunnable';
+ static const kIsolateExit = 'IsolateExit';
+ static const kIsolateUpdate = 'IsolateUpdate';
+ static const kIsolateReload = 'IsolateReload';
+ static const kIsolateSpawn = 'IsolateSpawn';
+ static const kServiceExtensionAdded = 'ServiceExtensionAdded';
+ static const kPauseStart = 'PauseStart';
+ static const kPauseExit = 'PauseExit';
+ static const kPauseBreakpoint = 'PauseBreakpoint';
+ static const kPauseInterrupted = 'PauseInterrupted';
+ static const kPauseException = 'PauseException';
+ static const kNone = 'None';
+ static const kResume = 'Resume';
+ static const kBreakpointAdded = 'BreakpointAdded';
+ static const kBreakpointResolved = 'BreakpointResolved';
+ static const kBreakpointRemoved = 'BreakpointRemoved';
+ static const kGraph = '_Graph';
+ static const kGC = 'GC';
+ static const kInspect = 'Inspect';
static const kDebuggerSettingsUpdate = '_DebuggerSettingsUpdate';
- static const kConnectionClosed = 'ConnectionClosed';
- static const kLogging = '_Logging';
- static const kExtension = 'Extension';
+ static const kConnectionClosed = 'ConnectionClosed';
+ static const kLogging = '_Logging';
+ static const kExtension = 'Extension';
ServiceEvent._empty(ServiceObjectOwner owner) : super._empty(owner);
@@ -2051,11 +2063,11 @@
bool get isPauseEvent {
return (kind == kPauseStart ||
- kind == kPauseExit ||
- kind == kPauseBreakpoint ||
- kind == kPauseInterrupted ||
- kind == kPauseException ||
- kind == kNone);
+ kind == kPauseExit ||
+ kind == kPauseBreakpoint ||
+ kind == kPauseInterrupted ||
+ kind == kPauseException ||
+ kind == kNone);
}
void _update(Map map, bool mapIsRef) {
@@ -2063,8 +2075,7 @@
_upgradeCollection(map, owner);
assert(map['isolate'] == null || owner == map['isolate']);
- timestamp =
- new DateTime.fromMillisecondsSinceEpoch(map['timestamp']);
+ timestamp = new DateTime.fromMillisecondsSinceEpoch(map['timestamp']);
kind = map['kind'];
name = 'ServiceEvent $kind';
vmName = name;
@@ -2224,7 +2235,6 @@
}
}
-
class LibraryDependency implements M.LibraryDependency {
final bool isImport;
final bool isDeferred;
@@ -2235,13 +2245,10 @@
LibraryDependency._(this.isImport, this.isDeferred, this.prefix, this.target);
- static _fromMap(map) => new LibraryDependency._(map["isImport"],
- map["isDeferred"],
- map["prefix"],
- map["target"]);
+ static _fromMap(map) => new LibraryDependency._(
+ map["isImport"], map["isDeferred"], map["prefix"], map["target"]);
}
-
class Library extends HeapObject implements M.Library {
String uri;
final dependencies = <LibraryDependency>[];
@@ -2264,8 +2271,7 @@
uri = map['uri'];
var shortUri = uri;
- if (uri.startsWith('file://') ||
- uri.startsWith('http://')) {
+ if (uri.startsWith('file://') || uri.startsWith('http://')) {
shortUri = uri.substring(uri.lastIndexOf('/') + 1);
}
name = map['name'];
@@ -2387,7 +2393,7 @@
name = map['name'];
vmName = (map.containsKey('_vmName') ? map['_vmName'] : name);
if (vmName == '::') {
- name = 'top-level-class'; // Better than ''
+ name = 'top-level-class'; // Better than ''
}
var idPrefix = "classes/";
assert(id.startsWith(idPrefix));
@@ -2469,14 +2475,13 @@
Future<ServiceObject> setTraceAllocations(bool enable) {
return isolate.invokeRpc('_setTraceClassAllocation', {
- 'enable': enable,
- 'classId': id,
- });
+ 'enable': enable,
+ 'classId': id,
+ });
}
Future<ServiceObject> getAllocationSamples([String tags = 'None']) {
- var params = { 'tags': tags,
- 'classId': id };
+ var params = {'tags': tags, 'classId': id};
return isolate.invokeRpc('_getAllocationSamples', params);
}
@@ -2573,17 +2578,14 @@
throw new Exception('${obj.type} is neither Sentinel or $T');
}
- Guarded.fromSentinel(this.asSentinel)
- : asValue = null;
- Guarded.fromValue(this.asValue)
- : asSentinel = null;
+ Guarded.fromSentinel(this.asSentinel) : asValue = null;
+ Guarded.fromValue(this.asValue) : asSentinel = null;
}
class BoundField implements M.BoundField {
final Field decl;
final Guarded<Instance> value;
- BoundField(this.decl, value)
- : value = new Guarded(value);
+ BoundField(this.decl, value) : value = new Guarded(value);
}
class NativeField implements M.NativeField {
@@ -2595,20 +2597,20 @@
final Guarded<Instance> key;
final Guarded<Instance> value;
MapAssociation(key, value)
- : key = new Guarded(key),
- value = new Guarded(value);
+ : key = new Guarded(key),
+ value = new Guarded(value);
}
class Instance extends HeapObject implements M.Instance {
M.InstanceKind kind;
- String valueAsString; // If primitive.
+ String valueAsString; // If primitive.
bool valueAsStringIsTruncated;
- ServiceFunction closureFunction; // If a closure.
- Context closureContext; // If a closure.
+ ServiceFunction closureFunction; // If a closure.
+ Context closureContext; // If a closure.
int length; // If a List, Map or TypedData.
int count;
int offset;
- Instance pattern; // If a RegExp.
+ Instance pattern; // If a RegExp.
String name;
Class typeClass;
@@ -2620,21 +2622,21 @@
Iterable<BoundField> fields;
var nativeFields;
- Iterable<Guarded<HeapObject>> elements; // If a List.
- Iterable<MapAssociation> associations; // If a Map.
- Iterable<dynamic> typedElements; // If a TypedData.
- HeapObject referent; // If a MirrorReference.
- Instance key; // If a WeakProperty.
- Instance value; // If a WeakProperty.
- Breakpoint activationBreakpoint; // If a Closure.
- ServiceFunction oneByteFunction; // If a RegExp.
- ServiceFunction twoByteFunction; // If a RegExp.
- ServiceFunction externalOneByteFunction; // If a RegExp.
- ServiceFunction externalTwoByteFunction; // If a RegExp.
- Instance oneByteBytecode; // If a RegExp.
- Instance twoByteBytecode; // If a RegExp.
- bool isCaseSensitive; // If a RegExp.
- bool isMultiLine; // If a RegExp.
+ Iterable<Guarded<HeapObject>> elements; // If a List.
+ Iterable<MapAssociation> associations; // If a Map.
+ Iterable<dynamic> typedElements; // If a TypedData.
+ HeapObject referent; // If a MirrorReference.
+ Instance key; // If a WeakProperty.
+ Instance value; // If a WeakProperty.
+ Breakpoint activationBreakpoint; // If a Closure.
+ ServiceFunction oneByteFunction; // If a RegExp.
+ ServiceFunction twoByteFunction; // If a RegExp.
+ ServiceFunction externalOneByteFunction; // If a RegExp.
+ ServiceFunction externalTwoByteFunction; // If a RegExp.
+ Instance oneByteBytecode; // If a RegExp.
+ Instance twoByteBytecode; // If a RegExp.
+ bool isCaseSensitive; // If a RegExp.
+ bool isMultiLine; // If a RegExp.
bool get isAbstractType => M.isAbstractType(kind);
bool get isNull => kind == M.InstanceKind.vNull;
@@ -2647,9 +2649,11 @@
bool get isTypedData {
return M.isTypedData(kind);
}
+
bool get isSimdValue {
return M.isSimdValue(kind);
}
+
bool get isRegExp => kind == M.InstanceKind.regExp;
bool get isMirrorReference => kind == M.InstanceKind.mirrorReference;
bool get isWeakProperty => kind == M.InstanceKind.weakProperty;
@@ -2708,69 +2712,88 @@
bool isCompiled = map['_oneByteFunction'] is ServiceFunction;
oneByteFunction = isCompiled ? map['_oneByteFunction'] : null;
twoByteFunction = isCompiled ? map['_twoByteFunction'] : null;
- externalOneByteFunction = isCompiled ? map['_externalOneByteFunction'] : null;
- externalTwoByteFunction = isCompiled ? map['_externalTwoByteFunction'] : null;
+ externalOneByteFunction =
+ isCompiled ? map['_externalOneByteFunction'] : null;
+ externalTwoByteFunction =
+ isCompiled ? map['_externalTwoByteFunction'] : null;
oneByteBytecode = map['_oneByteBytecode'];
twoByteBytecode = map['_twoByteBytecode'];
if (map['fields'] != null) {
fields = map['fields']
- .map((f) => new BoundField(f['decl'], f['value'])).toList();
+ .map((f) => new BoundField(f['decl'], f['value']))
+ .toList();
} else {
fields = null;
}
if (map['_nativeFields'] != null) {
- nativeFields = map['_nativeFields']
- .map((f) => new NativeField(f['value'])).toList();
+ nativeFields =
+ map['_nativeFields'].map((f) => new NativeField(f['value'])).toList();
} else {
nativeFields = null;
}
if (map['elements'] != null) {
- // Should be:
- // elements = map['elements'].map((e) => new Guarded<Instance>(e)).toList();
- // some times we obtain object that are not InstanceRef
- elements = map['elements'].map((e) => new Guarded<ServiceObject>(e))
- .toList();
+ // Should be:
+ // elements = map['elements'].map((e) => new Guarded<Instance>(e)).toList();
+ // some times we obtain object that are not InstanceRef
+ elements =
+ map['elements'].map((e) => new Guarded<ServiceObject>(e)).toList();
} else {
elements = null;
}
if (map['associations'] != null) {
- associations = map['associations'].map((a) =>
- new MapAssociation(a['key'], a['value'])).toList();
+ associations = map['associations']
+ .map((a) => new MapAssociation(a['key'], a['value']))
+ .toList();
} else {
associations = null;
- };
+ }
+ ;
if (map['bytes'] != null) {
Uint8List bytes = BASE64.decode(map['bytes']);
switch (map['kind']) {
case "Uint8ClampedList":
- typedElements = bytes.buffer.asUint8ClampedList(); break;
+ typedElements = bytes.buffer.asUint8ClampedList();
+ break;
case "Uint8List":
- typedElements = bytes.buffer.asUint8List(); break;
+ typedElements = bytes.buffer.asUint8List();
+ break;
case "Uint16List":
- typedElements = bytes.buffer.asUint16List(); break;
+ typedElements = bytes.buffer.asUint16List();
+ break;
case "Uint32List":
- typedElements = bytes.buffer.asUint32List(); break;
+ typedElements = bytes.buffer.asUint32List();
+ break;
case "Uint64List":
- typedElements = bytes.buffer.asUint64List(); break;
+ typedElements = bytes.buffer.asUint64List();
+ break;
case "Int8List":
- typedElements = bytes.buffer.asInt8List(); break;
+ typedElements = bytes.buffer.asInt8List();
+ break;
case "Int16List":
- typedElements = bytes.buffer.asInt16List(); break;
+ typedElements = bytes.buffer.asInt16List();
+ break;
case "Int32List":
- typedElements = bytes.buffer.asInt32List(); break;
+ typedElements = bytes.buffer.asInt32List();
+ break;
case "Int64List":
- typedElements = bytes.buffer.asInt64List(); break;
+ typedElements = bytes.buffer.asInt64List();
+ break;
case "Float32List":
- typedElements = bytes.buffer.asFloat32List(); break;
+ typedElements = bytes.buffer.asFloat32List();
+ break;
case "Float64List":
- typedElements = bytes.buffer.asFloat64List(); break;
+ typedElements = bytes.buffer.asFloat64List();
+ break;
case "Int32x4List":
- typedElements = bytes.buffer.asInt32x4List(); break;
+ typedElements = bytes.buffer.asInt32x4List();
+ break;
case "Float32x4List":
- typedElements = bytes.buffer.asFloat32x4List(); break;
+ typedElements = bytes.buffer.asFloat32x4List();
+ break;
case "Float64x2List":
- typedElements = bytes.buffer.asFloat64x2List(); break;
+ typedElements = bytes.buffer.asFloat64x2List();
+ break;
}
} else {
typedElements = null;
@@ -2807,7 +2830,6 @@
String toString() => 'Instance($shortName)';
}
-
class Context extends HeapObject implements M.Context {
Context parentContext;
int length;
@@ -2827,8 +2849,8 @@
return;
}
- variables = (map['variables'] ?? const []).map((element) =>
- new ContextElement(element));
+ variables = (map['variables'] ?? const [])
+ .map((element) => new ContextElement(element));
// We are fully loaded.
_loaded = true;
@@ -2840,31 +2862,47 @@
class ContextElement extends M.ContextElement {
final Guarded<Instance> value;
- ContextElement(Map map)
- : value = new Guarded<Instance>(map['value']);
+ ContextElement(Map map) : value = new Guarded<Instance>(map['value']);
}
M.FunctionKind stringToFunctionKind(String value) {
- switch(value) {
- case 'RegularFunction': return M.FunctionKind.regular;
- case 'ClosureFunction': return M.FunctionKind.closure;
- case 'GetterFunction': return M.FunctionKind.getter;
- case 'SetterFunction': return M.FunctionKind.setter;
- case 'Constructor': return M.FunctionKind.constructor;
- case 'ImplicitGetter': return M.FunctionKind.implicitGetter;
- case 'ImplicitSetter': return M.FunctionKind.implicitSetter;
+ switch (value) {
+ case 'RegularFunction':
+ return M.FunctionKind.regular;
+ case 'ClosureFunction':
+ return M.FunctionKind.closure;
+ case 'GetterFunction':
+ return M.FunctionKind.getter;
+ case 'SetterFunction':
+ return M.FunctionKind.setter;
+ case 'Constructor':
+ return M.FunctionKind.constructor;
+ case 'ImplicitGetter':
+ return M.FunctionKind.implicitGetter;
+ case 'ImplicitSetter':
+ return M.FunctionKind.implicitSetter;
case 'ImplicitStaticFinalGetter':
return M.FunctionKind.implicitStaticFinalGetter;
- case 'IrregexpFunction': return M.FunctionKind.irregexpFunction;
- case 'StaticInitializer': return M.FunctionKind.staticInitializer;
- case 'MethodExtractor': return M.FunctionKind.methodExtractor;
- case 'NoSuchMethodDispatcher': return M.FunctionKind.noSuchMethodDispatcher;
- case 'InvokeFieldDispatcher': return M.FunctionKind.invokeFieldDispatcher;
- case 'Collected': return M.FunctionKind.collected;
- case 'Native': return M.FunctionKind.native;
- case 'Stub': return M.FunctionKind.stub;
- case 'Tag': return M.FunctionKind.tag;
- case 'SignatureFunction': return M.FunctionKind.signatureFunction;
+ case 'IrregexpFunction':
+ return M.FunctionKind.irregexpFunction;
+ case 'StaticInitializer':
+ return M.FunctionKind.staticInitializer;
+ case 'MethodExtractor':
+ return M.FunctionKind.methodExtractor;
+ case 'NoSuchMethodDispatcher':
+ return M.FunctionKind.noSuchMethodDispatcher;
+ case 'InvokeFieldDispatcher':
+ return M.FunctionKind.invokeFieldDispatcher;
+ case 'Collected':
+ return M.FunctionKind.collected;
+ case 'Native':
+ return M.FunctionKind.native;
+ case 'Stub':
+ return M.FunctionKind.stub;
+ case 'Tag':
+ return M.FunctionKind.tag;
+ case 'SignatureFunction':
+ return M.FunctionKind.signatureFunction;
}
Logger.root.severe('Unrecognized function kind: $value');
throw new FallThroughError();
@@ -2912,12 +2950,10 @@
ServiceFunction ownerFunction = dartOwner;
library = ownerFunction.library;
qualifiedName = "${ownerFunction.qualifiedName}.${name}";
-
} else if (dartOwner is Class) {
Class ownerClass = dartOwner;
library = ownerClass.library;
qualifiedName = "${ownerClass.name}.${name}";
-
} else {
library = dartOwner;
qualifiedName = name;
@@ -2974,7 +3010,6 @@
}
class Sentinel extends ServiceObject implements M.Sentinel {
-
M.SentinelKind kind;
String valueAsString;
@@ -3029,7 +3064,6 @@
if (dartOwner is Class) {
Class ownerClass = dartOwner;
library = ownerClass.library;
-
} else {
library = dartOwner;
}
@@ -3041,8 +3075,8 @@
guardNullable = map['_guardNullable'];
if (map['_guardClass'] is Class) {
- guardClass = map['_guardClass'];
- guardClassKind = M.GuardClassKind.single;
+ guardClass = map['_guardClass'];
+ guardClassKind = M.GuardClassKind.single;
} else {
switch (map['_guardClass']) {
case 'various':
@@ -3063,7 +3097,6 @@
String toString() => 'Field(${dartOwner.name}.$name)';
}
-
class ScriptLine {
final Script script;
final int line;
@@ -3168,6 +3201,7 @@
operator ==(other) {
return (script == other.script) && (tokenPos == other.tokenPos);
}
+
int get hashCode => (script.hashCode << 8) | tokenPos;
String toString() => "CallSite($name, $tokenPos)";
@@ -3181,9 +3215,8 @@
CallSiteEntry(this.receiver, this.count, this.target);
factory CallSiteEntry.fromMap(Map entryMap) {
- return new CallSiteEntry(entryMap['receiver'],
- entryMap['count'],
- entryMap['target']);
+ return new CallSiteEntry(
+ entryMap['receiver'], entryMap['count'], entryMap['target']);
}
String toString() => "CallSiteEntry(${receiver.name}, $count)";
@@ -3241,19 +3274,18 @@
var c = source.codeUnitAt(pos);
if (c == 123) return 1; // { - Map literal
- if (c == 91) return 1; // [ - List literal, index, index assignment
+ if (c == 91) return 1; // [ - List literal, index, index assignment
- if (c == 40) return 1; // ( - Closure call
+ if (c == 40) return 1; // ( - Closure call
if (_isOperatorChar(c)) {
- while (++pos < source.length &&
- _isOperatorChar(source.codeUnitAt(pos)));
+ while (++pos < source.length && _isOperatorChar(source.codeUnitAt(pos)));
return pos - column;
}
if (_isInitialIdentifierChar(c)) {
- while (++pos < source.length &&
- _isIdentifierChar(source.codeUnitAt(pos)));
+ while (
+ ++pos < source.length && _isIdentifierChar(source.codeUnitAt(pos)));
return pos - column;
}
@@ -3262,21 +3294,21 @@
static bool _isOperatorChar(int c) {
switch (c) {
- case 25: // %
- case 26: // &
- case 42: // *
- case 43: // +
- case 45: // -:
- case 47: // /
- case 60: // <
- case 61: // =
- case 62: // >
- case 94: // ^
- case 124: // |
- case 126: // ~
- return true;
- default:
- return false;
+ case 25: // %
+ case 26: // &
+ case 42: // *
+ case 43: // +
+ case 45: // -:
+ case 47: // /
+ case 60: // <
+ case 61: // =
+ case 62: // >
+ case 94: // ^
+ case 124: // |
+ case 126: // ~
+ return true;
+ default:
+ return false;
}
}
@@ -3333,17 +3365,17 @@
for (var pos = 1; pos < line.length; pos += 2) {
// ...and is followed by (token offset, col number) pairs.
var tokenOffset = line[pos];
- var colNumber = line[pos+1];
+ var colNumber = line[pos + 1];
if (firstTokenPos == null) {
// Mark first token position.
firstTokenPos = tokenOffset;
lastTokenPos = tokenOffset;
} else {
// Keep track of max and min token positions.
- firstTokenPos = (firstTokenPos <= tokenOffset) ?
- firstTokenPos : tokenOffset;
- lastTokenPos = (lastTokenPos >= tokenOffset) ?
- lastTokenPos : tokenOffset;
+ firstTokenPos =
+ (firstTokenPos <= tokenOffset) ? firstTokenPos : tokenOffset;
+ lastTokenPos =
+ (lastTokenPos >= tokenOffset) ? lastTokenPos : tokenOffset;
}
_tokenToLine[tokenOffset] = lineNumber;
_tokenToCol[tokenOffset] = colNumber;
@@ -3396,10 +3428,7 @@
}
List<LocalVarLocation> scanLineForLocalVariableLocations(Pattern pattern,
- String name,
- String lineContents,
- int lineNumber,
- int columnOffset) {
+ String name, String lineContents, int lineNumber, int columnOffset) {
var r = <LocalVarLocation>[];
pattern.allMatches(lineContents).forEach((Match match) {
@@ -3408,18 +3437,16 @@
var nameStart = match.input.indexOf(name, match.start);
var column = nameStart + columnOffset;
var endColumn = column + name.length;
- var localVarLocation = new LocalVarLocation(lineNumber,
- column,
- endColumn);
+ var localVarLocation =
+ new LocalVarLocation(lineNumber, column, endColumn);
r.add(localVarLocation);
});
return r;
}
- List<LocalVarLocation> scanForLocalVariableLocations(String name,
- int tokenPos,
- int endTokenPos) {
+ List<LocalVarLocation> scanForLocalVariableLocations(
+ String name, int tokenPos, int endTokenPos) {
// A pattern that matches:
// start of line OR non-(alpha numeric OR period) character followed by
// name followed by
@@ -3468,22 +3495,16 @@
// io_sink.dart snapshotted source line 23 ends at column 35.
lastColumn = math.min(getLine(line).text.length, lastColumn);
lineContents = getLine(line).text.substring(column, lastColumn - 1);
- return scanLineForLocalVariableLocations(pattern,
- name,
- lineContents,
- line,
- column);
+ return scanLineForLocalVariableLocations(
+ pattern, name, lineContents, line, column);
}
}
// Scan first line.
if (!getLine(line).isTrivial) {
lineContents = getLine(line).text.substring(column);
- r.addAll(scanLineForLocalVariableLocations(pattern,
- name,
- lineContents,
- line++,
- column));
+ r.addAll(scanLineForLocalVariableLocations(
+ pattern, name, lineContents, line++, column));
}
// Scan middle lines.
@@ -3493,12 +3514,8 @@
continue;
}
lineContents = getLine(line).text;
- r.addAll(
- scanLineForLocalVariableLocations(pattern,
- name,
- lineContents,
- line++,
- 0));
+ r.addAll(scanLineForLocalVariableLocations(
+ pattern, name, lineContents, line++, 0));
}
// Scan last line.
@@ -3509,12 +3526,8 @@
// io_sink.dart snapshotted source line 23 ends at column 35.
lastColumn = math.min(getLine(line).text.length, lastColumn);
lineContents = getLine(line).text.substring(0, lastColumn - 1);
- r.addAll(
- scanLineForLocalVariableLocations(pattern,
- name,
- lineContents,
- line,
- 0));
+ r.addAll(scanLineForLocalVariableLocations(
+ pattern, name, lineContents, line, 0));
}
return r;
}
@@ -3528,8 +3541,8 @@
final String kind;
Script script;
String formattedLine;
- PcDescriptor(this.pcOffset, this.deoptId, this.tokenPos, this.tryIndex,
- this.kind);
+ PcDescriptor(
+ this.pcOffset, this.deoptId, this.tokenPos, this.tryIndex, this.kind);
String formattedDeoptId() {
if (deoptId == -1) {
@@ -3566,8 +3579,7 @@
bool get immutable => true;
final List<PcDescriptor> descriptors = <PcDescriptor>[];
- PcDescriptors._empty(ServiceObjectOwner owner) : super._empty(owner) {
- }
+ PcDescriptors._empty(ServiceObjectOwner owner) : super._empty(owner) {}
void _update(Map m, bool mapIsRef) {
if (mapIsRef) {
@@ -3578,13 +3590,13 @@
size = m['size'];
descriptors.clear();
for (var descriptor in m['members']) {
- var pcOffset = int.parse(descriptor['pcOffset'], radix:16);
+ var pcOffset = int.parse(descriptor['pcOffset'], radix: 16);
var deoptId = descriptor['deoptId'];
var tokenPos = descriptor['tokenPos'];
var tryIndex = descriptor['tryIndex'];
var kind = descriptor['kind'].trim();
- descriptors.add(
- new PcDescriptor(pcOffset, deoptId, tokenPos, tryIndex, kind));
+ descriptors
+ .add(new PcDescriptor(pcOffset, deoptId, tokenPos, tryIndex, kind));
}
}
}
@@ -3599,7 +3611,7 @@
final String kind;
LocalVarDescriptor(this.id, this.name, this.index, this.beginPos, this.endPos,
- this.scopeId, this.kind);
+ this.scopeId, this.kind);
}
class LocalVarDescriptors extends ServiceObject {
@@ -3625,9 +3637,8 @@
var endPos = descriptor['endPos'];
var scopeId = descriptor['scopeId'];
var kind = descriptor['kind'].trim();
- descriptors.add(
- new LocalVarDescriptor(id, name, index, beginPos, endPos, scopeId,
- kind));
+ descriptors.add(new LocalVarDescriptor(
+ id, name, index, beginPos, endPos, scopeId, kind));
}
}
}
@@ -3670,11 +3681,11 @@
}
ObjectPoolEntry._fromObject(this.asObject, this.offset)
- : kind = M.ObjectPoolEntryKind.object,
- asInteger = null;
+ : kind = M.ObjectPoolEntryKind.object,
+ asInteger = null;
ObjectPoolEntry._fromInteger(this.kind, this.asInteger, this.offset)
- : asObject = null;
+ : asObject = null;
}
M.ObjectPoolEntryKind stringToObjectPoolEntryKind(String kind) {
@@ -3804,11 +3815,8 @@
CodeInstruction jumpTarget;
List<PcDescriptor> descriptors = <PcDescriptor>[];
- CodeInstruction(this.address,
- this.pcOffset,
- this.machine,
- this.human,
- this.object);
+ CodeInstruction(
+ this.address, this.pcOffset, this.machine, this.human, this.object);
bool get isComment => address == 0;
bool get hasDescriptors => descriptors.length > 0;
@@ -3830,14 +3838,14 @@
address = address.substring(2);
}
try {
- return int.parse(address, radix:16);
+ return int.parse(address, radix: 16);
} catch (_) {
return 0;
}
}
- void _resolveJumpTarget(List<CodeInstruction> instructionsByAddressOffset,
- int startAddress) {
+ void _resolveJumpTarget(
+ List<CodeInstruction> instructionsByAddressOffset, int startAddress) {
if (!_isJumpInstruction()) {
return;
}
@@ -3918,14 +3926,13 @@
// Already done.
return;
}
- if (kind != M.CodeKind.dart){
+ if (kind != M.CodeKind.dart) {
return;
}
if (function == null) {
return;
}
- if ((function.location == null) ||
- (function.location.script == null)) {
+ if ((function.location == null) || (function.location.script == null)) {
// Attempt to load the function.
function.load().then((func) {
var script = function.location.script;
@@ -3964,8 +3971,8 @@
return;
}
_loaded = true;
- startAddress = int.parse(m['_startAddress'], radix:16);
- endAddress = int.parse(m['_endAddress'], radix:16);
+ startAddress = int.parse(m['_startAddress'], radix: 16);
+ endAddress = int.parse(m['_endAddress'], radix: 16);
function = isolate.getFromMap(m['function']);
objectPool = isolate.getFromMap(m['_objectPool']);
var disassembly = m['_disassembly'];
@@ -4014,7 +4021,7 @@
}
void _processInline(List<ServiceFunction> inlinedFunctionsTable,
- List<List<int>> inlinedIntervals) {
+ List<List<int>> inlinedIntervals) {
for (var i = 0; i < inlinedIntervals.length; i++) {
var inlinedInterval = inlinedIntervals[i];
var start = inlinedInterval[0] + startAddress;
@@ -4041,7 +4048,7 @@
assert((disassembly.length % 4) == 0);
for (var i = 0; i < disassembly.length; i += 4) {
- var address = 0; // Assume code comment.
+ var address = 0; // Assume code comment.
var machine = disassembly[i + 1];
var human = disassembly[i + 2];
var object = disassembly[i + 3];
@@ -4051,7 +4058,7 @@
var pcOffset = 0;
if (disassembly[i] != null) {
// Not a code comment, extract address.
- address = int.parse(disassembly[i], radix:16);
+ address = int.parse(disassembly[i], radix: 16);
pcOffset = address - startAddress;
}
var instruction =
@@ -4069,7 +4076,7 @@
void _processDescriptors(List<Map> descriptors) {
for (Map descriptor in descriptors) {
- var pcOffset = int.parse(descriptor['pcOffset'], radix:16);
+ var pcOffset = int.parse(descriptor['pcOffset'], radix: 16);
var address = startAddress + pcOffset;
var deoptId = descriptor['deoptId'];
var tokenPos = descriptor['tokenPos'];
@@ -4078,14 +4085,11 @@
var instruction = instructionsByAddressOffset[address - startAddress];
if (instruction != null) {
- instruction.descriptors.add(new PcDescriptor(pcOffset,
- deoptId,
- tokenPos,
- tryIndex,
- kind));
+ instruction.descriptors
+ .add(new PcDescriptor(pcOffset, deoptId, tokenPos, tryIndex, kind));
} else {
Logger.root.warning(
- 'Could not find instruction with pc descriptor address: $address');
+ 'Could not find instruction with pc descriptor address: $address');
}
}
}
@@ -4095,13 +4099,11 @@
return (address >= startAddress) && (address < endAddress);
}
- bool get isDartCode => (kind == M.CodeKind.dart) ||
- (kind == M.CodeKind.stub);
+ bool get isDartCode => (kind == M.CodeKind.dart) || (kind == M.CodeKind.stub);
String toString() => 'Code($kind, $name)';
}
-
class SocketKind {
final _value;
const SocketKind._internal(this._value);
@@ -4120,6 +4122,7 @@
Logger.root.warning('Unknown socket kind $s');
throw new FallThroughError();
}
+
static const Listening = const SocketKind._internal('Listening');
static const Normal = const SocketKind._internal('Normal');
static const Pipe = const SocketKind._internal('Pipe');
@@ -4134,9 +4137,8 @@
final int writeCalls;
final int available;
- SocketStats(this.bytesRead, this.bytesWritten,
- this.readCalls, this.writeCalls,
- this.available);
+ SocketStats(this.bytesRead, this.bytesWritten, this.readCalls,
+ this.writeCalls, this.available);
}
/// A peer to a Socket in dart:io. Sockets can represent network sockets or
@@ -4203,14 +4205,13 @@
}
class ServiceMetric extends ServiceObject implements M.Metric {
- ServiceMetric._empty(ServiceObjectOwner owner) : super._empty(owner) {
- }
+ ServiceMetric._empty(ServiceObjectOwner owner) : super._empty(owner) {}
bool get immutable => false;
Future<Map> _fetchDirect({int count: kDefaultFieldLimit}) {
assert(owner is Isolate);
- return isolate.invokeRpcNoUpgrade('_getIsolateMetric', { 'metricId': id });
+ return isolate.invokeRpcNoUpgrade('_getIsolateMetric', {'metricId': id});
}
String description;
@@ -4256,7 +4257,6 @@
String toString() => "Frame(${function.qualifiedName} $location)";
}
-
class ServiceMessage extends ServiceObject {
int index;
String messageObjectId;
@@ -4278,7 +4278,6 @@
}
}
-
// Helper function to extract possible breakpoint locations from a
// SourceReport for some script.
Set<int> getPossibleBreakpointLines(ServiceMap report, Script script) {
@@ -4320,7 +4319,6 @@
return result;
}
-
// Returns true if [map] is a service map. i.e. it has the following keys:
// 'id' and a 'type'.
bool _isServiceMap(Map m) {
diff --git a/runtime/observatory/lib/tracer.dart b/runtime/observatory/lib/tracer.dart
index ffe0892..dc9c4b6 100644
--- a/runtime/observatory/lib/tracer.dart
+++ b/runtime/observatory/lib/tracer.dart
@@ -13,13 +13,13 @@
if (src is Map) {
var dest = {};
src.forEach((key, val) {
- dest[key] = _deepCopy(val);
+ dest[key] = _deepCopy(val);
});
return dest;
} else if (src is List) {
var dest = [];
src.forEach((val) {
- dest.add(_deepCopy(val));
+ dest.add(_deepCopy(val));
});
return dest;
} else {
@@ -54,6 +54,7 @@
_current = new Tracer();
}
}
+
static void stop() {
if (_current != null) {
_current.cancel();
@@ -74,9 +75,9 @@
_time = new Stopwatch();
_time.start();
loggerSub = Logger.root.onRecord.listen((LogRecord rec) {
- // Echo all log messages to the trace.
- trace('${rec.level.name}: ${rec.message}');
- });
+ // Echo all log messages to the trace.
+ trace('${rec.level.name}: ${rec.message}');
+ });
reset();
}
diff --git a/runtime/observatory/lib/utils.dart b/runtime/observatory/lib/utils.dart
index 8796e3d6..3e1f025 100644
--- a/runtime/observatory/lib/utils.dart
+++ b/runtime/observatory/lib/utils.dart
@@ -8,7 +8,6 @@
import 'dart:math';
class Utils {
-
static String formatPercentNormalized(double x) {
var percent = 100.0 * x;
return '${percent.toStringAsFixed(2)}%';
@@ -75,16 +74,16 @@
if (hours > 0) {
return ("${zeroPad(hours,2)}"
- ":${zeroPad(minutes,2)}"
- ":${zeroPad(seconds,2)}"
- ".${zeroPad(millis,3)}");
+ ":${zeroPad(minutes,2)}"
+ ":${zeroPad(seconds,2)}"
+ ".${zeroPad(millis,3)}");
} else if (minutes > 0) {
return ("${zeroPad(minutes,2)}"
- ":${zeroPad(seconds,2)}"
- ".${zeroPad(millis,3)}");
+ ":${zeroPad(seconds,2)}"
+ ".${zeroPad(millis,3)}");
} else {
return ("${zeroPad(seconds,2)}"
- ".${zeroPad(millis,3)}");
+ ".${zeroPad(millis,3)}");
}
}
@@ -137,9 +136,9 @@
static String formatDateTime(DateTime now) {
return '${now.year}-${now.month}-${now.day} '
- '${now.hour.toString().padLeft(2)}:'
- '${now.minute.toString().padLeft(2)}:'
- '${now.second.toString().padLeft(2)}';
+ '${now.hour.toString().padLeft(2)}:'
+ '${now.minute.toString().padLeft(2)}:'
+ '${now.second.toString().padLeft(2)}';
}
static String formatSeconds(double x) {
@@ -151,30 +150,40 @@
}
static String formatDurationInSeconds(Duration x) =>
- formatSeconds(x.inMicroseconds / Duration.MICROSECONDS_PER_SECOND);
+ formatSeconds(x.inMicroseconds / Duration.MICROSECONDS_PER_SECOND);
static String formatDurationInMilliseconds(Duration x) =>
- formatMillis(x.inMicroseconds / Duration.MICROSECONDS_PER_MILLISECOND);
+ formatMillis(x.inMicroseconds / Duration.MICROSECONDS_PER_MILLISECOND);
static bool runningInJavaScript() => identical(1.0, 1);
- static formatStringAsLiteral(String value, [bool wasTruncated=false]) {
+ static formatStringAsLiteral(String value, [bool wasTruncated = false]) {
var result = new List();
result.add("'".codeUnitAt(0));
for (int codeUnit in value.codeUnits) {
- if (codeUnit == '\n'.codeUnitAt(0)) result.addAll('\\n'.codeUnits);
- else if (codeUnit == '\r'.codeUnitAt(0)) result.addAll('\\r'.codeUnits);
- else if (codeUnit == '\f'.codeUnitAt(0)) result.addAll('\\f'.codeUnits);
- else if (codeUnit == '\b'.codeUnitAt(0)) result.addAll('\\b'.codeUnits);
- else if (codeUnit == '\t'.codeUnitAt(0)) result.addAll('\\t'.codeUnits);
- else if (codeUnit == '\v'.codeUnitAt(0)) result.addAll('\\v'.codeUnits);
- else if (codeUnit == '\$'.codeUnitAt(0)) result.addAll('\\\$'.codeUnits);
- else if (codeUnit == '\\'.codeUnitAt(0)) result.addAll('\\\\'.codeUnits);
- else if (codeUnit == "'".codeUnitAt(0)) result.addAll("'".codeUnits);
+ if (codeUnit == '\n'.codeUnitAt(0))
+ result.addAll('\\n'.codeUnits);
+ else if (codeUnit == '\r'.codeUnitAt(0))
+ result.addAll('\\r'.codeUnits);
+ else if (codeUnit == '\f'.codeUnitAt(0))
+ result.addAll('\\f'.codeUnits);
+ else if (codeUnit == '\b'.codeUnitAt(0))
+ result.addAll('\\b'.codeUnits);
+ else if (codeUnit == '\t'.codeUnitAt(0))
+ result.addAll('\\t'.codeUnits);
+ else if (codeUnit == '\v'.codeUnitAt(0))
+ result.addAll('\\v'.codeUnits);
+ else if (codeUnit == '\$'.codeUnitAt(0))
+ result.addAll('\\\$'.codeUnits);
+ else if (codeUnit == '\\'.codeUnitAt(0))
+ result.addAll('\\\\'.codeUnits);
+ else if (codeUnit == "'".codeUnitAt(0))
+ result.addAll("'".codeUnits);
else if (codeUnit < 32) {
- var escapeSequence = "\\u" + codeUnit.toRadixString(16).padLeft(4, "0");
- result.addAll(escapeSequence.codeUnits);
- } else result.add(codeUnit);
+ var escapeSequence = "\\u" + codeUnit.toRadixString(16).padLeft(4, "0");
+ result.addAll(escapeSequence.codeUnits);
+ } else
+ result.add(codeUnit);
}
if (wasTruncated) {
result.addAll("...".codeUnits);
@@ -200,8 +209,8 @@
return;
}
_timer = new Timer(Duration.ZERO, () {
- _timer = null;
- callback();
+ _timer = null;
+ callback();
});
}
}
diff --git a/runtime/observatory/observatory.gypi b/runtime/observatory/observatory.gypi
index 39a6db9d..ed241c5 100644
--- a/runtime/observatory/observatory.gypi
+++ b/runtime/observatory/observatory.gypi
@@ -12,8 +12,6 @@
'type': 'none',
'dependencies': [
'dart_bootstrap#host',
- # We use packages for building
- '../pkg/pkg.gyp:pkg_packages#target',
],
'toolsets': ['host'],
'actions': [
@@ -21,7 +19,6 @@
'action_name': 'get_obsevatory_dependencies',
'inputs': [
'../../tools/observatory_tool.py',
- '<(SHARED_INTERMEDIATE_DIR)/packages.stamp',
'pubspec.yaml',
],
'outputs': [
@@ -31,7 +28,6 @@
'python',
'../tools/observatory_tool.py',
'--sdk=True',
- '--package-root', '<(PRODUCT_DIR)/packages',
'--stamp',
'<(gen_source_dir)/observatory_packages.stamp',
'--dart-executable',
@@ -68,7 +64,6 @@
'python',
'../tools/observatory_tool.py',
'--sdk=True',
- '--package-root', '<(PRODUCT_DIR)/packages',
'--dart-executable',
'<(PRODUCT_DIR)/<(EXECUTABLE_PREFIX)dart_bootstrap<(EXECUTABLE_SUFFIX)',
'--directory', 'observatory',
@@ -89,7 +84,6 @@
'python',
'../tools/observatory_tool.py',
'--sdk=True',
- '--package-root', '<(PRODUCT_DIR)/packages',
'--dart-executable',
'<(PRODUCT_DIR)/<(EXECUTABLE_PREFIX)dart_bootstrap<(EXECUTABLE_SUFFIX)',
'--directory', '<(PRODUCT_DIR)/observatory/',
diff --git a/runtime/observatory/pubspec.yaml b/runtime/observatory/pubspec.yaml
index 20f6ac4..b2f6c3b5 100644
--- a/runtime/observatory/pubspec.yaml
+++ b/runtime/observatory/pubspec.yaml
@@ -6,6 +6,7 @@
- $dart2js:
suppressWarnings: false
commandLineOptions: [--show-package-warnings]
+ minify: false
dependencies:
args: any
charted: ^0.3.0
diff --git a/runtime/observatory/tests/observatory_ui/vm_connect/element_test.dart b/runtime/observatory/tests/observatory_ui/vm_connect/element_test.dart
index 84026e5..1a46af5 100644
--- a/runtime/observatory/tests/observatory_ui/vm_connect/element_test.dart
+++ b/runtime/observatory/tests/observatory_ui/vm_connect/element_test.dart
@@ -45,7 +45,6 @@
document.body.append(e);
await e.onRendered.first;
expect(targets.listInvoked, isTrue, reason: 'should invoke list()');
- expect(targets.currentInvoked, isTrue, reason: 'should invoke current');
expect(e.children.length, isNonZero, reason: 'has elements');
expect(e.querySelectorAll(nTag).length, equals(1));
expect(e.querySelectorAll(tTag).length, equals(2));
@@ -72,7 +71,7 @@
});
group('invokes', () {
test('add on click', () async {
- final address = 'ws://host:1234';
+ final address = 'ws://host:1234/ws';
final list = <TargetMock>[const TargetMock(name: 't-1')];
final targets = new TargetRepositoryMock(list: list,
add: expectAsync((String val) {
diff --git a/runtime/observatory/tests/service/async_generator_breakpoint_test.dart b/runtime/observatory/tests/service/async_generator_breakpoint_test.dart
index 7a26e42..aef2e8e 100644
--- a/runtime/observatory/tests/service/async_generator_breakpoint_test.dart
+++ b/runtime/observatory/tests/service/async_generator_breakpoint_test.dart
@@ -75,7 +75,7 @@
var bp = event.breakpoint;
print('Hit $bp');
hits.add(bp);
- isolate.resume();
+ await isolate.resume();
if (hits.length == 5) break;
}
diff --git a/runtime/observatory/tests/service/test_helper.dart b/runtime/observatory/tests/service/test_helper.dart
index 4828557..858a233 100644
--- a/runtime/observatory/tests/service/test_helper.dart
+++ b/runtime/observatory/tests/service/test_helper.dart
@@ -8,6 +8,7 @@
import 'dart:convert';
import 'dart:io';
import 'package:observatory/service_io.dart';
+import 'package:stack_trace/stack_trace.dart';
import 'service_test_common.dart';
/// Will be set to the http address of the VM's service protocol before
@@ -15,11 +16,6 @@
String serviceHttpAddress;
String serviceWebsocketAddress;
-bool _isWebSocketDisconnect(e) {
- return e is NetworkRpcException;
-}
-
-
const String _TESTEE_ENV_KEY = 'SERVICE_TEST_TESTEE';
const Map<String, String> _TESTEE_SPAWN_ENV = const {
_TESTEE_ENV_KEY: 'true'
@@ -271,7 +267,7 @@
serviceWebsocketAddress = 'ws://localhost:$port/ws';
serviceHttpAddress = 'http://localhost:$port';
var name = Platform.script.pathSegments.last;
- runZoned(() async {
+ Chain.capture(() async {
var vm =
new WebSocketVM(new WebSocketVMTarget(serviceWebsocketAddress));
print('Loading VM...');
@@ -302,11 +298,8 @@
await test(isolate);
}
}
- }, onError: (e, st) {
- if (!_isWebSocketDisconnect(e)) {
- print('Unexpected exception in service tests: $e $st');
- throw e;
- }
+ }, onError: (error, stackTrace) {
+ print('Unexpected exception in service tests: $error\n$stackTrace');
});
}
}
@@ -338,7 +331,7 @@
serviceWebsocketAddress = 'ws://localhost:$port/ws';
serviceHttpAddress = 'http://localhost:$port';
var name = Platform.script.pathSegments.last;
- runZoned(() async {
+ Chain.capture(() async {
var vm =
new WebSocketVM(new WebSocketVMTarget(serviceWebsocketAddress));
print('Loading VM...');
@@ -371,19 +364,10 @@
}
await process.requestExit();
- }, onError: (e, st) {
+ }, onError: (error, stackTrace) {
process.requestExit();
- // TODO: remove this workaround.
- // This is necessary due to non awaited operations.
- // E.G. object.dart (398~402)
- // When an exception is thrown inside a test (directly or via await) the
- // stacktrace is non-null and shows where the exception has been thrown.
- // If vice versa the exception is due to an error in a non-awaited
- // Future the stacktrace is null.
- if (st != null || !_isWebSocketDisconnect(e)) {
- print('Unexpected exception in service tests: $e $st');
- throw e;
- }
+ print('Unexpected exception in service tests: $error\n$stackTrace');
+ throw error;
});
});
}
diff --git a/runtime/observatory/tool/ensure_dartfmt.sh b/runtime/observatory/tool/ensure_dartfmt.sh
new file mode 100755
index 0000000..6aa50e9
--- /dev/null
+++ b/runtime/observatory/tool/ensure_dartfmt.sh
@@ -0,0 +1,15 @@
+#!/bin/sh
+
+dart_files=$(find lib web -name "*.dart")
+[ -z "$dart_files" ] && exit 0
+
+unformatted=$(dartfmt -n $dart_files)
+[ -z "$unformatted" ] && exit 0
+
+# Some files are not dartfmt'd. Print message and fail.
+echo >&2 "dart files must be formatted with dartfmt. Please run:"
+for fn in $unformatted; do
+ echo >&2 " dartfmt -w $PWD/$fn"
+done
+
+exit 1
diff --git a/runtime/observatory/web/main.dart b/runtime/observatory/web/main.dart
index 4f63d25..07fcb1a 100644
--- a/runtime/observatory/web/main.dart
+++ b/runtime/observatory/web/main.dart
@@ -5,14 +5,17 @@
import 'dart:html';
import 'package:logging/logging.dart';
import 'package:observatory/elements.dart';
+import 'package:stack_trace/stack_trace.dart';
main() async {
- Logger.root.level = Level.INFO;
- Logger.root.onRecord.listen((LogRecord rec) {
+ Chain.capture(() async {
+ Logger.root.level = Level.INFO;
+ Logger.root.onRecord.listen((LogRecord rec) {
print('${rec.level.name}: ${rec.time}: ${rec.message}');
+ });
+ await initElements();
+ Logger.root.info('Starting Observatory');
+ document.body.children
+ .insert(0, document.createElement('observatory-application'));
});
- await initElements();
- Logger.root.info('Starting Observatory');
- document.body.children
- .insert(0, document.createElement('observatory-application'));
}
diff --git a/runtime/platform/globals.h b/runtime/platform/globals.h
index 3a3ed26..114c47d 100644
--- a/runtime/platform/globals.h
+++ b/runtime/platform/globals.h
@@ -138,11 +138,16 @@
#endif // defined(DEBUG)
#endif // defined(PRODUCT)
-
#if defined(DART_PRECOMPILED_RUNTIME) && defined(DART_PRECOMPILER)
#error DART_PRECOMPILED_RUNTIME and DART_PRECOMPILER are mutually exclusive
#endif // defined(DART_PRECOMPILED_RUNTIME) && defined(DART_PRECOMPILER)
+#if defined(DART_PRECOMPILED_RUNTIME)
+#define NOT_IN_PRECOMPILED(code)
+#else
+#define NOT_IN_PRECOMPILED(code) code
+#endif // defined(DART_PRECOMPILED_RUNTIME)
+
namespace dart {
struct simd128_value_t {
diff --git a/runtime/tests/vm/vm.status b/runtime/tests/vm/vm.status
index ebb0df9..61d2bac 100644
--- a/runtime/tests/vm/vm.status
+++ b/runtime/tests/vm/vm.status
@@ -17,6 +17,9 @@
cc/Fail1: Fail
cc/Fail2: Fail
+cc/Dart2JSCompileAll: Crash # Issue 27369
+cc/Dart2JSCompilerStats: Crash # Issue 27369
+
cc/SNPrint_BadArgs: Skip
# Flaky on buildbot. Issue 5133 and 10409.
diff --git a/runtime/tools/gyp/runtime-configurations.gypi b/runtime/tools/gyp/runtime-configurations.gypi
index e5fc998..0b993ca 100644
--- a/runtime/tools/gyp/runtime-configurations.gypi
+++ b/runtime/tools/gyp/runtime-configurations.gypi
@@ -9,6 +9,7 @@
# then do not build the native libraries supporting dart:io.
'dart_io_support%': 0,
'dart_io_secure_socket%': 1,
+ 'asan%': 0,
# Intel VTune related variables.
'dart_vtune_support%': 0,
'conditions': [
diff --git a/runtime/vm/atomic.h b/runtime/vm/atomic.h
index d6a833b..e16eee1 100644
--- a/runtime/vm/atomic.h
+++ b/runtime/vm/atomic.h
@@ -20,6 +20,7 @@
// NOTE: Not to be used for any atomic operations involving memory locations
// that are accessed by generated code.
static uintptr_t FetchAndIncrement(uintptr_t* p);
+ static intptr_t FetchAndIncrement(intptr_t* p);
// Atomically increment the value at p by 'value'.
//
@@ -34,6 +35,7 @@
// NOTE: Not to be used for any atomic operations involving memory locations
// that are accessed by generated code.
static uintptr_t FetchAndDecrement(uintptr_t* p);
+ static intptr_t FetchAndDecrement(intptr_t* p);
// Atomically decrement the value at p by 'value'.
//
diff --git a/runtime/vm/atomic_android.h b/runtime/vm/atomic_android.h
index 689173a..aa2b623 100644
--- a/runtime/vm/atomic_android.h
+++ b/runtime/vm/atomic_android.h
@@ -21,6 +21,11 @@
}
+inline intptr_t AtomicOperations::FetchAndIncrement(intptr_t* p) {
+ return __sync_fetch_and_add(p, 1);
+}
+
+
inline void AtomicOperations::IncrementBy(intptr_t* p, intptr_t value) {
__sync_fetch_and_add(p, value);
}
@@ -36,6 +41,11 @@
}
+inline intptr_t AtomicOperations::FetchAndDecrement(intptr_t* p) {
+ return __sync_fetch_and_sub(p, 1);
+}
+
+
inline void AtomicOperations::DecrementBy(intptr_t* p, intptr_t value) {
__sync_fetch_and_sub(p, value);
}
diff --git a/runtime/vm/atomic_fuchsia.h b/runtime/vm/atomic_fuchsia.h
index 67dd329..c44c080 100644
--- a/runtime/vm/atomic_fuchsia.h
+++ b/runtime/vm/atomic_fuchsia.h
@@ -20,6 +20,11 @@
}
+inline intptr_t AtomicOperations::FetchAndIncrement(intptr_t* p) {
+ return __sync_fetch_and_add(p, 1);
+}
+
+
inline void AtomicOperations::IncrementBy(intptr_t* p, intptr_t value) {
__sync_fetch_and_add(p, value);
}
@@ -35,6 +40,11 @@
}
+inline intptr_t AtomicOperations::FetchAndDecrement(intptr_t* p) {
+ return __sync_fetch_and_sub(p, 1);
+}
+
+
inline void AtomicOperations::DecrementBy(intptr_t* p, intptr_t value) {
__sync_fetch_and_sub(p, value);
}
diff --git a/runtime/vm/atomic_linux.h b/runtime/vm/atomic_linux.h
index 18456cf..350bced 100644
--- a/runtime/vm/atomic_linux.h
+++ b/runtime/vm/atomic_linux.h
@@ -21,6 +21,11 @@
}
+inline intptr_t AtomicOperations::FetchAndIncrement(intptr_t* p) {
+ return __sync_fetch_and_add(p, 1);
+}
+
+
inline void AtomicOperations::IncrementBy(intptr_t* p, intptr_t value) {
__sync_fetch_and_add(p, value);
}
@@ -41,6 +46,11 @@
}
+inline intptr_t AtomicOperations::FetchAndDecrement(intptr_t* p) {
+ return __sync_fetch_and_sub(p, 1);
+}
+
+
inline void AtomicOperations::DecrementBy(intptr_t* p, intptr_t value) {
__sync_fetch_and_sub(p, value);
}
diff --git a/runtime/vm/atomic_macos.h b/runtime/vm/atomic_macos.h
index 479ca30..cdd57d4 100644
--- a/runtime/vm/atomic_macos.h
+++ b/runtime/vm/atomic_macos.h
@@ -21,6 +21,11 @@
}
+inline intptr_t AtomicOperations::FetchAndIncrement(intptr_t* p) {
+ return __sync_fetch_and_add(p, 1);
+}
+
+
inline void AtomicOperations::IncrementBy(intptr_t* p, intptr_t value) {
__sync_fetch_and_add(p, value);
}
@@ -36,6 +41,11 @@
}
+inline intptr_t AtomicOperations::FetchAndDecrement(intptr_t* p) {
+ return __sync_fetch_and_sub(p, 1);
+}
+
+
inline void AtomicOperations::DecrementBy(intptr_t* p, intptr_t value) {
__sync_fetch_and_sub(p, value);
}
diff --git a/runtime/vm/atomic_test.cc b/runtime/vm/atomic_test.cc
index 6973d8b..262a328 100644
--- a/runtime/vm/atomic_test.cc
+++ b/runtime/vm/atomic_test.cc
@@ -26,6 +26,22 @@
}
+UNIT_TEST_CASE(FetchAndIncrementSigned) {
+ intptr_t v = -42;
+ EXPECT_EQ(static_cast<intptr_t>(-42),
+ AtomicOperations::FetchAndIncrement(&v));
+ EXPECT_EQ(static_cast<intptr_t>(-41), v);
+}
+
+
+UNIT_TEST_CASE(FetchAndDecrementSigned) {
+ intptr_t v = -42;
+ EXPECT_EQ(static_cast<intptr_t>(-42),
+ AtomicOperations::FetchAndDecrement(&v));
+ EXPECT_EQ(static_cast<intptr_t>(-43), v);
+}
+
+
UNIT_TEST_CASE(IncrementBy) {
intptr_t v = 42;
AtomicOperations::IncrementBy(&v, 100);
diff --git a/runtime/vm/atomic_win.h b/runtime/vm/atomic_win.h
index 38ec10a..2f8ee20 100644
--- a/runtime/vm/atomic_win.h
+++ b/runtime/vm/atomic_win.h
@@ -28,6 +28,19 @@
}
+inline intptr_t AtomicOperations::FetchAndIncrement(intptr_t* p) {
+#if defined(HOST_ARCH_X64)
+ return static_cast<intptr_t>(
+ InterlockedIncrement64(reinterpret_cast<LONGLONG*>(p))) - 1;
+#elif defined(HOST_ARCH_IA32)
+ return static_cast<intptr_t>(
+ InterlockedIncrement(reinterpret_cast<LONG*>(p))) - 1;
+#else
+#error Unsupported host architecture.
+#endif
+}
+
+
inline void AtomicOperations::IncrementBy(intptr_t* p, intptr_t value) {
#if defined(HOST_ARCH_X64)
InterlockedExchangeAdd64(reinterpret_cast<LONGLONG*>(p),
@@ -64,6 +77,19 @@
}
+inline intptr_t AtomicOperations::FetchAndDecrement(intptr_t* p) {
+#if defined(HOST_ARCH_X64)
+ return static_cast<intptr_t>(
+ InterlockedDecrement64(reinterpret_cast<LONGLONG*>(p))) + 1;
+#elif defined(HOST_ARCH_IA32)
+ return static_cast<intptr_t>(
+ InterlockedDecrement(reinterpret_cast<LONG*>(p))) + 1;
+#else
+#error Unsupported host architecture.
+#endif
+}
+
+
inline void AtomicOperations::DecrementBy(intptr_t* p, intptr_t value) {
#if defined(HOST_ARCH_X64)
InterlockedExchangeAdd64(reinterpret_cast<LONGLONG*>(p),
diff --git a/runtime/vm/class_finalizer.cc b/runtime/vm/class_finalizer.cc
index 1191301..8d9c266 100644
--- a/runtime/vm/class_finalizer.cc
+++ b/runtime/vm/class_finalizer.cc
@@ -1693,6 +1693,7 @@
TypeParameter& cloned_param = TypeParameter::Handle(zone);
String& param_name = String::Handle(zone);
AbstractType& param_bound = AbstractType::Handle(zone);
+ Function& null_function = Function::Handle(zone);
intptr_t cloned_index = 0;
// First, clone the super class type parameters. Rename them so that
@@ -1718,6 +1719,7 @@
param_name = Symbols::FromConcat(thread,
param_name, Symbols::Backtick());
cloned_param = TypeParameter::New(mixin_app_class,
+ null_function,
cloned_index,
param_name,
param_bound,
@@ -1756,6 +1758,7 @@
has_uninstantiated_bounds = true;
}
cloned_param = TypeParameter::New(mixin_app_class,
+ null_function,
cloned_index, // Unfinalized index.
param_name,
param_bound,
diff --git a/runtime/vm/clustered_snapshot.cc b/runtime/vm/clustered_snapshot.cc
index 8ddbd39..c2f3fc0 100644
--- a/runtime/vm/clustered_snapshot.cc
+++ b/runtime/vm/clustered_snapshot.cc
@@ -49,6 +49,7 @@
}
+#if !defined(DART_PRECOMPILED_RUNTIME)
class ClassSerializationCluster : public SerializationCluster {
public:
explicit ClassSerializationCluster(intptr_t num_cids) :
@@ -112,6 +113,7 @@
s->WriteRef(*p);
}
intptr_t class_id = cls->ptr()->id_;
+ ASSERT(class_id != kIllegalCid);
s->WriteCid(class_id);
s->Write<int32_t>(cls->ptr()->instance_size_in_words_);
s->Write<int32_t>(cls->ptr()->next_field_offset_in_words_);
@@ -127,6 +129,7 @@
GrowableArray<RawClass*> predefined_;
GrowableArray<RawClass*> objects_;
};
+#endif // !DART_PRECOMPILED_RUNTIME
class ClassDeserializationCluster : public DeserializationCluster {
@@ -247,6 +250,7 @@
};
+#if !defined(DART_PRECOMPILED_RUNTIME)
class UnresolvedClassSerializationCluster : public SerializationCluster {
public:
UnresolvedClassSerializationCluster() { }
@@ -290,6 +294,7 @@
private:
GrowableArray<RawUnresolvedClass*> objects_;
};
+#endif // !DART_PRECOMPILED_RUNTIME
class UnresolvedClassDeserializationCluster : public DeserializationCluster {
@@ -328,6 +333,7 @@
};
+#if !defined(DART_PRECOMPILED_RUNTIME)
class TypeArgumentsSerializationCluster : public SerializationCluster {
public:
TypeArgumentsSerializationCluster() { }
@@ -375,6 +381,7 @@
private:
GrowableArray<RawTypeArguments*> objects_;
};
+#endif // !DART_PRECOMPILED_RUNTIME
class TypeArgumentsDeserializationCluster : public DeserializationCluster {
@@ -418,6 +425,7 @@
};
+#if !defined(DART_PRECOMPILED_RUNTIME)
class PatchClassSerializationCluster : public SerializationCluster {
public:
PatchClassSerializationCluster() { }
@@ -459,6 +467,7 @@
private:
GrowableArray<RawPatchClass*> objects_;
};
+#endif // !DART_PRECOMPILED_RUNTIME
class PatchClassDeserializationCluster : public DeserializationCluster {
@@ -494,6 +503,7 @@
};
+#if !defined(DART_PRECOMPILED_RUNTIME)
class FunctionSerializationCluster : public SerializationCluster {
public:
FunctionSerializationCluster() { }
@@ -511,7 +521,7 @@
if (s->kind() == Snapshot::kAppNoJIT) {
s->Push(func->ptr()->code_);
} else if (s->kind() == Snapshot::kAppWithJIT) {
- s->Push(func->ptr()->unoptimized_code_);
+ NOT_IN_PRECOMPILED(s->Push(func->ptr()->unoptimized_code_));
s->Push(func->ptr()->ic_data_array_);
}
}
@@ -539,18 +549,23 @@
if (kind == Snapshot::kAppNoJIT) {
s->WriteRef(func->ptr()->code_);
} else if (s->kind() == Snapshot::kAppWithJIT) {
- s->WriteRef(func->ptr()->unoptimized_code_);
+ NOT_IN_PRECOMPILED(s->WriteRef(func->ptr()->unoptimized_code_));
s->WriteRef(func->ptr()->ic_data_array_);
}
- s->WriteTokenPosition(func->ptr()->token_pos_);
- s->WriteTokenPosition(func->ptr()->end_token_pos_);
+#if !defined(DART_PRECOMPILED_RUNTIME)
+ if (kind != Snapshot::kAppNoJIT) {
+ s->WriteTokenPosition(func->ptr()->token_pos_);
+ s->WriteTokenPosition(func->ptr()->end_token_pos_);
+ }
+#endif
s->Write<int16_t>(func->ptr()->num_fixed_parameters_);
s->Write<int16_t>(func->ptr()->num_optional_parameters_);
s->Write<uint32_t>(func->ptr()->kind_tag_);
if (kind == Snapshot::kAppNoJIT) {
// Omit fields used to support de/reoptimization.
} else {
+#if !defined(DART_PRECOMPILED_RUNTIME)
bool is_optimized = Code::IsOptimized(func->ptr()->code_);
if (is_optimized) {
s->Write<int32_t>(FLAG_optimization_counter_threshold);
@@ -560,6 +575,7 @@
s->Write<int8_t>(func->ptr()->deoptimization_counter_);
s->Write<uint16_t>(func->ptr()->optimized_instruction_count_);
s->Write<uint16_t>(func->ptr()->optimized_call_site_count_);
+#endif
}
}
}
@@ -567,6 +583,7 @@
private:
GrowableArray<RawFunction*> objects_;
};
+#endif // !DART_PRECOMPILED_RUNTIME
class FunctionDeserializationCluster : public DeserializationCluster {
@@ -605,8 +622,8 @@
if (kind == Snapshot::kAppNoJIT) {
func->ptr()->code_ = reinterpret_cast<RawCode*>(d->ReadRef());
} else if (kind == Snapshot::kAppWithJIT) {
- func->ptr()->unoptimized_code_ =
- reinterpret_cast<RawCode*>(d->ReadRef());
+ NOT_IN_PRECOMPILED(func->ptr()->unoptimized_code_ =
+ reinterpret_cast<RawCode*>(d->ReadRef()));
func->ptr()->ic_data_array_ = reinterpret_cast<RawArray*>(d->ReadRef());
}
@@ -614,18 +631,24 @@
func->ptr()->entry_point_ = 0;
#endif
- func->ptr()->token_pos_ = d->ReadTokenPosition();
- func->ptr()->end_token_pos_ = d->ReadTokenPosition();
+#if !defined(DART_PRECOMPILED_RUNTIME)
+ if (kind != Snapshot::kAppNoJIT) {
+ func->ptr()->token_pos_ = d->ReadTokenPosition();
+ func->ptr()->end_token_pos_ = d->ReadTokenPosition();
+ }
+#endif
func->ptr()->num_fixed_parameters_ = d->Read<int16_t>();
func->ptr()->num_optional_parameters_ = d->Read<int16_t>();
func->ptr()->kind_tag_ = d->Read<uint32_t>();
if (kind == Snapshot::kAppNoJIT) {
// Omit fields used to support de/reoptimization.
} else {
+#if !defined(DART_PRECOMPILED_RUNTIME)
func->ptr()->usage_counter_ = d->Read<int32_t>();
func->ptr()->deoptimization_counter_ = d->Read<int8_t>();
func->ptr()->optimized_instruction_count_ = d->Read<uint16_t>();
func->ptr()->optimized_call_site_count_ = d->Read<uint16_t>();
+#endif
}
}
}
@@ -670,6 +693,7 @@
};
+#if !defined(DART_PRECOMPILED_RUNTIME)
class ClosureDataSerializationCluster : public SerializationCluster {
public:
ClosureDataSerializationCluster() { }
@@ -679,11 +703,12 @@
RawClosureData* data = ClosureData::RawCast(object);
objects_.Add(data);
- RawObject** from = data->from();
- RawObject** to = data->to();
- for (RawObject** p = from; p <= to; p++) {
- s->Push(*p);
+ if (s->kind() != Snapshot::kAppNoJIT) {
+ s->Push(data->ptr()->context_scope_);
}
+ s->Push(data->ptr()->parent_function_);
+ s->Push(data->ptr()->signature_type_);
+ s->Push(data->ptr()->closure_);
}
void WriteAlloc(Serializer* s) {
@@ -700,17 +725,19 @@
intptr_t count = objects_.length();
for (intptr_t i = 0; i < count; i++) {
RawClosureData* data = objects_[i];
- RawObject** from = data->from();
- RawObject** to = data->to();
- for (RawObject** p = from; p <= to; p++) {
- s->WriteRef(*p);
+ if (s->kind() != Snapshot::kAppNoJIT) {
+ s->WriteRef(data->ptr()->context_scope_);
}
+ s->WriteRef(data->ptr()->parent_function_);
+ s->WriteRef(data->ptr()->signature_type_);
+ s->WriteRef(data->ptr()->closure_);
}
}
private:
GrowableArray<RawClosureData*> objects_;
};
+#endif // !DART_PRECOMPILED_RUNTIME
class ClosureDataDeserializationCluster : public DeserializationCluster {
@@ -735,17 +762,23 @@
for (intptr_t id = start_index_; id < stop_index_; id++) {
RawClosureData* data = reinterpret_cast<RawClosureData*>(d->Ref(id));
Deserializer::InitializeHeader(data, kClosureDataCid,
- ClosureData::InstanceSize(), is_vm_object);
- RawObject** from = data->from();
- RawObject** to = data->to();
- for (RawObject** p = from; p <= to; p++) {
- *p = d->ReadRef();
+ ClosureData::InstanceSize(),
+ is_vm_object);
+ if (d->kind() == Snapshot::kAppNoJIT) {
+ data->ptr()->context_scope_ = ContextScope::null();
+ } else {
+ data->ptr()->context_scope_ =
+ static_cast<RawContextScope*>(d->ReadRef());
}
+ data->ptr()->parent_function_ = static_cast<RawFunction*>(d->ReadRef());
+ data->ptr()->signature_type_ = static_cast<RawType*>(d->ReadRef());
+ data->ptr()->closure_ = static_cast<RawInstance*>(d->ReadRef());
}
}
};
+#if !defined(DART_PRECOMPILED_RUNTIME)
class RedirectionDataSerializationCluster : public SerializationCluster {
public:
RedirectionDataSerializationCluster() { }
@@ -787,6 +820,7 @@
private:
GrowableArray<RawRedirectionData*> objects_;
};
+#endif // !DART_PRECOMPILED_RUNTIME
class RedirectionDataDeserializationCluster : public DeserializationCluster {
@@ -824,6 +858,7 @@
};
+#if !defined(DART_PRECOMPILED_RUNTIME)
class FieldSerializationCluster : public SerializationCluster {
public:
FieldSerializationCluster() { }
@@ -924,6 +959,7 @@
private:
GrowableArray<RawField*> objects_;
};
+#endif // !DART_PRECOMPILED_RUNTIME
class FieldDeserializationCluster : public DeserializationCluster {
@@ -992,6 +1028,7 @@
};
+#if !defined(DART_PRECOMPILED_RUNTIME)
class LiteralTokenSerializationCluster : public SerializationCluster {
public:
LiteralTokenSerializationCluster() { }
@@ -1034,6 +1071,7 @@
private:
GrowableArray<RawLiteralToken*> objects_;
};
+#endif // !DART_PRECOMPILED_RUNTIME
class LiteralTokenDeserializationCluster : public DeserializationCluster {
@@ -1071,6 +1109,7 @@
};
+#if !defined(DART_PRECOMPILED_RUNTIME)
class TokenStreamSerializationCluster : public SerializationCluster {
public:
TokenStreamSerializationCluster() { }
@@ -1112,6 +1151,7 @@
private:
GrowableArray<RawTokenStream*> objects_;
};
+#endif // !DART_PRECOMPILED_RUNTIME
class TokenStreamDeserializationCluster : public DeserializationCluster {
@@ -1147,6 +1187,7 @@
};
+#if !defined(DART_PRECOMPILED_RUNTIME)
class ScriptSerializationCluster : public SerializationCluster {
public:
ScriptSerializationCluster() { }
@@ -1193,6 +1234,7 @@
private:
GrowableArray<RawScript*> objects_;
};
+#endif // !DART_PRECOMPILED_RUNTIME
class ScriptDeserializationCluster : public DeserializationCluster {
@@ -1237,6 +1279,7 @@
};
+#if !defined(DART_PRECOMPILED_RUNTIME)
class LibrarySerializationCluster : public SerializationCluster {
public:
LibrarySerializationCluster() { }
@@ -1285,6 +1328,8 @@
private:
GrowableArray<RawLibrary*> objects_;
};
+#endif // !DART_PRECOMPILED_RUNTIME
+
class LibraryDeserializationCluster : public DeserializationCluster {
public:
@@ -1347,6 +1392,7 @@
};
+#if !defined(DART_PRECOMPILED_RUNTIME)
class NamespaceSerializationCluster : public SerializationCluster {
public:
NamespaceSerializationCluster() { }
@@ -1388,6 +1434,7 @@
private:
GrowableArray<RawNamespace*> objects_;
};
+#endif // !DART_PRECOMPILED_RUNTIME
class NamespaceDeserializationCluster : public DeserializationCluster {
@@ -1422,6 +1469,7 @@
};
+#if !defined(DART_PRECOMPILED_RUNTIME)
class CodeSerializationCluster : public SerializationCluster {
public:
CodeSerializationCluster() { }
@@ -1461,7 +1509,8 @@
}
if (kind == Snapshot::kAppNoJIT) {
// No disabled code in precompilation.
- ASSERT(code->ptr()->instructions_ == code->ptr()->active_instructions_);
+ NOT_IN_PRECOMPILED(ASSERT(
+ code->ptr()->instructions_ == code->ptr()->active_instructions_));
} else {
ASSERT(kind == Snapshot::kAppWithJIT);
// We never include optimized code in JIT precompilation. Deoptimization
@@ -1491,6 +1540,7 @@
private:
GrowableArray<RawCode*> objects_;
};
+#endif // !DART_PRECOMPILED_RUNTIME
class CodeDeserializationCluster : public DeserializationCluster {
@@ -1523,7 +1573,7 @@
code->ptr()->entry_point_ = Instructions::UncheckedEntryPoint(instr);
code->ptr()->checked_entry_point_ =
Instructions::CheckedEntryPoint(instr);
- code->ptr()->active_instructions_ = instr;
+ NOT_IN_PRECOMPILED(code->ptr()->active_instructions_ = instr);
code->ptr()->instructions_ = instr;
code->ptr()->object_pool_ =
reinterpret_cast<RawObjectPool*>(d->ReadRef());
@@ -1535,6 +1585,7 @@
code->ptr()->stackmaps_ =
reinterpret_cast<RawArray*>(d->ReadRef());
+#if !defined(DART_PRECOMPILED_RUNTIME)
code->ptr()->deopt_info_array_ = Array::null();
code->ptr()->static_calls_target_table_ = Array::null();
code->ptr()->var_descriptors_ = LocalVarDescriptors::null();
@@ -1544,13 +1595,17 @@
code->ptr()->return_address_metadata_ = Object::null();
code->ptr()->compile_timestamp_ = 0;
+#endif
code->ptr()->state_bits_ = d->Read<int32_t>();
+#if !defined(DART_PRECOMPILED_RUNTIME)
code->ptr()->lazy_deopt_pc_offset_ = -1;
+#endif
}
}
};
+#if !defined(DART_PRECOMPILED_RUNTIME)
class ObjectPoolSerializationCluster : public SerializationCluster {
public:
ObjectPoolSerializationCluster() { }
@@ -1634,6 +1689,7 @@
private:
GrowableArray<RawObjectPool*> objects_;
};
+#endif // !DART_PRECOMPILED_RUNTIME
class ObjectPoolDeserializationCluster : public DeserializationCluster {
@@ -1701,6 +1757,7 @@
};
+#if !defined(DART_PRECOMPILED_RUNTIME)
// PcDescriptor, Stackmap, OneByteString, TwoByteString
class RODataSerializationCluster : public SerializationCluster {
public:
@@ -1751,6 +1808,7 @@
const intptr_t cid_;
GrowableArray<RawObject*> objects_;
};
+#endif // !DART_PRECOMPILED_RUNTIME
class RODataDeserializationCluster : public DeserializationCluster {
@@ -1772,20 +1830,7 @@
};
-class LocalVarDescriptorsSerializationCluster : public SerializationCluster {
- public:
- LocalVarDescriptorsSerializationCluster() { }
- virtual ~LocalVarDescriptorsSerializationCluster() { }
-
- void Trace(Serializer* s, RawObject* object) { UNIMPLEMENTED(); }
- void WriteAlloc(Serializer* s) {}
- void WriteFill(Serializer* s) {}
-
- private:
- GrowableArray<RawClass*> objects_;
-};
-
-
+#if !defined(DART_PRECOMPILED_RUNTIME)
class ExceptionHandlersSerializationCluster : public SerializationCluster {
public:
ExceptionHandlersSerializationCluster() { }
@@ -1828,6 +1873,7 @@
private:
GrowableArray<RawExceptionHandlers*> objects_;
};
+#endif // !DART_PRECOMPILED_RUNTIME
class ExceptionHandlersDeserializationCluster : public DeserializationCluster {
@@ -1869,6 +1915,7 @@
}
};
+#if !defined(DART_PRECOMPILED_RUNTIME)
class ContextSerializationCluster : public SerializationCluster {
public:
ContextSerializationCluster() { }
@@ -1913,6 +1960,7 @@
private:
GrowableArray<RawContext*> objects_;
};
+#endif // !DART_PRECOMPILED_RUNTIME
class ContextDeserializationCluster : public DeserializationCluster {
@@ -1951,6 +1999,7 @@
};
+#if !defined(DART_PRECOMPILED_RUNTIME)
class ContextScopeSerializationCluster : public SerializationCluster {
public:
ContextScopeSerializationCluster() { }
@@ -1998,6 +2047,7 @@
private:
GrowableArray<RawContextScope*> objects_;
};
+#endif // !DART_PRECOMPILED_RUNTIME
class ContextScopeDeserializationCluster : public DeserializationCluster {
@@ -2038,6 +2088,7 @@
};
+#if !defined(DART_PRECOMPILED_RUNTIME)
class ICDataSerializationCluster : public SerializationCluster {
public:
ICDataSerializationCluster() { }
@@ -2074,7 +2125,9 @@
for (RawObject** p = from; p <= to; p++) {
s->WriteRef(*p);
}
- s->Write<int32_t>(ic->ptr()->deopt_id_);
+ if (kind != Snapshot::kAppNoJIT) {
+ NOT_IN_PRECOMPILED(s->Write<int32_t>(ic->ptr()->deopt_id_));
+ }
s->Write<uint32_t>(ic->ptr()->state_bits_);
#if defined(TAG_IC_DATA)
s->Write<int32_t>(ic->ptr()->tag_);
@@ -2085,6 +2138,7 @@
private:
GrowableArray<RawICData*> objects_;
};
+#endif // !DART_PRECOMPILED_RUNTIME
class ICDataDeserializationCluster : public DeserializationCluster {
@@ -2119,7 +2173,7 @@
for (RawObject** p = to_snapshot + 1; p <= to; p++) {
*p = Object::null();
}
- ic->ptr()->deopt_id_ = d->Read<int32_t>();
+ NOT_IN_PRECOMPILED(ic->ptr()->deopt_id_ = d->Read<int32_t>());
ic->ptr()->state_bits_ = d->Read<int32_t>();
#if defined(TAG_IC_DATA)
ic->ptr()->tag_ = d->Read<int32_t>();
@@ -2129,6 +2183,7 @@
};
+#if !defined(DART_PRECOMPILED_RUNTIME)
class MegamorphicCacheSerializationCluster : public SerializationCluster {
public:
MegamorphicCacheSerializationCluster() { }
@@ -2171,6 +2226,7 @@
private:
GrowableArray<RawMegamorphicCache*> objects_;
};
+#endif // !DART_PRECOMPILED_RUNTIME
class MegamorphicCacheDeserializationCluster : public DeserializationCluster {
@@ -2209,6 +2265,7 @@
};
+#if !defined(DART_PRECOMPILED_RUNTIME)
class SubtypeTestCacheSerializationCluster : public SerializationCluster {
public:
SubtypeTestCacheSerializationCluster() { }
@@ -2241,6 +2298,7 @@
private:
GrowableArray<RawSubtypeTestCache*> objects_;
};
+#endif // !DART_PRECOMPILED_RUNTIME
class SubtypeTestCacheDeserializationCluster : public DeserializationCluster {
@@ -2274,6 +2332,7 @@
};
+#if !defined(DART_PRECOMPILED_RUNTIME)
class LanguageErrorSerializationCluster : public SerializationCluster {
public:
LanguageErrorSerializationCluster() { }
@@ -2318,6 +2377,7 @@
private:
GrowableArray<RawLanguageError*> objects_;
};
+#endif // !DART_PRECOMPILED_RUNTIME
class LanguageErrorDeserializationCluster : public DeserializationCluster {
@@ -2357,6 +2417,7 @@
};
+#if !defined(DART_PRECOMPILED_RUNTIME)
class UnhandledExceptionSerializationCluster : public SerializationCluster {
public:
UnhandledExceptionSerializationCluster() { }
@@ -2398,6 +2459,7 @@
private:
GrowableArray<RawUnhandledException*> objects_;
};
+#endif // !DART_PRECOMPILED_RUNTIME
class UnhandledExceptionDeserializationCluster : public DeserializationCluster {
@@ -2435,6 +2497,7 @@
};
+#if !defined(DART_PRECOMPILED_RUNTIME)
class InstanceSerializationCluster : public SerializationCluster {
public:
explicit InstanceSerializationCluster(intptr_t cid) : cid_(cid) {
@@ -2496,6 +2559,7 @@
intptr_t instance_size_in_words_;
GrowableArray<RawInstance*> objects_;
};
+#endif // !DART_PRECOMPILED_RUNTIME
class InstanceDeserializationCluster : public DeserializationCluster {
@@ -2553,6 +2617,7 @@
};
+#if !defined(DART_PRECOMPILED_RUNTIME)
class LibraryPrefixSerializationCluster : public SerializationCluster {
public:
LibraryPrefixSerializationCluster() { }
@@ -2597,6 +2662,7 @@
private:
GrowableArray<RawLibraryPrefix*> objects_;
};
+#endif // !DART_PRECOMPILED_RUNTIME
class LibraryPrefixDeserializationCluster : public DeserializationCluster {
@@ -2637,6 +2703,7 @@
};
+#if !defined(DART_PRECOMPILED_RUNTIME)
class TypeSerializationCluster : public SerializationCluster {
public:
TypeSerializationCluster() { }
@@ -2707,6 +2774,7 @@
GrowableArray<RawType*> canonical_objects_;
GrowableArray<RawType*> objects_;
};
+#endif // !DART_PRECOMPILED_RUNTIME
class TypeDeserializationCluster : public DeserializationCluster {
@@ -2769,6 +2837,7 @@
};
+#if !defined(DART_PRECOMPILED_RUNTIME)
class TypeRefSerializationCluster : public SerializationCluster {
public:
TypeRefSerializationCluster() { }
@@ -2810,6 +2879,7 @@
private:
GrowableArray<RawTypeRef*> objects_;
};
+#endif // !DART_PRECOMPILED_RUNTIME
class TypeRefDeserializationCluster : public DeserializationCluster {
@@ -2844,6 +2914,7 @@
};
+#if !defined(DART_PRECOMPILED_RUNTIME)
class TypeParameterSerializationCluster : public SerializationCluster {
public:
TypeParameterSerializationCluster() { }
@@ -2890,6 +2961,7 @@
private:
GrowableArray<RawTypeParameter*> objects_;
};
+#endif // !DART_PRECOMPILED_RUNTIME
class TypeParameterDeserializationCluster : public DeserializationCluster {
@@ -2930,6 +3002,7 @@
};
+#if !defined(DART_PRECOMPILED_RUNTIME)
class BoundedTypeSerializationCluster : public SerializationCluster {
public:
BoundedTypeSerializationCluster() { }
@@ -2971,6 +3044,7 @@
private:
GrowableArray<RawBoundedType*> objects_;
};
+#endif // !DART_PRECOMPILED_RUNTIME
class BoundedTypeDeserializationCluster : public DeserializationCluster {
@@ -3006,6 +3080,7 @@
};
+#if !defined(DART_PRECOMPILED_RUNTIME)
class ClosureSerializationCluster : public SerializationCluster {
public:
ClosureSerializationCluster() { }
@@ -3048,6 +3123,7 @@
private:
GrowableArray<RawClosure*> objects_;
};
+#endif // !DART_PRECOMPILED_RUNTIME
class ClosureDeserializationCluster : public DeserializationCluster {
@@ -3084,6 +3160,7 @@
};
+#if !defined(DART_PRECOMPILED_RUNTIME)
class MintSerializationCluster : public SerializationCluster {
public:
MintSerializationCluster() { }
@@ -3123,6 +3200,7 @@
GrowableArray<RawSmi*> smis_;
GrowableArray<RawMint*> mints_;
};
+#endif // !DART_PRECOMPILED_RUNTIME
class MintDeserializationCluster : public DeserializationCluster {
@@ -3178,6 +3256,7 @@
};
+#if !defined(DART_PRECOMPILED_RUNTIME)
class BigintSerializationCluster : public SerializationCluster {
public:
BigintSerializationCluster() { }
@@ -3220,6 +3299,7 @@
private:
GrowableArray<RawBigint*> objects_;
};
+#endif // !DART_PRECOMPILED_RUNTIME
class BigintDeserializationCluster : public DeserializationCluster {
@@ -3256,6 +3336,7 @@
};
+#if !defined(DART_PRECOMPILED_RUNTIME)
class DoubleSerializationCluster : public SerializationCluster {
public:
DoubleSerializationCluster() { }
@@ -3288,6 +3369,7 @@
private:
GrowableArray<RawDouble*> objects_;
};
+#endif // !DART_PRECOMPILED_RUNTIME
class DoubleDeserializationCluster : public DeserializationCluster {
@@ -3320,6 +3402,7 @@
};
+#if !defined(DART_PRECOMPILED_RUNTIME)
class GrowableObjectArraySerializationCluster : public SerializationCluster {
public:
GrowableObjectArraySerializationCluster() { }
@@ -3362,6 +3445,7 @@
private:
GrowableArray<RawGrowableObjectArray*> objects_;
};
+#endif // !DART_PRECOMPILED_RUNTIME
class GrowableObjectArrayDeserializationCluster
@@ -3401,6 +3485,7 @@
};
+#if !defined(DART_PRECOMPILED_RUNTIME)
class TypedDataSerializationCluster : public SerializationCluster {
public:
explicit TypedDataSerializationCluster(intptr_t cid) : cid_(cid) { }
@@ -3440,6 +3525,7 @@
const intptr_t cid_;
GrowableArray<RawTypedData*> objects_;
};
+#endif // !DART_PRECOMPILED_RUNTIME
class TypedDataDeserializationCluster : public DeserializationCluster {
@@ -3483,6 +3569,7 @@
};
+#if !defined(DART_PRECOMPILED_RUNTIME)
class ExternalTypedDataSerializationCluster : public SerializationCluster {
public:
explicit ExternalTypedDataSerializationCluster(intptr_t cid) : cid_(cid) { }
@@ -3520,6 +3607,7 @@
const intptr_t cid_;
GrowableArray<RawExternalTypedData*> objects_;
};
+#endif // !DART_PRECOMPILED_RUNTIME
class ExternalTypedDataDeserializationCluster : public DeserializationCluster {
@@ -3561,6 +3649,7 @@
};
+#if !defined(DART_PRECOMPILED_RUNTIME)
class StacktraceSerializationCluster : public SerializationCluster {
public:
StacktraceSerializationCluster() { }
@@ -3602,6 +3691,7 @@
private:
GrowableArray<RawStacktrace*> objects_;
};
+#endif // !DART_PRECOMPILED_RUNTIME
class StacktraceDeserializationCluster : public DeserializationCluster {
@@ -3637,6 +3727,7 @@
};
+#if !defined(DART_PRECOMPILED_RUNTIME)
class RegExpSerializationCluster : public SerializationCluster {
public:
RegExpSerializationCluster() { }
@@ -3681,6 +3772,7 @@
private:
GrowableArray<RawRegExp*> objects_;
};
+#endif // !DART_PRECOMPILED_RUNTIME
class RegExpDeserializationCluster : public DeserializationCluster {
@@ -3719,6 +3811,7 @@
};
+#if !defined(DART_PRECOMPILED_RUNTIME)
class LinkedHashMapSerializationCluster : public SerializationCluster {
public:
LinkedHashMapSerializationCluster() { }
@@ -3784,6 +3877,7 @@
private:
GrowableArray<RawLinkedHashMap*> objects_;
};
+#endif // !DART_PRECOMPILED_RUNTIME
class LinkedHashMapDeserializationCluster : public DeserializationCluster {
@@ -3845,6 +3939,7 @@
};
+#if !defined(DART_PRECOMPILED_RUNTIME)
class ArraySerializationCluster : public SerializationCluster {
public:
explicit ArraySerializationCluster(intptr_t cid) : cid_(cid) { }
@@ -3891,6 +3986,7 @@
intptr_t cid_;
GrowableArray<RawArray*> objects_;
};
+#endif // !DART_PRECOMPILED_RUNTIME
class ArrayDeserializationCluster : public DeserializationCluster {
@@ -3934,6 +4030,7 @@
};
+#if !defined(DART_PRECOMPILED_RUNTIME)
class OneByteStringSerializationCluster : public SerializationCluster {
public:
OneByteStringSerializationCluster() { }
@@ -3972,6 +4069,7 @@
private:
GrowableArray<RawOneByteString*> objects_;
};
+#endif // !DART_PRECOMPILED_RUNTIME
class OneByteStringDeserializationCluster : public DeserializationCluster {
@@ -4011,6 +4109,7 @@
};
+#if !defined(DART_PRECOMPILED_RUNTIME)
class TwoByteStringSerializationCluster : public SerializationCluster {
public:
TwoByteStringSerializationCluster() { }
@@ -4049,6 +4148,7 @@
private:
GrowableArray<RawTwoByteString*> objects_;
};
+#endif // !DART_PRECOMPILED_RUNTIME
class TwoByteStringDeserializationCluster : public DeserializationCluster {
@@ -4120,6 +4220,10 @@
SerializationCluster* Serializer::NewClusterForClass(intptr_t cid) {
+#if defined(DART_PRECOMPILED_RUNTIME)
+ UNREACHABLE();
+ return NULL;
+#else
Zone* Z = zone_;
if ((cid > kNumPredefinedCids) ||
(cid == kInstanceCid) ||
@@ -4206,6 +4310,7 @@
FATAL1("No cluster defined for cid %" Pd, cid);
return NULL;
+#endif // !DART_PRECOMPILED_RUNTIME
}
diff --git a/runtime/vm/compiler.cc b/runtime/vm/compiler.cc
index aa92737..93898ad 100644
--- a/runtime/vm/compiler.cc
+++ b/runtime/vm/compiler.cc
@@ -165,6 +165,10 @@
const Error& error =
Error::Handle(Compiler::CompileFunction(thread, function));
if (!error.IsNull()) {
+ if (error.IsLanguageError()) {
+ Exceptions::ThrowCompileTimeError(LanguageError::Cast(error));
+ UNREACHABLE();
+ }
Exceptions::PropagateError(error);
}
}
@@ -1284,8 +1288,9 @@
// We got an error during compilation.
error = thread->sticky_error();
thread->clear_sticky_error();
- if (error.IsLanguageError() &&
- LanguageError::Cast(error).kind() == Report::kBailout) {
+ if ((error.IsLanguageError() &&
+ LanguageError::Cast(error).kind() == Report::kBailout) ||
+ error.IsUnhandledException()) {
if (FLAG_trace_compiler) {
THR_Print("--> disabling optimizations for '%s'\n",
function.ToFullyQualifiedCString());
@@ -1360,9 +1365,6 @@
}
return Error::null();
}
- // Unoptimized compilation or precompilation may encounter compile-time
- // errors, but regular optimized compilation should not.
- ASSERT(!optimized);
// Do not attempt to optimize functions that can cause errors.
function.set_is_optimizable(false);
return error.raw();
@@ -1862,15 +1864,9 @@
while (running_ && !function.IsNull() && !isolate_->IsTopLevelParsing()) {
// Check that we have aggregated and cleared the stats.
ASSERT(thread->compiler_stats()->IsCleared());
- const Error& error = Error::Handle(zone,
- Compiler::CompileOptimizedFunction(thread,
- function,
- Compiler::kNoOSRDeoptId));
- // TODO(srdjan): We do not expect errors while compiling optimized
- // code, any errors should have been caught when compiling
- // unoptimized code. Any issues while optimizing are flagged by
- // making the result invalid.
- ASSERT(error.IsNull());
+ Compiler::CompileOptimizedFunction(thread,
+ function,
+ Compiler::kNoOSRDeoptId);
#ifndef PRODUCT
Isolate* isolate = thread->isolate();
isolate->aggregate_compiler_stats()->Add(*thread->compiler_stats());
diff --git a/runtime/vm/constants_dbc.h b/runtime/vm/constants_dbc.h
index c5dbe04..44398aa 100644
--- a/runtime/vm/constants_dbc.h
+++ b/runtime/vm/constants_dbc.h
@@ -220,6 +220,16 @@
//
// FP[rA] <- op(FP[rD]). Assumes FP[rD] is an unboxed double.
//
+// - DTruncate, DFloor, DCeil rA, rD
+//
+// Applies trunc(), floor(), or ceil() to the unboxed double in FP[rD], and
+// stores the result in FP[rA].
+//
+// - DoubleToFloat, FloatToDouble rA, rD
+//
+// Convert the unboxed float or double in FP[rD] as indicated, and store the
+// result in FP[rA].
+//
// - BitOr, BitAnd, BitXor rA, rB, rC
//
// FP[rA] <- FP[rB] op FP[rC]. These instructions expect their operands to be
@@ -331,6 +341,13 @@
//
// Allocate object of class SP[0] with type arguments SP[-1].
//
+// - AllocateTOpt rA, D
+//
+// Similar to AllocateOpt with the difference that the offset of the
+// type arguments in the resulting object is taken from the D field of the
+// following Nop instruction, and on success 4 instructions are skipped and
+// the object at the top of the stack is popped.
+//
// - StoreIndexedTOS
//
// Store SP[0] into array SP[-2] at index SP[-1]. No typechecking is done.
@@ -341,9 +358,11 @@
// Store FP[rC] into array FP[rA] at index FP[rB]. No typechecking is done.
// FP[rA] is assumed to be a RawArray, FP[rB] to be a smi.
//
-// - StoreIndexed{N}{Float64, Uint8, OneByteString} rA, rB, rC
+// - StoreIndexed{N}{Type} rA, rB, rC
//
-// Where N is '' or '8'. N may only be '8' for Float64.
+// Where Type is Float32, Float64, Uint8, or OneByteString
+// Where N is '', '4', or '8'. N may only be '4' for Float32 and '8' for
+// Float64.
//
// Store the unboxed double or tagged Smi in FP[rC] into the typed data array
// at FP[rA] at index FP[rB]. If N is not '', the index is assumed to be
@@ -360,8 +379,9 @@
//
// - LoadIndexed{N}{Type} rA, rB, rC
//
-// Where Type is Float64, OneByteString, TwoByteString, Uint8, or Int8,
-// and N is '' or '8'. N may only be '8' for Float64.
+// Where Type is Float32, Float64, OneByteString, TwoByteString, Uint8,
+// Int8, and N is '', '4', or '8'. N may only be '4' for Float32, and may
+// only be '8' for Float64.
//
// Loads from typed data array FP[rB] at index FP[rC] into an unboxed double,
// or tagged Smi in FP[rA] as indicated by the type in the name. If N is not
@@ -464,6 +484,12 @@
//
// Allocate Context object assuming for D context variables.
//
+// - AllocateUninitializedContext rA, D
+//
+// Allocates an uninitialized context for D variables, and places the result
+// in FP[rA]. On success, skips the next 2 instructions, which should be the
+// slow path (AllocateContext D; PopLocal rA).
+//
// - CloneContext
//
// Clone context stored in TOS.
@@ -670,6 +696,11 @@
V(DSin, A_D, reg, reg, ___) \
V(DPow, A_B_C, reg, reg, reg) \
V(DMod, A_B_C, reg, reg, reg) \
+ V(DTruncate, A_D, reg, reg, ___) \
+ V(DFloor, A_D, reg, reg, ___) \
+ V(DCeil, A_D, reg, reg, ___) \
+ V(DoubleToFloat, A_D, reg, reg, ___) \
+ V(FloatToDouble, A_D, reg, reg, ___) \
V(StoreStaticTOS, D, lit, ___, ___) \
V(PushStatic, D, lit, ___, ___) \
V(InitStaticTOS, 0, ___, ___, ___) \
@@ -702,12 +733,15 @@
V(Allocate, D, lit, ___, ___) \
V(AllocateT, 0, ___, ___, ___) \
V(AllocateOpt, A_D, reg, lit, ___) \
+ V(AllocateTOpt, A_D, reg, lit, ___) \
V(StoreIndexedTOS, 0, ___, ___, ___) \
V(StoreIndexed, A_B_C, reg, reg, reg) \
V(StoreIndexedUint8, A_B_C, reg, reg, reg) \
V(StoreIndexedExternalUint8, A_B_C, reg, reg, reg) \
V(StoreIndexedOneByteString, A_B_C, reg, reg, reg) \
V(StoreIndexedUint32, A_B_C, reg, reg, reg) \
+ V(StoreIndexedFloat32, A_B_C, reg, reg, reg) \
+ V(StoreIndexed4Float32, A_B_C, reg, reg, reg) \
V(StoreIndexedFloat64, A_B_C, reg, reg, reg) \
V(StoreIndexed8Float64, A_B_C, reg, reg, reg) \
V(LoadIndexed, A_B_C, reg, reg, reg) \
@@ -717,6 +751,8 @@
V(LoadIndexedUint32, A_B_C, reg, reg, reg) \
V(LoadIndexedExternalUint8, A_B_C, reg, reg, reg) \
V(LoadIndexedExternalInt8, A_B_C, reg, reg, reg) \
+ V(LoadIndexedFloat32, A_B_C, reg, reg, reg) \
+ V(LoadIndexed4Float32, A_B_C, reg, reg, reg) \
V(LoadIndexedFloat64, A_B_C, reg, reg, reg) \
V(LoadIndexed8Float64, A_B_C, reg, reg, reg) \
V(LoadIndexedOneByteString, A_B_C, reg, reg, reg) \
@@ -735,6 +771,7 @@
V(Frame, D, num, ___, ___) \
V(SetFrame, A, num, ___, num) \
V(AllocateContext, D, num, ___, ___) \
+ V(AllocateUninitializedContext, A_D, reg, num, ___) \
V(CloneContext, 0, ___, ___, ___) \
V(MoveSpecial, A_D, reg, num, ___) \
V(InstantiateType, D, lit, ___, ___) \
diff --git a/runtime/vm/dart_api_impl.cc b/runtime/vm/dart_api_impl.cc
index ccda7f0..d5d7998 100644
--- a/runtime/vm/dart_api_impl.cc
+++ b/runtime/vm/dart_api_impl.cc
@@ -184,6 +184,21 @@
}
+static bool IsCompiletimeErrorObject(Zone* zone, const Object& obj) {
+#if defined(DART_PRECOMPILED_RUNTIME)
+ // All compile-time errors were handled at snapshot generation time and
+ // compiletime_error_class was removed.
+ return false;
+#else
+ Isolate* I = Thread::Current()->isolate();
+ const Class& error_class =
+ Class::Handle(zone, I->object_store()->compiletime_error_class());
+ ASSERT(!error_class.IsNull());
+ return (obj.GetClassId() == error_class.id());
+#endif
+}
+
+
static bool GetNativeStringArgument(NativeArguments* arguments,
int arg_index,
Dart_Handle* str,
@@ -761,6 +776,13 @@
DART_EXPORT bool Dart_IsCompilationError(Dart_Handle object) {
+ if (::Dart_IsUnhandledExceptionError(object)) {
+ DARTSCOPE(Thread::Current());
+ const UnhandledException& error =
+ UnhandledException::Cast(Object::Handle(Z, Api::UnwrapHandle(object)));
+ const Instance& exc = Instance::Handle(Z, error.exception());
+ return IsCompiletimeErrorObject(Z, exc);
+ }
return Api::ClassId(object) == kLanguageErrorCid;
}
@@ -1451,11 +1473,11 @@
Isolate* isolate = thread->isolate();
CHECK_ISOLATE(isolate);
NoSafepointScope no_safepoint_scope;
- if (isolate->sticky_error() != Error::null()) {
+ if ((isolate->sticky_error() != Error::null()) && !::Dart_IsNull(error)) {
FATAL1("%s expects there to be no sticky error.", CURRENT_FUNC);
}
- if (!::Dart_IsUnhandledExceptionError(error)) {
- FATAL1("%s expects the error to be an unhandled exception error.",
+ if (!::Dart_IsUnhandledExceptionError(error) && !::Dart_IsNull(error)) {
+ FATAL1("%s expects the error to be an unhandled exception error or null.",
CURRENT_FUNC);
}
isolate->SetStickyError(
@@ -1471,6 +1493,19 @@
}
+DART_EXPORT Dart_Handle Dart_GetStickyError() {
+ Isolate* I = Isolate::Current();
+ CHECK_ISOLATE(I);
+ NoSafepointScope no_safepoint_scope;
+ if (I->sticky_error() != Object::null()) {
+ Dart_Handle error =
+ Api::NewHandle(Thread::Current(), I->sticky_error());
+ return error;
+ }
+ return Dart_Null();
+}
+
+
DART_EXPORT void Dart_ExitIsolate() {
Thread* T = Thread::Current();
CHECK_ISOLATE(T->isolate());
diff --git a/runtime/vm/dart_api_impl_test.cc b/runtime/vm/dart_api_impl_test.cc
index 5560535..d2016a4 100644
--- a/runtime/vm/dart_api_impl_test.cc
+++ b/runtime/vm/dart_api_impl_test.cc
@@ -570,7 +570,6 @@
result = Dart_Invoke(lib, NewString("Func1"), 0, NULL);
EXPECT(Dart_IsError(result));
- EXPECT(!Dart_ErrorHasException(result));
EXPECT_SUBSTRING("semicolon expected", Dart_GetError(result));
result = Dart_Invoke(lib, NewString("Func2"), 0, NULL);
@@ -584,7 +583,6 @@
result = Dart_Invoke(lib, NewString("Func1"), 0, NULL);
EXPECT(Dart_IsError(result));
- EXPECT(!Dart_ErrorHasException(result));
EXPECT_SUBSTRING("semicolon expected", Dart_GetError(result));
result = Dart_Invoke(lib, NewString("Func2"), 0, NULL);
@@ -598,7 +596,6 @@
result = Dart_Invoke(lib, NewString("Func1"), 0, NULL);
EXPECT(Dart_IsError(result));
- EXPECT(!Dart_ErrorHasException(result));
EXPECT_SUBSTRING("semicolon expected", Dart_GetError(result));
result = Dart_Invoke(lib, NewString("Func2"), 0, NULL);
@@ -3640,8 +3637,13 @@
EXPECT(Dart_IsError(retobj));
EXPECT(Dart_IsUnhandledExceptionError(retobj));
EXPECT(!Dart_HasStickyError());
+ EXPECT(Dart_GetStickyError() == Dart_Null());
Dart_SetStickyError(retobj);
EXPECT(Dart_HasStickyError());
+ EXPECT(Dart_GetStickyError() != Dart_Null());
+ Dart_SetStickyError(Dart_Null());
+ EXPECT(!Dart_HasStickyError());
+ EXPECT(Dart_GetStickyError() == Dart_Null());
}
diff --git a/runtime/vm/dart_api_state.cc b/runtime/vm/dart_api_state.cc
index ed6ac3e..6d0967d 100644
--- a/runtime/vm/dart_api_state.cc
+++ b/runtime/vm/dart_api_state.cc
@@ -22,7 +22,6 @@
PageSpace* old_space = isolate->heap()->old_space();
MonitorLocker ml(old_space->tasks_lock());
old_space->set_tasks(old_space->tasks() + 1);
- ml.Notify();
}
@@ -49,7 +48,7 @@
PageSpace* old_space = isolate_->heap()->old_space();
MonitorLocker ml(old_space->tasks_lock());
old_space->set_tasks(old_space->tasks() - 1);
- ml.Notify();
+ ml.NotifyAll();
}
}
diff --git a/runtime/vm/exceptions.cc b/runtime/vm/exceptions.cc
index 37a99f2..edfad99 100644
--- a/runtime/vm/exceptions.cc
+++ b/runtime/vm/exceptions.cc
@@ -11,6 +11,7 @@
#include "vm/debugger.h"
#include "vm/flags.h"
#include "vm/log.h"
+#include "vm/longjump.h"
#include "vm/object.h"
#include "vm/object_store.h"
#include "vm/stack_frame.h"
@@ -146,7 +147,7 @@
bool* needs_stacktrace) {
StackFrameIterator frames(StackFrameIterator::kDontValidateFrames);
StackFrame* frame = frames.NextFrame();
- ASSERT(frame != NULL); // We expect to find a dart invocation frame.
+ if (frame == NULL) return false; // No Dart frame.
bool handler_pc_set = false;
*needs_stacktrace = false;
bool is_catch_all = false;
@@ -327,6 +328,16 @@
&handler_sp,
&handler_fp,
&handler_needs_stacktrace);
+ if (handler_pc == 0) {
+ // No Dart frame.
+ ASSERT(!thread->IsMutatorThread());
+ ASSERT(incoming_exception.raw() ==
+ isolate->object_store()->out_of_memory());
+ const UnhandledException& error = UnhandledException::Handle(
+ zone, isolate->object_store()->preallocated_unhandled_exception());
+ thread->long_jump_base()->Jump(1, error);
+ UNREACHABLE();
+ }
if (handler_needs_stacktrace) {
BuildStackTrace(&frame_builder);
}
@@ -640,6 +651,13 @@
}
+void Exceptions::ThrowCompileTimeError(const LanguageError& error) {
+ const Array& args = Array::Handle(Array::New(1));
+ args.SetAt(0, String::Handle(error.FormatMessage()));
+ Exceptions::ThrowByType(Exceptions::kCompileTimeError, args);
+}
+
+
RawObject* Exceptions::Create(ExceptionType type, const Array& arguments) {
Library& library = Library::Handle();
const String* class_name = NULL;
@@ -713,6 +731,11 @@
case kCyclicInitializationError:
library = Library::CoreLibrary();
class_name = &Symbols::CyclicInitializationError();
+ break;
+ case kCompileTimeError:
+ library = Library::CoreLibrary();
+ class_name = &Symbols::_CompileTimeError();
+ break;
}
return DartLibraryCalls::InstanceCreate(library,
diff --git a/runtime/vm/exceptions.h b/runtime/vm/exceptions.h
index e0a64c8..e85f100 100644
--- a/runtime/vm/exceptions.h
+++ b/runtime/vm/exceptions.h
@@ -15,6 +15,7 @@
class Array;
class DartFrameIterator;
class Error;
+class LanguageError;
class Instance;
class Integer;
class RawInstance;
@@ -60,6 +61,7 @@
kFallThrough,
kAbstractClassInstantiation,
kCyclicInitializationError,
+ kCompileTimeError,
};
static void ThrowByType(ExceptionType type, const Array& arguments);
@@ -72,6 +74,7 @@
const Integer& argument_value,
intptr_t expected_from,
intptr_t expected_to);
+ static void ThrowCompileTimeError(const LanguageError& error);
// Returns a RawInstance if the exception is successfully created,
// otherwise returns a RawError.
diff --git a/runtime/vm/flag_list.h b/runtime/vm/flag_list.h
index d23492c..3a54ca8 100644
--- a/runtime/vm/flag_list.h
+++ b/runtime/vm/flag_list.h
@@ -136,8 +136,6 @@
"Precompilation compiler mode") \
C(precompiled_runtime, true, false, bool, false, \
"Precompiled runtime mode") \
-R(print_ssa_liveness, false, bool, false, \
- "Print liveness for ssa variables.") \
R(print_ssa_liveranges, false, bool, false, \
"Print live ranges after allocation.") \
C(print_stop_message, false, false, bool, false, \
diff --git a/runtime/vm/flow_graph_inliner.cc b/runtime/vm/flow_graph_inliner.cc
index 113c3e9..b42bba5 100644
--- a/runtime/vm/flow_graph_inliner.cc
+++ b/runtime/vm/flow_graph_inliner.cc
@@ -961,9 +961,9 @@
} else {
error = thread()->sticky_error();
thread()->clear_sticky_error();
- ASSERT(error.IsLanguageError());
- if (LanguageError::Cast(error).kind() == Report::kBailout) {
+ if (error.IsLanguageError() &&
+ (LanguageError::Cast(error).kind() == Report::kBailout)) {
if (error.raw() == Object::background_compilation_error().raw()) {
// Fall through to exit the compilation, and retry it later.
} else {
@@ -976,18 +976,20 @@
}
} else {
// Fall through to exit long jump scope.
- ASSERT(FLAG_precompiled_mode);
}
}
}
// Propagate a compile-time error. In precompilation we attempt to
// inline functions that have never been compiled before; when JITing we
- // should only see compile-time errors in unoptimized compilation.
+ // should only see language errors in unoptimized compilation.
+ // Otherwise, there can be an out-of-memory error (unhandled exception).
// In background compilation we may abort compilation as the state
// changes while compiling. Propagate that 'error' and retry compilation
// later.
- ASSERT(FLAG_precompiled_mode || Compiler::IsBackgroundCompilation());
+ ASSERT(FLAG_precompiled_mode ||
+ Compiler::IsBackgroundCompilation() ||
+ error.IsUnhandledException());
Thread::Current()->long_jump_base()->Jump(1, error);
UNREACHABLE();
return false;
diff --git a/runtime/vm/gc_marker.cc b/runtime/vm/gc_marker.cc
index 7ea64d6..ed6d4da 100644
--- a/runtime/vm/gc_marker.cc
+++ b/runtime/vm/gc_marker.cc
@@ -30,6 +30,9 @@
}
void DetachCode() {
+#if defined(DART_PRECOMPILED_RUNTIME)
+ UNREACHABLE();
+#else
intptr_t unoptimized_code_count = 0;
intptr_t current_code_count = 0;
for (int i = 0; i < skipped_code_functions_.length(); i++) {
@@ -76,6 +79,7 @@
}
// Clean up.
skipped_code_functions_.Clear();
+#endif // !DART_PRECOMPILED_RUNTIME
}
private:
diff --git a/runtime/vm/gc_sweeper.cc b/runtime/vm/gc_sweeper.cc
index e37f1db..40ee3db 100644
--- a/runtime/vm/gc_sweeper.cc
+++ b/runtime/vm/gc_sweeper.cc
@@ -111,7 +111,6 @@
ASSERT(freelist_ != NULL);
MonitorLocker ml(old_space_->tasks_lock());
old_space_->set_tasks(old_space_->tasks() + 1);
- ml.Notify();
}
virtual void Run() {
diff --git a/runtime/vm/heap.cc b/runtime/vm/heap.cc
index b9a74c7..fd22740 100644
--- a/runtime/vm/heap.cc
+++ b/runtime/vm/heap.cc
@@ -518,45 +518,33 @@
}
-void Heap::GetMergedAddressRange(uword* start, uword* end) const {
- if (new_space_.CapacityInWords() != 0) {
- uword new_start;
- uword new_end;
- new_space_.StartEndAddress(&new_start, &new_end);
- *start = Utils::Minimum(new_start, *start);
- *end = Utils::Maximum(new_end, *end);
- }
- if (old_space_.CapacityInWords() != 0) {
- uword old_start;
- uword old_end;
- old_space_.StartEndAddress(&old_start, &old_end);
- *start = Utils::Minimum(old_start, *start);
- *end = Utils::Maximum(old_end, *end);
- }
- ASSERT(*start <= *end);
+void Heap::AddRegionsToObjectSet(ObjectSet* set) const {
+ new_space_.AddRegionsToObjectSet(set);
+ old_space_.AddRegionsToObjectSet(set);
}
ObjectSet* Heap::CreateAllocatedObjectSet(
+ Zone* zone,
MarkExpectation mark_expectation) const {
- uword start = static_cast<uword>(-1);
- uword end = 0;
- Isolate* vm_isolate = Dart::vm_isolate();
- vm_isolate->heap()->GetMergedAddressRange(&start, &end);
- this->GetMergedAddressRange(&start, &end);
+ ObjectSet* allocated_set = new(zone) ObjectSet(zone);
- ObjectSet* allocated_set = new ObjectSet(start, end);
+ this->AddRegionsToObjectSet(allocated_set);
{
VerifyObjectVisitor object_visitor(
isolate(), allocated_set, mark_expectation);
this->VisitObjects(&object_visitor);
}
+
+ Isolate* vm_isolate = Dart::vm_isolate();
+ vm_isolate->heap()->AddRegionsToObjectSet(allocated_set);
{
// VM isolate heap is premarked.
VerifyObjectVisitor vm_object_visitor(
isolate(), allocated_set, kRequireMarked);
vm_isolate->heap()->VisitObjects(&vm_object_visitor);
}
+
return allocated_set;
}
@@ -568,10 +556,12 @@
bool Heap::VerifyGC(MarkExpectation mark_expectation) const {
- ObjectSet* allocated_set = CreateAllocatedObjectSet(mark_expectation);
+ StackZone stack_zone(Thread::Current());
+ ObjectSet* allocated_set = CreateAllocatedObjectSet(stack_zone.GetZone(),
+ mark_expectation);
VerifyPointersVisitor visitor(isolate(), allocated_set);
VisitObjectPointers(&visitor);
- delete allocated_set;
+
// Only returning a value so that Heap::Validate can be called from an ASSERT.
return true;
}
diff --git a/runtime/vm/heap.h b/runtime/vm/heap.h
index 63f35d8..deae0a0 100644
--- a/runtime/vm/heap.h
+++ b/runtime/vm/heap.h
@@ -166,7 +166,8 @@
intptr_t Collections(Space space) const;
- ObjectSet* CreateAllocatedObjectSet(MarkExpectation mark_expectation) const;
+ ObjectSet* CreateAllocatedObjectSet(Zone* zone,
+ MarkExpectation mark_expectation) const;
static const char* GCReasonToString(GCReason gc_reason);
@@ -329,10 +330,7 @@
bool BeginOldSpaceGC(Thread* thread);
void EndOldSpaceGC();
- // If this heap is non-empty, updates start and end to the smallest range that
- // contains both the original [start, end) and the [lowest, highest) addresses
- // of this heap.
- void GetMergedAddressRange(uword* start, uword* end) const;
+ void AddRegionsToObjectSet(ObjectSet* set) const;
Isolate* isolate_;
diff --git a/runtime/vm/intermediate_language_dbc.cc b/runtime/vm/intermediate_language_dbc.cc
index d619f09..aca13bd 100644
--- a/runtime/vm/intermediate_language_dbc.cc
+++ b/runtime/vm/intermediate_language_dbc.cc
@@ -34,9 +34,6 @@
M(BinaryInt32Op) \
M(Int32ToDouble) \
M(DoubleToInteger) \
- M(DoubleToDouble) \
- M(DoubleToFloat) \
- M(FloatToDouble) \
M(BoxInt64) \
M(MergedMath) \
M(GuardFieldClass) \
@@ -743,6 +740,20 @@
}
break;
}
+ case kTypedDataFloat32ArrayCid:
+ if (IsExternal()) {
+ Unsupported(compiler);
+ UNREACHABLE();
+ }
+ if (index_scale() == 1) {
+ __ StoreIndexedFloat32(array, index, value);
+ } else if (index_scale() == 4) {
+ __ StoreIndexed4Float32(array, index, value);
+ } else {
+ __ ShlImm(temp, index, Utils::ShiftForPowerOfTwo(index_scale()));
+ __ StoreIndexedFloat32(array, temp, value);
+ }
+ break;
case kTypedDataFloat64ArrayCid:
if (IsExternal()) {
Unsupported(compiler);
@@ -807,10 +818,18 @@
Unsupported(compiler);
UNREACHABLE();
}
+ if (IsExternal()) {
+ Unsupported(compiler);
+ UNREACHABLE();
+ }
__ LoadIndexedTwoByteString(result, array, index);
break;
case kTypedDataInt32ArrayCid:
ASSERT(representation() == kUnboxedInt32);
+ if (IsExternal()) {
+ Unsupported(compiler);
+ UNREACHABLE();
+ }
if (index_scale() == 1) {
__ LoadIndexedInt32(result, array, index);
} else {
@@ -820,6 +839,10 @@
break;
case kTypedDataUint32ArrayCid:
ASSERT(representation() == kUnboxedUint32);
+ if (IsExternal()) {
+ Unsupported(compiler);
+ UNREACHABLE();
+ }
if (index_scale() == 1) {
__ LoadIndexedUint32(result, array, index);
} else {
@@ -827,7 +850,25 @@
__ LoadIndexedUint32(result, array, temp);
}
break;
+ case kTypedDataFloat32ArrayCid:
+ if (IsExternal()) {
+ Unsupported(compiler);
+ UNREACHABLE();
+ }
+ if (index_scale() == 1) {
+ __ LoadIndexedFloat32(result, array, index);
+ } else if (index_scale() == 4) {
+ __ LoadIndexed4Float32(result, array, index);
+ } else {
+ __ ShlImm(temp, index, Utils::ShiftForPowerOfTwo(index_scale()));
+ __ LoadIndexedFloat32(result, array, temp);
+ }
+ break;
case kTypedDataFloat64ArrayCid:
+ if (IsExternal()) {
+ Unsupported(compiler);
+ UNREACHABLE();
+ }
if (index_scale() == 1) {
__ LoadIndexedFloat64(result, array, index);
} else if (index_scale() == 8) {
@@ -916,14 +957,37 @@
LocationSummary::kCall) {
if (ArgumentCount() == 1) {
// Allocate with type arguments.
- __ PushConstant(cls());
- __ AllocateT();
- compiler->AddCurrentDescriptor(RawPcDescriptors::kOther,
- Thread::kNoDeoptId,
- token_pos());
- compiler->RecordSafepoint(locs());
if (compiler->is_optimizing()) {
+ // If we're optimizing, try a streamlined fastpath.
+ const intptr_t instance_size = cls().instance_size();
+ Isolate* isolate = Isolate::Current();
+ if (Heap::IsAllocatableInNewSpace(instance_size) &&
+ !cls().TraceAllocation(isolate)) {
+ uword tags = 0;
+ tags = RawObject::SizeTag::update(instance_size, tags);
+ ASSERT(cls().id() != kIllegalCid);
+ tags = RawObject::ClassIdTag::update(cls().id(), tags);
+ if (Smi::IsValid(tags)) {
+ const intptr_t tags_kidx = __ AddConstant(
+ Smi::Handle(Smi::New(tags)));
+ __ AllocateTOpt(locs()->out(0).reg(), tags_kidx);
+ __ Nop(cls().type_arguments_field_offset());
+ }
+ }
+ __ PushConstant(cls());
+ __ AllocateT();
+ compiler->AddCurrentDescriptor(RawPcDescriptors::kOther,
+ Thread::kNoDeoptId,
+ token_pos());
+ compiler->RecordSafepoint(locs());
__ PopLocal(locs()->out(0).reg());
+ } else {
+ __ PushConstant(cls());
+ __ AllocateT();
+ compiler->AddCurrentDescriptor(RawPcDescriptors::kOther,
+ Thread::kNoDeoptId,
+ token_pos());
+ compiler->RecordSafepoint(locs());
}
} else if (compiler->is_optimizing()) {
// If we're optimizing, try a streamlined fastpath.
@@ -1020,6 +1084,8 @@
0, Location::RequiresRegister(),
LocationSummary::kCall) {
ASSERT(compiler->is_optimizing());
+ __ AllocateUninitializedContext(locs()->out(0).reg(),
+ num_context_variables());
__ AllocateContext(num_context_variables());
compiler->RecordSafepoint(locs());
compiler->AddCurrentDescriptor(RawPcDescriptors::kOther,
@@ -1572,6 +1638,39 @@
}
+EMIT_NATIVE_CODE(DoubleToDouble, 1, Location::RequiresRegister()) {
+ const Register in = locs()->in(0).reg();
+ const Register result = locs()->out(0).reg();
+ switch (recognized_kind()) {
+ case MethodRecognizer::kDoubleTruncate:
+ __ DTruncate(result, in);
+ break;
+ case MethodRecognizer::kDoubleFloor:
+ __ DFloor(result, in);
+ break;
+ case MethodRecognizer::kDoubleCeil:
+ __ DCeil(result, in);
+ break;
+ default:
+ UNREACHABLE();
+ }
+}
+
+
+EMIT_NATIVE_CODE(DoubleToFloat, 1, Location::RequiresRegister()) {
+ const Register in = locs()->in(0).reg();
+ const Register result = locs()->out(0).reg();
+ __ DoubleToFloat(result, in);
+}
+
+
+EMIT_NATIVE_CODE(FloatToDouble, 1, Location::RequiresRegister()) {
+ const Register in = locs()->in(0).reg();
+ const Register result = locs()->out(0).reg();
+ __ FloatToDouble(result, in);
+}
+
+
EMIT_NATIVE_CODE(InvokeMathCFunction,
InputCount(), Location::RequiresRegister()) {
const Register left = locs()->in(0).reg();
diff --git a/runtime/vm/isolate.cc b/runtime/vm/isolate.cc
index f950d7e..908f0f2 100644
--- a/runtime/vm/isolate.cc
+++ b/runtime/vm/isolate.cc
@@ -8,6 +8,7 @@
#include "include/dart_native_api.h"
#include "platform/assert.h"
#include "platform/text_buffer.h"
+#include "vm/atomic.h"
#include "vm/class_finalizer.h"
#include "vm/code_observers.h"
#include "vm/compiler.h"
@@ -142,19 +143,20 @@
}
-
NoReloadScope::NoReloadScope(Isolate* isolate, Thread* thread)
: StackResource(thread),
isolate_(isolate) {
ASSERT(isolate_ != NULL);
- isolate_->no_reload_scope_depth_++;
- ASSERT(isolate_->no_reload_scope_depth_ >= 0);
+ AtomicOperations::FetchAndIncrement(&(isolate_->no_reload_scope_depth_));
+ ASSERT(
+ AtomicOperations::LoadRelaxed(&(isolate_->no_reload_scope_depth_)) >= 0);
}
NoReloadScope::~NoReloadScope() {
- isolate_->no_reload_scope_depth_--;
- ASSERT(isolate_->no_reload_scope_depth_ >= 0);
+ AtomicOperations::FetchAndDecrement(&(isolate_->no_reload_scope_depth_));
+ ASSERT(
+ AtomicOperations::LoadRelaxed(&(isolate_->no_reload_scope_depth_)) >= 0);
}
@@ -1074,7 +1076,8 @@
bool Isolate::CanReload() const {
#ifndef PRODUCT
return !ServiceIsolate::IsServiceIsolateDescendant(this) &&
- is_runnable() && !IsReloading() && (no_reload_scope_depth_ == 0) &&
+ is_runnable() && !IsReloading() &&
+ (AtomicOperations::LoadRelaxed(&no_reload_scope_depth_) == 0) &&
IsolateCreationEnabled();
#else
return false;
@@ -1501,6 +1504,9 @@
// TODO(27003): Enable for precompiled.
#if defined(DEBUG) && !defined(DART_PRECOMPILED_RUNTIME)
if (!isolate->HasAttemptedReload()) {
+ // For this verification we need to stop the background compiler earlier.
+ // This would otherwise happen in Dart::ShowdownIsolate.
+ isolate->StopBackgroundCompiler();
isolate->heap()->CollectAllGarbage();
VerifyCanonicalVisitor check_canonical(thread);
isolate->heap()->IterateObjects(&check_canonical);
@@ -1518,9 +1524,10 @@
void Isolate::SetStickyError(RawError* sticky_error) {
- ASSERT(sticky_error_ == Error::null());
+ ASSERT(((sticky_error_ == Error::null()) ||
+ (sticky_error == Error::null())) &&
+ (sticky_error != sticky_error_));
sticky_error_ = sticky_error;
- message_handler()->PausedOnExit(true);
}
diff --git a/runtime/vm/object.cc b/runtime/vm/object.cc
index 4ed0793..21b4366 100644
--- a/runtime/vm/object.cc
+++ b/runtime/vm/object.cc
@@ -2483,8 +2483,6 @@
}
-// Return a TypeParameter if the type_name is a type parameter of this class.
-// Return null otherwise.
RawTypeParameter* Class::LookupTypeParameter(const String& type_name) const {
ASSERT(!type_name.IsNull());
Thread* thread = Thread::Current();
@@ -5299,9 +5297,13 @@
void Function::ClearCode() const {
+#if defined(DART_PRECOMPILED_RUNTIME)
+ UNREACHABLE();
+#else
ASSERT(Thread::Current()->IsMutatorThread());
StorePointer(&raw_ptr()->unoptimized_code_, Code::null());
SetInstructions(Code::Handle(StubCode::LazyCompile_entry()->code()));
+#endif
}
@@ -5373,9 +5375,13 @@
void Function::set_unoptimized_code(const Code& value) const {
+#if defined(DART_PRECOMPILED_RUNTIME)
+ UNREACHABLE();
+#else
ASSERT(Thread::Current()->IsMutatorThread());
ASSERT(value.IsNull() || !value.is_optimized());
StorePointer(&raw_ptr()->unoptimized_code_, value.raw());
+#endif
}
@@ -5495,6 +5501,12 @@
const Object& obj = Object::Handle(raw_ptr()->data_);
ASSERT(!obj.IsNull());
return ClosureData::Cast(obj).parent_function();
+ } else if (IsSignatureFunction()) {
+ const Object& obj = Object::Handle(raw_ptr()->data_);
+ // Parent function may be null or data_ may already be set to function type.
+ if (!obj.IsNull() && obj.IsFunction()) {
+ return Function::Cast(obj).raw();
+ }
}
return Function::null();
}
@@ -5506,6 +5518,9 @@
ASSERT(!obj.IsNull());
ClosureData::Cast(obj).set_parent_function(value);
return;
+ } else if (IsSignatureFunction()) {
+ set_data(value); // Temporarily set during parsing only.
+ return;
}
UNREACHABLE();
}
@@ -5853,6 +5868,61 @@
}
+void Function::set_type_parameters(const TypeArguments& value) const {
+ StorePointer(&raw_ptr()->type_parameters_, value.raw());
+}
+
+
+intptr_t Function::NumTypeParameters(Thread* thread) const {
+ if (type_parameters() == TypeArguments::null()) {
+ return 0;
+ }
+ REUSABLE_TYPE_ARGUMENTS_HANDLESCOPE(thread);
+ TypeArguments& type_params = thread->TypeArgumentsHandle();
+ type_params = type_parameters();
+ return type_params.Length();
+}
+
+
+RawTypeParameter* Function::LookupTypeParameter(
+ const String& type_name, intptr_t* function_level) const {
+ ASSERT(!type_name.IsNull());
+ Thread* thread = Thread::Current();
+ REUSABLE_TYPE_ARGUMENTS_HANDLESCOPE(thread);
+ REUSABLE_TYPE_PARAMETER_HANDLESCOPE(thread);
+ REUSABLE_STRING_HANDLESCOPE(thread);
+ TypeArguments& type_params = thread->TypeArgumentsHandle();
+ TypeParameter& type_param = thread->TypeParameterHandle();
+ String& type_param_name = thread->StringHandle();
+ Function& function = thread->FunctionHandle();
+
+ function ^= this->raw();
+ intptr_t parent_level = -1;
+ while (!function.IsNull()) {
+ type_params ^= function.type_parameters();
+ if (!type_params.IsNull()) {
+ parent_level++;
+ const intptr_t num_type_params = type_params.Length();
+ for (intptr_t i = 0; i < num_type_params; i++) {
+ type_param ^= type_params.TypeAt(i);
+ type_param_name = type_param.name();
+ if (type_param_name.Equals(type_name)) {
+ if (parent_level > 0) {
+ // TODO(regis): Clone type parameter and set parent_level.
+ }
+ return type_param.raw();
+ }
+ }
+ }
+ function ^= function.parent_function();
+ if (function_level != NULL) {
+ (*function_level)--;
+ }
+ }
+ return TypeParameter::null();
+}
+
+
void Function::set_kind(RawFunction::Kind value) const {
set_kind_tag(KindBits::update(value, raw_ptr()->kind_tag_));
}
@@ -5871,8 +5941,12 @@
void Function::set_token_pos(TokenPosition token_pos) const {
+#if defined(DART_PRECOMPILED_RUNTIME)
+ UNREACHABLE();
+#else
ASSERT(!token_pos.IsClassifying() || IsMethodExtractor());
StoreNonPointer(&raw_ptr()->token_pos_, token_pos);
+#endif
}
@@ -6527,16 +6601,16 @@
result.set_is_generated_body(false);
result.set_always_inline(false);
result.set_is_polymorphic_target(false);
- result.set_was_compiled(false);
+ NOT_IN_PRECOMPILED(result.set_was_compiled(false));
result.set_owner(owner);
- result.set_token_pos(token_pos);
- result.set_end_token_pos(token_pos);
+ NOT_IN_PRECOMPILED(result.set_token_pos(token_pos));
+ NOT_IN_PRECOMPILED(result.set_end_token_pos(token_pos));
result.set_num_fixed_parameters(0);
result.set_num_optional_parameters(0);
- result.set_usage_counter(0);
- result.set_deoptimization_counter(0);
- result.set_optimized_instruction_count(0);
- result.set_optimized_call_site_count(0);
+ NOT_IN_PRECOMPILED(result.set_usage_counter(0));
+ NOT_IN_PRECOMPILED(result.set_deoptimization_counter(0));
+ NOT_IN_PRECOMPILED(result.set_optimized_instruction_count(0));
+ NOT_IN_PRECOMPILED(result.set_optimized_call_site_count(0));
result.set_is_optimizable(is_native ? false : true);
result.set_is_inlinable(true);
result.set_allows_hoisting_check_class(true);
@@ -12599,8 +12673,12 @@
void ICData::set_deopt_id(intptr_t value) const {
+#if defined(DART_PRECOMPILED_RUNTIME)
+ UNREACHABLE();
+#else
ASSERT(value <= kMaxInt32);
StoreNonPointer(&raw_ptr()->deopt_id_, value);
+#endif
}
@@ -13512,7 +13590,7 @@
result.set_owner(owner);
result.set_target_name(target_name);
result.set_arguments_descriptor(arguments_descriptor);
- result.set_deopt_id(deopt_id);
+ NOT_IN_PRECOMPILED(result.set_deopt_id(deopt_id));
result.set_state_bits(0);
#if defined(TAG_IC_DATA)
result.set_tag(-1);
@@ -13700,13 +13778,21 @@
void Code::set_deopt_info_array(const Array& array) const {
+#if defined(DART_PRECOMPILED_RUNTIME)
+ UNREACHABLE();
+#else
ASSERT(array.IsOld());
StorePointer(&raw_ptr()->deopt_info_array_, array.raw());
+#endif
}
void Code::set_static_calls_target_table(const Array& value) const {
+#if defined(DART_PRECOMPILED_RUNTIME)
+ UNREACHABLE();
+#else
StorePointer(&raw_ptr()->static_calls_target_table_, value.raw());
+#endif
#if defined(DEBUG)
// Check that the table is sorted by pc offsets.
// FlowGraphCompiler::AddStaticCallTarget adds pc-offsets to the table while
@@ -13769,6 +13855,9 @@
intptr_t Code::BinarySearchInSCallTable(uword pc) const {
+#if defined(DART_PRECOMPILED_RUNTIME)
+ UNREACHABLE();
+#else
NoSafepointScope no_safepoint;
const Array& table = Array::Handle(raw_ptr()->static_calls_target_table_);
RawObject* key = reinterpret_cast<RawObject*>(Smi::New(pc - PayloadStart()));
@@ -13786,11 +13875,16 @@
return real_index;
}
}
+#endif
return -1;
}
RawFunction* Code::GetStaticCallTargetFunctionAt(uword pc) const {
+#if defined(DART_PRECOMPILED_RUNTIME)
+ UNREACHABLE();
+ return Function::null();
+#else
const intptr_t i = BinarySearchInSCallTable(pc);
if (i < 0) {
return Function::null();
@@ -13800,10 +13894,15 @@
Function& function = Function::Handle();
function ^= array.At(i + kSCallTableFunctionEntry);
return function.raw();
+#endif
}
RawCode* Code::GetStaticCallTargetCodeAt(uword pc) const {
+#if defined(DART_PRECOMPILED_RUNTIME)
+ UNREACHABLE();
+ return Code::null();
+#else
const intptr_t i = BinarySearchInSCallTable(pc);
if (i < 0) {
return Code::null();
@@ -13813,10 +13912,14 @@
Code& code = Code::Handle();
code ^= array.At(i + kSCallTableCodeEntry);
return code.raw();
+#endif
}
void Code::SetStaticCallTargetCodeAt(uword pc, const Code& code) const {
+#if defined(DART_PRECOMPILED_RUNTIME)
+ UNREACHABLE();
+#else
const intptr_t i = BinarySearchInSCallTable(pc);
ASSERT(i >= 0);
const Array& array =
@@ -13824,10 +13927,14 @@
ASSERT(code.IsNull() ||
(code.function() == array.At(i + kSCallTableFunctionEntry)));
array.SetAt(i + kSCallTableCodeEntry, code);
+#endif
}
void Code::SetStubCallTargetCodeAt(uword pc, const Code& code) const {
+#if defined(DART_PRECOMPILED_RUNTIME)
+ UNREACHABLE();
+#else
const intptr_t i = BinarySearchInSCallTable(pc);
ASSERT(i >= 0);
const Array& array =
@@ -13841,6 +13948,7 @@
}
#endif
array.SetAt(i + kSCallTableCodeEntry, code);
+#endif
}
@@ -13861,26 +13969,41 @@
const Code::Comments& Code::comments() const {
+#if defined(DART_PRECOMPILED_RUNTIME)
+ Comments* comments = new Code::Comments(Array::Handle());
+#else
Comments* comments = new Code::Comments(Array::Handle(raw_ptr()->comments_));
+#endif
return *comments;
}
void Code::set_comments(const Code::Comments& comments) const {
+#if defined(DART_PRECOMPILED_RUNTIME)
+ UNREACHABLE();
+#else
ASSERT(comments.comments_.IsOld());
StorePointer(&raw_ptr()->comments_, comments.comments_.raw());
+#endif
}
void Code::SetPrologueOffset(intptr_t offset) const {
+#if defined(DART_PRECOMPILED_RUNTIME)
+ UNREACHABLE();
+#else
ASSERT(offset >= 0);
StoreSmi(
reinterpret_cast<RawSmi* const *>(&raw_ptr()->return_address_metadata_),
Smi::New(offset));
+#endif
}
intptr_t Code::GetPrologueOffset() const {
+#if defined(DART_PRECOMPILED_RUNTIME)
+ return -1;
+#else
const Object& object = Object::Handle(raw_ptr()->return_address_metadata_);
// In the future we may put something other than a smi in
// |return_address_metadata_|.
@@ -13888,20 +14011,28 @@
return -1;
}
return Smi::Cast(object).Value();
+#endif
}
RawArray* Code::GetInlinedIntervals() const {
+#if defined(DART_PRECOMPILED_RUNTIME)
+ return Array::null();
+#else
const Array& metadata = Array::Handle(raw_ptr()->inlined_metadata_);
if (metadata.IsNull()) {
return metadata.raw();
}
return reinterpret_cast<RawArray*>(
metadata.At(RawCode::kInlinedIntervalsIndex));
+#endif
}
void Code::SetInlinedIntervals(const Array& value) const {
+#if defined(DART_PRECOMPILED_RUNTIME)
+ UNREACHABLE();
+#else
if (raw_ptr()->inlined_metadata_ == Array::null()) {
StorePointer(&raw_ptr()->inlined_metadata_,
Array::New(RawCode::kInlinedMetadataSize, Heap::kOld));
@@ -13911,20 +14042,28 @@
ASSERT(metadata.IsOld());
ASSERT(value.IsOld());
metadata.SetAt(RawCode::kInlinedIntervalsIndex, value);
+#endif
}
RawArray* Code::GetInlinedIdToFunction() const {
+#if defined(DART_PRECOMPILED_RUNTIME)
+ return Array::null();
+#else
const Array& metadata = Array::Handle(raw_ptr()->inlined_metadata_);
if (metadata.IsNull()) {
return metadata.raw();
}
return reinterpret_cast<RawArray*>(
metadata.At(RawCode::kInlinedIdToFunctionIndex));
+#endif
}
void Code::SetInlinedIdToFunction(const Array& value) const {
+#if defined(DART_PRECOMPILED_RUNTIME)
+ UNREACHABLE();
+#else
if (raw_ptr()->inlined_metadata_ == Array::null()) {
StorePointer(&raw_ptr()->inlined_metadata_,
Array::New(RawCode::kInlinedMetadataSize, Heap::kOld));
@@ -13934,20 +14073,28 @@
ASSERT(metadata.IsOld());
ASSERT(value.IsOld());
metadata.SetAt(RawCode::kInlinedIdToFunctionIndex, value);
+#endif
}
RawArray* Code::GetInlinedIdToTokenPos() const {
+#if defined(DART_PRECOMPILED_RUNTIME)
+ return Array::null();
+#else
const Array& metadata = Array::Handle(raw_ptr()->inlined_metadata_);
if (metadata.IsNull()) {
return metadata.raw();
}
return reinterpret_cast<RawArray*>(
metadata.At(RawCode::kInlinedIdToTokenPosIndex));
+#endif
}
void Code::SetInlinedIdToTokenPos(const Array& value) const {
+#if defined(DART_PRECOMPILED_RUNTIME)
+ UNREACHABLE();
+#else
if (raw_ptr()->inlined_metadata_ == Array::null()) {
StorePointer(&raw_ptr()->inlined_metadata_,
Array::New(RawCode::kInlinedMetadataSize, Heap::kOld));
@@ -13957,20 +14104,28 @@
ASSERT(metadata.IsOld());
ASSERT(value.IsOld());
metadata.SetAt(RawCode::kInlinedIdToTokenPosIndex, value);
+#endif
}
RawArray* Code::GetInlinedCallerIdMap() const {
+#if defined(DART_PRECOMPILED_RUNTIME)
+ return Array::null();
+#else
const Array& metadata = Array::Handle(raw_ptr()->inlined_metadata_);
if (metadata.IsNull()) {
return metadata.raw();
}
return reinterpret_cast<RawArray*>(
metadata.At(RawCode::kInlinedCallerIdMapIndex));
+#endif
}
void Code::SetInlinedCallerIdMap(const Array& value) const {
+#if defined(DART_PRECOMPILED_RUNTIME)
+ UNREACHABLE();
+#else
if (raw_ptr()->inlined_metadata_ == Array::null()) {
StorePointer(&raw_ptr()->inlined_metadata_,
Array::New(RawCode::kInlinedMetadataSize, Heap::kOld));
@@ -13980,6 +14135,7 @@
ASSERT(metadata.IsOld());
ASSERT(value.IsOld());
metadata.SetAt(RawCode::kInlinedCallerIdMapIndex, value);
+#endif
}
@@ -14296,6 +14452,9 @@
void Code::SetActiveInstructions(RawInstructions* instructions) const {
+#if defined(DART_PRECOMPILED_RUNTIME)
+ UNREACHABLE();
+#else
DEBUG_ASSERT(IsMutatorOrAtSafepoint() || !is_alive());
// RawInstructions are never allocated in New space and hence a
// store buffer update is not needed here.
@@ -14304,6 +14463,7 @@
Instructions::UncheckedEntryPoint(instructions));
StoreNonPointer(&raw_ptr()->checked_entry_point_,
Instructions::CheckedEntryPoint(instructions));
+#endif
}
@@ -15351,11 +15511,11 @@
const Class& cls = Class::Handle(zone, this->clazz());
{
SafepointMutexLocker ml(isolate->constant_canonicalization_mutex());
+ result ^= cls.LookupCanonicalInstance(zone, *this);
+ if (!result.IsNull()) {
+ return result.raw();
+ }
if (IsNew()) {
- result ^= cls.LookupCanonicalInstance(zone, *this);
- if (!result.IsNull()) {
- return result.raw();
- }
ASSERT((isolate == Dart::vm_isolate()) || !InVMHeap());
// Create a canonical object in old space.
result ^= Object::Clone(*this, Heap::kOld);
@@ -15377,12 +15537,6 @@
const Class& cls = Class::Handle(zone, this->clazz());
SafepointMutexLocker ml(isolate->constant_canonicalization_mutex());
result ^= cls.LookupCanonicalInstance(zone, *this);
- // TODO(johnmccutchan) : Temporary workaround for issue (26988).
- if ((result.raw() != raw()) &&
- isolate->HasAttemptedReload() &&
- (GetClassId() == kImmutableArrayCid)) {
- return true;
- }
return (result.raw() == this->raw());
}
#endif // DEBUG
@@ -17610,6 +17764,11 @@
}
+void TypeParameter::set_parameterized_function(const Function& value) const {
+ StorePointer(&raw_ptr()->parameterized_function_, value.raw());
+}
+
+
void TypeParameter::set_index(intptr_t value) const {
ASSERT(value >= 0);
ASSERT(Utils::IsInt(16, value));
@@ -17720,6 +17879,7 @@
}
// No need to clone bound, as it is not part of the finalization state.
return TypeParameter::New(Class::Handle(parameterized_class()),
+ Function::Handle(parameterized_function()),
index(),
String::Handle(name()),
AbstractType::Handle(bound()),
@@ -17739,7 +17899,9 @@
const intptr_t new_index = index() +
new_owner.NumTypeArguments() - old_owner.NumTypeArguments();
AbstractType& upper_bound = AbstractType::Handle(bound());
+ ASSERT(parameterized_function() == Function::null());
clone = TypeParameter::New(new_owner,
+ Function::Handle(),
new_index,
String::Handle(name()),
upper_bound, // Not cloned yet.
@@ -17790,12 +17952,15 @@
RawTypeParameter* TypeParameter::New(const Class& parameterized_class,
+ const Function& parameterized_function,
intptr_t index,
const String& name,
const AbstractType& bound,
TokenPosition token_pos) {
+ ASSERT(parameterized_class.IsNull() != parameterized_function.IsNull());
const TypeParameter& result = TypeParameter::Handle(TypeParameter::New());
result.set_parameterized_class(parameterized_class);
+ result.set_parameterized_function(parameterized_function);
result.set_index(index);
result.set_name(name);
result.set_bound(bound);
@@ -21417,6 +21582,7 @@
uword Array::ComputeCanonicalTableHash() const {
ASSERT(!IsNull());
+ NoSafepointScope no_safepoint;
intptr_t len = Length();
uword hash = len;
uword value = reinterpret_cast<uword>(GetTypeArguments());
diff --git a/runtime/vm/object.h b/runtime/vm/object.h
index b502dfc..91f37f2 100644
--- a/runtime/vm/object.h
+++ b/runtime/vm/object.h
@@ -1886,7 +1886,12 @@
intptr_t NumArgsTested() const;
intptr_t deopt_id() const {
+#if defined(DART_PRECOMPILED_RUNTIME)
+ UNREACHABLE();
+ return -1;
+#else
return raw_ptr()->deopt_id_;
+#endif
}
bool IsImmutable() const;
@@ -2284,6 +2289,27 @@
RawArray* parameter_names() const { return raw_ptr()->parameter_names_; }
void set_parameter_names(const Array& value) const;
+ // The type parameters (and their bounds) are specified as an array of
+ // TypeParameter.
+ RawTypeArguments* type_parameters() const {
+ return raw_ptr()->type_parameters_;
+ }
+ void set_type_parameters(const TypeArguments& value) const;
+ intptr_t NumTypeParameters(Thread* thread) const;
+ intptr_t NumTypeParameters() const {
+ return NumTypeParameters(Thread::Current());
+ }
+
+ // Return a TypeParameter if the type_name is a type parameter of this
+ // function or of one of its parent functions.
+ // Unless NULL, adjust function_level accordingly (in and out parameter).
+ // Return null otherwise.
+ RawTypeParameter* LookupTypeParameter(const String& type_name,
+ intptr_t* function_level) const;
+
+ // Return true if this function declares type parameters.
+ bool IsGeneric() const { return NumTypeParameters() > 0; }
+
// Not thread-safe; must be called in the main thread.
// Sets function's code and code's function.
void InstallOptimizedCode(const Code& code, bool is_osr) const;
@@ -2307,7 +2333,13 @@
return raw_ptr()->code_;
}
- RawCode* unoptimized_code() const { return raw_ptr()->unoptimized_code_; }
+ RawCode* unoptimized_code() const {
+#if defined(DART_PRECOMPILED_RUNTIME)
+ return static_cast<RawCode*>(Object::null());
+#else
+ return raw_ptr()->unoptimized_code_;
+#endif
+ }
void set_unoptimized_code(const Code& value) const;
bool HasCode() const;
@@ -2441,12 +2473,28 @@
}
bool IsInFactoryScope() const;
- TokenPosition token_pos() const { return raw_ptr()->token_pos_; }
+ TokenPosition token_pos() const {
+#if defined(DART_PRECOMPILED_RUNTIME)
+ return TokenPosition();
+#else
+ return raw_ptr()->token_pos_;
+#endif
+ }
void set_token_pos(TokenPosition value) const;
- TokenPosition end_token_pos() const { return raw_ptr()->end_token_pos_; }
+ TokenPosition end_token_pos() const {
+#if defined(DART_PRECOMPILED_RUNTIME)
+ return TokenPosition();
+#else
+ return raw_ptr()->end_token_pos_;
+#endif
+}
void set_end_token_pos(TokenPosition value) const {
+#if defined(DART_PRECOMPILED_RUNTIME)
+ UNREACHABLE();
+#else
StoreNonPointer(&raw_ptr()->end_token_pos_, value);
+#endif
}
intptr_t num_fixed_parameters() const {
@@ -2484,48 +2532,86 @@
intptr_t NumImplicitParameters() const;
static intptr_t usage_counter_offset() {
+#if defined(DART_PRECOMPILED_RUNTIME)
+ UNREACHABLE();
+ return 0;
+#else
return OFFSET_OF(RawFunction, usage_counter_);
+#endif
}
intptr_t usage_counter() const {
+#if defined(DART_PRECOMPILED_RUNTIME)
+ return 0;
+#else
return raw_ptr()->usage_counter_;
+#endif
}
void set_usage_counter(intptr_t value) const {
+#if defined(DART_PRECOMPILED_RUNTIME)
+ UNREACHABLE();
+#else
// TODO(Srdjan): Assert that this is thread-safe, i.e., only
// set from mutator-thread or while at a safepoint (e.g., during marking).
StoreNonPointer(&raw_ptr()->usage_counter_, value);
+#endif
}
int8_t deoptimization_counter() const {
+#if defined(DART_PRECOMPILED_RUNTIME)
+ return 0;
+#else
return raw_ptr()->deoptimization_counter_;
+#endif
}
void set_deoptimization_counter(int8_t value) const {
+#if defined(DART_PRECOMPILED_RUNTIME)
+ UNREACHABLE();
+#else
ASSERT(value >= 0);
StoreNonPointer(&raw_ptr()->deoptimization_counter_, value);
+#endif
}
static const intptr_t kMaxInstructionCount = (1 << 16) - 1;
intptr_t optimized_instruction_count() const {
+#if defined(DART_PRECOMPILED_RUNTIME)
+ UNREACHABLE();
+ return 0;
+#else
return raw_ptr()->optimized_instruction_count_;
+#endif
}
void set_optimized_instruction_count(intptr_t value) const {
+#if defined(DART_PRECOMPILED_RUNTIME)
+ UNREACHABLE();
+#else
ASSERT(value >= 0);
if (value > kMaxInstructionCount) {
value = kMaxInstructionCount;
}
StoreNonPointer(&raw_ptr()->optimized_instruction_count_,
static_cast<uint16_t>(value));
+#endif
}
intptr_t optimized_call_site_count() const {
+#if defined(DART_PRECOMPILED_RUNTIME)
+ return 0;
+#else
return raw_ptr()->optimized_call_site_count_;
+#endif
}
void set_optimized_call_site_count(intptr_t value) const {
+#if defined(DART_PRECOMPILED_RUNTIME)
+ UNREACHABLE();
+#else
ASSERT(value >= 0);
if (value > kMaxInstructionCount) {
value = kMaxInstructionCount;
}
StoreNonPointer(&raw_ptr()->optimized_call_site_count_,
static_cast<uint16_t>(value));
+#endif
}
bool IsOptimizable() const;
@@ -2785,9 +2871,20 @@
// VM instantiation. It is independent from presence of type feedback
// (ic_data_array) and code, which may be loaded from a snapshot.
void set_was_compiled(bool value) const {
+#if defined(DART_PRECOMPILED_RUNTIME)
+ UNREACHABLE();
+#else
StoreNonPointer(&raw_ptr()->was_compiled_, value ? 1 : 0);
+#endif
}
- bool was_compiled() const { return raw_ptr()->was_compiled_ == 1; }
+ bool was_compiled() const {
+#if defined(DART_PRECOMPILED_RUNTIME)
+ UNREACHABLE();
+ return true;
+#else
+ return raw_ptr()->was_compiled_ == 1;
+#endif
+ }
// static: Considered during class-side or top-level resolution rather than
// instance-side resolution.
@@ -4504,7 +4601,12 @@
class Code : public Object {
public:
RawInstructions* active_instructions() const {
+#if defined(DART_PRECOMPILED_RUNTIME)
+ UNREACHABLE();
+ return NULL;
+#else
return raw_ptr()->active_instructions_;
+#endif
}
RawInstructions* instructions() const { return raw_ptr()->instructions_; }
@@ -4572,12 +4674,20 @@
}
RawCodeSourceMap* code_source_map() const {
+#if defined(DART_PRECOMPILED_RUNTIME)
+ return CodeSourceMap::null();
+#else
return raw_ptr()->code_source_map_;
+#endif
}
void set_code_source_map(const CodeSourceMap& code_source_map) const {
+#if defined(DART_PRECOMPILED_RUNTIME)
+ UNREACHABLE();
+#else
ASSERT(code_source_map.IsOld());
StorePointer(&raw_ptr()->code_source_map_, code_source_map.raw());
+#endif
}
// Used during reloading (see object_reload.cc). Calls Reset on all ICDatas
@@ -4588,7 +4698,12 @@
// Array of DeoptInfo objects.
RawArray* deopt_info_array() const {
+#if defined(DART_PRECOMPILED_RUNTIME)
+ UNREACHABLE();
+ return NULL;
+#else
return raw_ptr()->deopt_info_array_;
+#endif
}
void set_deopt_info_array(const Array& array) const;
@@ -4608,7 +4723,12 @@
void set_static_calls_target_table(const Array& value) const;
RawArray* static_calls_target_table() const {
+#if defined(DART_PRECOMPILED_RUNTIME)
+ UNREACHABLE();
+ return NULL;
+#else
return raw_ptr()->static_calls_target_table_;
+#endif
}
RawTypedData* GetDeoptInfoAtPc(uword pc,
@@ -4659,7 +4779,12 @@
void set_comments(const Comments& comments) const;
RawObject* return_address_metadata() const {
+#if defined(DART_PRECOMPILED_RUNTIME)
+ UNREACHABLE();
+ return NULL;
+#else
return raw_ptr()->return_address_metadata_;
+#endif
}
// Sets |return_address_metadata|.
void SetPrologueOffset(intptr_t offset) const;
@@ -4694,11 +4819,20 @@
void DumpInlinedIntervals() const;
RawLocalVarDescriptors* var_descriptors() const {
+#if defined(DART_PRECOMPILED_RUNTIME)
+ UNREACHABLE();
+ return NULL;
+#else
return raw_ptr()->var_descriptors_;
+#endif
}
void set_var_descriptors(const LocalVarDescriptors& value) const {
+#if defined(DART_PRECOMPILED_RUNTIME)
+ UNREACHABLE();
+#else
ASSERT(value.IsOld());
StorePointer(&raw_ptr()->var_descriptors_, value.raw());
+#endif
}
// Will compute local var descriptors is necessary.
@@ -4779,14 +4913,26 @@
RawString* QualifiedName() const;
int64_t compile_timestamp() const {
+#if defined(DART_PRECOMPILED_RUNTIME)
+ return 0;
+#else
return raw_ptr()->compile_timestamp_;
+#endif
}
intptr_t lazy_deopt_pc_offset() const {
+#if defined(DART_PRECOMPILED_RUNTIME)
+ return 0;
+#else
return raw_ptr()->lazy_deopt_pc_offset_;
+#endif
}
void set_lazy_deopt_pc_offset(intptr_t pc) const {
+#if defined(DART_PRECOMPILED_RUNTIME)
+ UNREACHABLE();
+#else
StoreNonPointer(&raw_ptr()->lazy_deopt_pc_offset_, pc);
+#endif
}
bool IsAllocationStubCode() const;
@@ -4850,7 +4996,11 @@
static const intptr_t kEntrySize = sizeof(int32_t); // NOLINT
void set_compile_timestamp(int64_t timestamp) const {
+#if defined(DART_PRECOMPILED_RUNTIME)
+ UNREACHABLE();
+#else
StoreNonPointer(&raw_ptr()->compile_timestamp_, timestamp);
+#endif
}
void SetActiveInstructions(RawInstructions* instructions) const;
@@ -5080,6 +5230,7 @@
private:
friend class Class;
friend class MegamorphicCacheTable;
+ friend class Precompiler;
static RawMegamorphicCache* New();
@@ -5219,6 +5370,8 @@
virtual const char* ToErrorCString() const;
+ TokenPosition token_pos() const { return raw_ptr()->token_pos_; }
+
private:
RawError* previous_error() const {
return raw_ptr()->previous_error_;
@@ -5228,7 +5381,6 @@
RawScript* script() const { return raw_ptr()->script_; }
void set_script(const Script& value) const;
- TokenPosition token_pos() const { return raw_ptr()->token_pos_; }
void set_token_pos(TokenPosition value) const;
bool report_after_token() const { return raw_ptr()->report_after_token_; }
@@ -5975,6 +6127,15 @@
virtual bool HasResolvedTypeClass() const { return false; }
classid_t parameterized_class_id() const;
RawClass* parameterized_class() const;
+ RawFunction* parameterized_function() const {
+ return raw_ptr()->parameterized_function_;
+ }
+ bool IsClassTypeParameter() const {
+ return parameterized_class_id() != kIllegalCid;
+ }
+ bool IsFunctionTypeParameter() const {
+ return parameterized_function() != Function::null();
+ }
RawString* name() const { return raw_ptr()->name_; }
intptr_t index() const { return raw_ptr()->index_; }
void set_index(intptr_t value) const;
@@ -6021,7 +6182,9 @@
return RoundedAllocationSize(sizeof(RawTypeParameter));
}
+ // Only one of parameterized_class and parameterized_function is non-null.
static RawTypeParameter* New(const Class& parameterized_class,
+ const Function& parameterized_function,
intptr_t index,
const String& name,
const AbstractType& bound,
@@ -6032,6 +6195,7 @@
void SetHash(intptr_t value) const;
void set_parameterized_class(const Class& value) const;
+ void set_parameterized_function(const Function& value) const;
void set_name(const String& value) const;
void set_token_pos(TokenPosition token_pos) const;
void set_type_state(int8_t state) const;
diff --git a/runtime/vm/object_set.h b/runtime/vm/object_set.h
index cdc642f..8ba53ba 100644
--- a/runtime/vm/object_set.h
+++ b/runtime/vm/object_set.h
@@ -6,109 +6,86 @@
#define VM_OBJECT_SET_H_
#include "platform/utils.h"
+#include "vm/bit_vector.h"
#include "vm/globals.h"
#include "vm/raw_object.h"
+#include "vm/zone.h"
namespace dart {
-class ObjectSet {
+class ObjectSetRegion : public ZoneAllocated {
public:
- ObjectSet() {
- Init(0, 0);
+ ObjectSetRegion(Zone* zone, uword start, uword end)
+ : start_(start),
+ end_(end),
+ bit_vector_(zone, (end - start) >> kWordSizeLog2),
+ next_(NULL) {
}
- ObjectSet(uword start, uword end) {
- Init(start, end);
+ bool ContainsAddress(uword address) {
+ return address >= start_ && address < end_;
}
- ~ObjectSet() {
- delete[] allocation_;
+ intptr_t IndexForAddress(uword address) {
+ ASSERT(Utils::IsAligned(address, kWordSize));
+ return (address - start_) >> kWordSizeLog2;
}
- void Init(uword start, uword end) {
- start_ = start;
- end_ = end;
- ASSERT(start_ <= end_);
- size_ = SizeFor((end_ - start_) >> kWordSizeLog2);
- allocation_ = new uword[size_];
- const intptr_t skipped_bitfield_words =
- (start >> kWordSizeLog2) / kBitsPerWord;
- data_ = &allocation_[-skipped_bitfield_words];
- ASSERT(allocation_ == &data_[skipped_bitfield_words]);
- Clear();
+ void AddObject(uword address) {
+ bit_vector_.Add(IndexForAddress(address));
+ }
+
+ bool ContainsObject(uword address) {
+ return bit_vector_.Contains(IndexForAddress(address));
+ }
+
+ ObjectSetRegion* next() { return next_; }
+ void set_next(ObjectSetRegion* region) { next_ = region; }
+
+ private:
+ uword start_;
+ uword end_;
+ BitVector bit_vector_;
+ ObjectSetRegion* next_;
+};
+
+class ObjectSet : public ZoneAllocated {
+ public:
+ explicit ObjectSet(Zone* zone) : zone_(zone), head_(NULL) { }
+
+ void AddRegion(uword start, uword end) {
+ ObjectSetRegion* region = new(zone_) ObjectSetRegion(zone_, start, end);
+ region->set_next(head_);
+ head_ = region;
}
bool Contains(RawObject* raw_obj) const {
uword raw_addr = RawObject::ToAddr(raw_obj);
- ASSERT(raw_addr >= start_);
- ASSERT(raw_addr < end_);
- uword i = raw_addr >> kWordSizeLog2;
- uword mask = (static_cast<uword>(1) << (i % kBitsPerWord));
- return (data_[i / kBitsPerWord] & mask) != 0;
+ for (ObjectSetRegion* region = head_;
+ region != NULL;
+ region = region->next()) {
+ if (region->ContainsAddress(raw_addr)) {
+ return region->ContainsObject(raw_addr);
+ }
+ }
+ return false;
}
void Add(RawObject* raw_obj) {
uword raw_addr = RawObject::ToAddr(raw_obj);
- ASSERT(raw_addr >= start_);
- ASSERT(raw_addr < end_);
- uword i = raw_addr >> kWordSizeLog2;
- data_[i / kBitsPerWord] |= (static_cast<uword>(1) << (i % kBitsPerWord));
- min_ = Utils::Minimum(raw_addr, min_);
- max_ = Utils::Maximum(raw_addr, max_);
- }
-
- void Resize(uword start, uword end) {
- if (start_ != start || end_ != end) {
- delete[] allocation_;
- Init(start, end);
+ for (ObjectSetRegion* region = head_;
+ region != NULL;
+ region = region->next()) {
+ if (region->ContainsAddress(raw_addr)) {
+ return region->AddObject(raw_addr);
+ }
}
- }
-
- void Clear() {
- memset(allocation_, 0, (size_ * sizeof(allocation_[0])));
- min_ = end_;
- max_ = start_;
- }
-
- void FastClear() {
- uword i = min_ >> kWordSizeLog2;
- memset(&data_[i / kBitsPerWord],
- 0,
- sizeof(uword) * SizeFor((max_ + 1 - min_) >> kWordSizeLog2));
- min_ = end_;
- max_ = start_;
+ FATAL("Address not in any heap region");
}
private:
- static intptr_t SizeFor(intptr_t length) {
- return 1 + ((length - 1) / kBitsPerWord);
- }
-
- // Biased data pointer aliased to allocation_. This value can be
- // indexed without adjusting for the starting address of the heap.
- uword* data_;
-
- // Allocated data pointer.
- uword* allocation_;
-
- // Allocation size in uwords.
- intptr_t size_;
-
- // Lowest possible heap address, inclusive.
- uword start_;
-
- // Highest possible heap address, exclusive.
- uword end_;
-
- // The inclusive minimum address set in this ObjectMap.
- // Used by FastClear
- uword min_;
-
- // The inclusive maximum address in this ObjectMap.
- // Used by FastClear
- uword max_;
-
- DISALLOW_COPY_AND_ASSIGN(ObjectSet);
+ Zone* zone_;
+ ObjectSetRegion* head_;
};
} // namespace dart
diff --git a/runtime/vm/object_store.cc b/runtime/vm/object_store.cc
index e0bf805..8812a8e 100644
--- a/runtime/vm/object_store.cc
+++ b/runtime/vm/object_store.cc
@@ -35,6 +35,7 @@
int32x4_type_(Type::null()),
float64x2_type_(Type::null()),
string_type_(Type::null()),
+ compiletime_error_class_(Class::null()),
future_class_(Class::null()),
completer_class_(Class::null()),
stream_iterator_class_(Class::null()),
@@ -243,6 +244,11 @@
cls = internal_lib.LookupClass(Symbols::Symbol());
set_symbol_class(cls);
+ const Library& core_lib = Library::Handle(core_library());
+ cls = core_lib.LookupClassAllowPrivate(Symbols::_CompileTimeError());
+ ASSERT(!cls.IsNull());
+ set_compiletime_error_class(cls);
+
// Cache the core private functions used for fast instance of checks.
simple_instance_of_function_ =
PrivateObjectLookup(Symbols::_simpleInstanceOf());
diff --git a/runtime/vm/object_store.h b/runtime/vm/object_store.h
index e6d6293..33c25ec 100644
--- a/runtime/vm/object_store.h
+++ b/runtime/vm/object_store.h
@@ -116,6 +116,13 @@
string_type_ = value.raw();
}
+ RawClass* compiletime_error_class() const {
+ return compiletime_error_class_;
+ }
+ void set_compiletime_error_class(const Class& value) {
+ compiletime_error_class_ = value.raw();
+ }
+
RawClass* future_class() const { return future_class_; }
void set_future_class(const Class& value) {
future_class_ = value.raw();
@@ -532,6 +539,7 @@
V(RawType*, int32x4_type_) \
V(RawType*, float64x2_type_) \
V(RawType*, string_type_) \
+ V(RawClass*, compiletime_error_class_) \
V(RawClass*, future_class_) \
V(RawClass*, completer_class_) \
V(RawClass*, stream_iterator_class_) \
diff --git a/runtime/vm/pages.cc b/runtime/vm/pages.cc
index 2f894b5..80527f2 100644
--- a/runtime/vm/pages.cc
+++ b/runtime/vm/pages.cc
@@ -10,6 +10,7 @@
#include "vm/gc_sweeper.h"
#include "vm/lockers.h"
#include "vm/object.h"
+#include "vm/object_set.h"
#include "vm/os_thread.h"
#include "vm/safepoint.h"
#include "vm/virtual_memory.h"
@@ -588,16 +589,11 @@
}
-void PageSpace::StartEndAddress(uword* start, uword* end) const {
+void PageSpace::AddRegionsToObjectSet(ObjectSet* set) const {
ASSERT((pages_ != NULL) || (exec_pages_ != NULL) || (large_pages_ != NULL));
- *start = static_cast<uword>(~0);
- *end = 0;
for (ExclusivePageIterator it(this); !it.Done(); it.Advance()) {
- *start = Utils::Minimum(*start, it.page()->object_start());
- *end = Utils::Maximum(*end, it.page()->object_end());
+ set->AddRegion(it.page()->object_start(), it.page()->object_end());
}
- ASSERT(*start != static_cast<uword>(~0));
- ASSERT(*end != 0);
}
diff --git a/runtime/vm/pages.h b/runtime/vm/pages.h
index ae32c87..640e771 100644
--- a/runtime/vm/pages.h
+++ b/runtime/vm/pages.h
@@ -23,6 +23,7 @@
class Heap;
class JSONObject;
class ObjectPointerVisitor;
+class ObjectSet;
// A page containing old generation objects.
class HeapPage {
@@ -269,7 +270,7 @@
// Collect the garbage in the page space using mark-sweep.
void MarkSweep(bool invoke_api_callbacks);
- void StartEndAddress(uword* start, uword* end) const;
+ void AddRegionsToObjectSet(ObjectSet* set) const;
void InitGrowthControl() {
page_space_controller_.set_last_usage(usage_);
diff --git a/runtime/vm/parser.cc b/runtime/vm/parser.cc
index 7c5eefc..2906378 100644
--- a/runtime/vm/parser.cc
+++ b/runtime/vm/parser.cc
@@ -2032,22 +2032,27 @@
if (!IsIdentifier()) {
ReportError("parameter name or type expected");
}
- // We have not seen a parameter type yet, so we check if the next
- // identifier could represent a type before parsing it.
- Token::Kind follower = LookaheadToken(1);
- // We have an identifier followed by a 'follower' token.
- // We either parse a type or assume that no type is specified.
- if ((follower == Token::kLT) || // Parameterized type.
- (follower == Token::kPERIOD) || // Qualified class name of type.
- Token::IsIdentifier(follower) || // Parameter name following a type.
- (follower == Token::kTHIS)) { // Field parameter following a type.
+
+ // Lookahead to determine whether the next tokens are a return type
+ // followed by a parameter name.
+ bool found_type = false;
+ {
+ TokenPosScope saved_pos(this);
+ if (TryParseReturnType()) {
+ if (IsIdentifier() || (CurrentToken() == Token::kTHIS)) {
+ found_type = true;
+ }
+ }
+ }
+ if (found_type) {
// The types of formal parameters are never ignored, even in unchecked
// mode, because they are part of the function type of closurized
// functions appearing in type tests with typedefs.
parameter.has_explicit_type = true;
+ // It is too early to resolve the type here, since it can be a result type
+ // referring to a not yet declared function type parameter.
parameter.type = &AbstractType::ZoneHandle(Z,
- ParseType(is_top_level_ ? ClassFinalizer::kResolveTypeParameters :
- ClassFinalizer::kCanonicalize));
+ ParseType(ClassFinalizer::kDoNotResolve));
} else {
// If this is an initializing formal, its type will be set to the type of
// the respective field when the constructor is fully parsed.
@@ -2097,21 +2102,31 @@
// metadata finalConstVarOrType? this ‘.’ identifier formalParameterList? ;
if (!var_seen && !final_seen) {
// The parsed parameter type is actually the function result type.
- const AbstractType& result_type =
+ AbstractType& result_type =
AbstractType::Handle(Z, parameter.type->raw());
+ // In top-level and mixin functions, the source may be in a different
+ // script than the script of the current class. However, we never reparse
+ // signature functions (except typedef signature functions), therefore
+ // we do not need to keep the correct script via a patch class. Use the
+ // actual current class as owner of the signature function.
+ const Function& signature_function = Function::Handle(Z,
+ Function::NewSignatureFunction(current_class(),
+ TokenPosition::kNoSource));
+ signature_function.set_parent_function(innermost_function());
+ innermost_function_ = signature_function.raw();
+
// Finish parsing the function type parameter.
if (CurrentToken() == Token::kLT) {
- // TODO(hausner): handle generic function types.
if (!FLAG_generic_method_syntax) {
ReportError("generic function types not supported");
}
- TokenPosition type_param_pos = TokenPos();
- if (!TryParseTypeParameters()) {
- ReportError(type_param_pos, "error in type parameters");
- }
+ ParseTypeParameters(false); // Not parameterizing class, but function.
}
+ // Now that type parameters are declared, the result type can be resolved.
+ ResolveType(ClassFinalizer::kResolveTypeParameters, &result_type);
+
ASSERT(CurrentToken() == Token::kLPAREN);
ParamList func_params;
@@ -2124,16 +2139,13 @@
const bool no_explicit_default_values = false;
ParseFormalParameterList(no_explicit_default_values, false, &func_params);
- // In top-level and mixin functions, the source may be in a different
- // script than the script of the current class. However, we never reparse
- // signature functions (except typedef signature functions), therefore
- // we do not need to keep the correct script via a patch class. Use the
- // actual current class as owner of the signature function.
- const Function& signature_function = Function::Handle(Z,
- Function::NewSignatureFunction(current_class(),
- TokenPosition::kNoSource));
signature_function.set_result_type(result_type);
AddFormalParamsToFunction(&func_params, signature_function);
+
+ ASSERT(innermost_function().raw() == signature_function.raw());
+ innermost_function_ = signature_function.parent_function();
+ signature_function.set_data(Object::Handle());
+
Type& signature_type =
Type::ZoneHandle(Z, signature_function.SignatureType());
if (!is_top_level_) {
@@ -2149,6 +2161,18 @@
// The type of the parameter is now the signature type.
parameter.type = &signature_type;
}
+ } else {
+ if (!parameter.type->IsFinalized()) {
+ AbstractType& type = AbstractType::ZoneHandle(Z, parameter.type->raw());
+ ResolveType(ClassFinalizer::kResolveTypeParameters, &type);
+ if (!is_top_level_) {
+ type = ClassFinalizer::FinalizeType(
+ Class::Handle(Z, innermost_function().origin()),
+ type,
+ ClassFinalizer::kCanonicalize);
+ }
+ parameter.type = &type;
+ }
}
if ((CurrentToken() == Token::kASSIGN) || (CurrentToken() == Token::kCOLON)) {
@@ -3393,9 +3417,7 @@
// Parse the formal parameters and code.
SequenceNode* Parser::ParseFunc(const Function& func, bool check_semicolon) {
TRACE_PARSER("ParseFunc");
- Function& saved_innermost_function =
- Function::Handle(Z, innermost_function().raw());
- innermost_function_ = func.raw();
+ ASSERT(innermost_function().raw() == func.raw());
// Save current try index. Try index starts at zero for each function.
intptr_t saved_try_index = last_used_try_index_;
@@ -3407,7 +3429,6 @@
if (func.IsGenerativeConstructor()) {
SequenceNode* statements = ParseConstructor(func);
- innermost_function_ = saved_innermost_function.raw();
last_used_try_index_ = saved_try_index;
return statements;
}
@@ -3643,7 +3664,6 @@
}
EnsureHasReturnStatement(body, end_token_pos);
current_block_->statements->Add(body);
- innermost_function_ = saved_innermost_function.raw();
last_used_try_index_ = saved_try_index;
async_temp_scope_ = saved_async_temp_scope;
return CloseBlock();
@@ -3739,10 +3759,17 @@
// A library prefix with the name exists. Now check whether it is
// shadowed by a local definition.
if (!is_top_level_ &&
- ResolveIdentInLocalScope(TokenPos(), ident, NULL)) {
+ ResolveIdentInLocalScope(TokenPos(), ident, NULL, NULL)) {
return LibraryPrefix::null();
}
- // Check whether the identifier is shadowed by a type parameter.
+ // Check whether the identifier is shadowed by a function type parameter.
+ // TODO(regis): Shortcut this lookup if no generic functions in scope.
+ if (!innermost_function().IsNull() &&
+ (innermost_function().LookupTypeParameter(ident, NULL) !=
+ TypeParameter::null())) {
+ return LibraryPrefix::null();
+ }
+ // Check whether the identifier is shadowed by a class type parameter.
ASSERT(!current_class().IsNull());
if (current_class().LookupTypeParameter(ident) != TypeParameter::null()) {
return LibraryPrefix::null();
@@ -3761,7 +3788,7 @@
ASSERT(CurrentToken() == Token::kLPAREN ||
CurrentToken() == Token::kLT ||
method->IsGetter());
- ASSERT(method->type != NULL);
+ ASSERT(method->type != NULL); // May still be unresolved.
ASSERT(current_member_ == method);
if (method->has_var) {
@@ -3785,9 +3812,21 @@
current_class().set_is_const();
}
+ Function& func = Function::Handle(Z,
+ Function::New(*method->name, // May change.
+ method->kind,
+ method->has_static,
+ method->has_const,
+ method->has_abstract, // May change.
+ method->has_external,
+ method->has_native, // May change.
+ current_class(),
+ method->decl_begin_pos));
+
+ ASSERT(innermost_function().IsNull());
+ innermost_function_ = func.raw();
+
if (CurrentToken() == Token::kLT) {
- // Parse type parameters, but ignore them.
- // TODO(hausner): handle type parameters.
if (!FLAG_generic_method_syntax) {
ReportError("generic type arguments not supported.");
}
@@ -3799,9 +3838,14 @@
ReportError(type_param_pos, "%s cannot be generic",
method->IsGetter() ? "getter" : "setter");
}
- if (!TryParseTypeParameters()) {
- ReportError(type_param_pos, "error in type parameters");
- }
+ ParseTypeParameters(false); // Not parameterizing class, but function.
+ }
+
+ // Now that type parameters are declared, the result type can be resolved.
+ if (!method->type->IsResolved()) {
+ AbstractType& type = AbstractType::ZoneHandle(Z, method->type->raw());
+ ResolveType(ClassFinalizer::kResolveTypeParameters, &type);
+ method->type = &type;
}
// Parse the formal parameters.
@@ -4075,26 +4119,10 @@
method->name->ToCString());
}
- RawFunction::Kind function_kind;
- if (method->IsFactoryOrConstructor()) {
- function_kind = RawFunction::kConstructor;
- } else if (method->IsGetter()) {
- function_kind = RawFunction::kGetterFunction;
- } else if (method->IsSetter()) {
- function_kind = RawFunction::kSetterFunction;
- } else {
- function_kind = RawFunction::kRegularFunction;
- }
- Function& func = Function::Handle(Z,
- Function::New(*method->name,
- function_kind,
- method->has_static,
- method->has_const,
- method->has_abstract,
- method->has_external,
- method->has_native,
- current_class(),
- method->decl_begin_pos));
+ // Update function object.
+ func.set_name(*method->name);
+ func.set_is_abstract(method->has_abstract);
+ func.set_is_native(method->has_native);
func.set_result_type(*method->type);
func.set_end_token_pos(method_end_pos);
func.set_is_redirecting(is_redirecting);
@@ -4127,6 +4155,8 @@
// No need to resolve parameter types yet, or add parameters to local scope.
ASSERT(is_top_level_);
AddFormalParamsToFunction(&method->params, func);
+ ASSERT(innermost_function().raw() == func.raw());
+ innermost_function_ = Function::null();
members->AddFunction(func);
}
@@ -4428,8 +4458,10 @@
}
}
if (found_type) {
+ // It is too early to resolve the type here, since it can be a result type
+ // referring to a not yet declared function type parameter.
member.type = &AbstractType::ZoneHandle(Z,
- ParseType(ClassFinalizer::kResolveTypeParameters));
+ ParseType(ClassFinalizer::kDoNotResolve));
}
}
@@ -4542,6 +4574,7 @@
member.type = &Object::dynamic_type();
}
ASSERT(member.IsFactory() == member.has_factory);
+ // Note that member.type may still be unresolved.
ParseMethodOrConstructor(members, &member);
} else if (CurrentToken() == Token::kSEMICOLON ||
CurrentToken() == Token::kCOMMA ||
@@ -4561,6 +4594,11 @@
} else if (member.type->IsVoidType()) {
ReportError(member.name_pos, "field may not be 'void'");
}
+ if (!member.type->IsResolved()) {
+ AbstractType& type = AbstractType::ZoneHandle(Z, member.type->raw());
+ ResolveType(ClassFinalizer::kResolveTypeParameters, &type);
+ member.type = &type;
+ }
ParseFieldDefinition(members, &member);
} else {
UnexpectedToken();
@@ -4679,7 +4717,7 @@
ASSERT(!cls.IsNull());
ASSERT(cls.functions() == Object::empty_array().raw());
set_current_class(cls);
- ParseTypeParameters(cls);
+ ParseTypeParameters(true); // Parameterizing current class.
if (is_patch) {
// Check that the new type parameters are identical to the original ones.
const TypeArguments& new_type_parameters =
@@ -5143,7 +5181,7 @@
mixin_application.set_is_mixin_app_alias();
library_.AddClass(mixin_application);
set_current_class(mixin_application);
- ParseTypeParameters(mixin_application);
+ ParseTypeParameters(true); // Parameterizing current class.
ExpectToken(Token::kASSIGN);
@@ -5271,14 +5309,12 @@
function_type_alias.set_is_prefinalized();
library_.AddClass(function_type_alias);
set_current_class(function_type_alias);
- // Parse the type parameters of the function type.
- ParseTypeParameters(function_type_alias);
+ // Parse the type parameters of the typedef class.
+ ParseTypeParameters(true); // Parameterizing current class.
// At this point, the type parameters have been parsed, so we can resolve the
// result type.
if (!result_type.IsNull()) {
- ResolveTypeFromClass(function_type_alias,
- ClassFinalizer::kResolveTypeParameters,
- &result_type);
+ ResolveType(ClassFinalizer::kResolveTypeParameters, &result_type);
}
// Parse the formal parameters of the function type.
CheckToken(Token::kLPAREN, "formal parameter list expected");
@@ -5297,6 +5333,8 @@
Function& signature_function =
Function::Handle(Z, Function::NewSignatureFunction(function_type_alias,
alias_name_pos));
+ ASSERT(innermost_function().IsNull());
+ innermost_function_ = signature_function.raw();
// Set the signature function in the function type alias class.
function_type_alias.set_signature_function(signature_function);
@@ -5306,6 +5344,9 @@
signature_function.set_result_type(result_type);
AddFormalParamsToFunction(&func_params, signature_function);
+ ASSERT(innermost_function().raw() == signature_function.raw());
+ innermost_function_ = Function::null();
+
if (FLAG_trace_parser) {
OS::Print("TopLevel parsing function type alias '%s'\n",
String::Handle(Z, signature_function.Signature()).ToCString());
@@ -5405,7 +5446,7 @@
}
-void Parser::ParseTypeParameters(const Class& cls) {
+void Parser::ParseTypeParameters(bool parameterizing_class) {
TRACE_PARSER("ParseTypeParameters");
if (CurrentToken() == Token::kLT) {
GrowableArray<AbstractType*> type_parameters_array(Z, 2);
@@ -5431,21 +5472,25 @@
type_parameter_name.ToCString());
}
}
- if (CurrentToken() == Token::kEXTENDS) {
+ if ((CurrentToken() == Token::kEXTENDS) ||
+ (!parameterizing_class && (CurrentToken() == Token::kSUPER))) {
ConsumeToken();
+ // TODO(regis): Handle 'super' differently than 'extends'.
// A bound may refer to the owner of the type parameter it applies to,
- // i.e. to the class or interface currently being parsed.
- // Postpone resolution in order to avoid resolving the class and its
+ // i.e. to the class or function currently being parsed.
+ // Postpone resolution in order to avoid resolving the owner and its
// type parameters, as they are not fully parsed yet.
type_parameter_bound = ParseType(ClassFinalizer::kDoNotResolve);
} else {
type_parameter_bound = I->object_store()->object_type();
}
- type_parameter = TypeParameter::New(cls,
- index,
- type_parameter_name,
- type_parameter_bound,
- declaration_pos);
+ type_parameter = TypeParameter::New(
+ parameterizing_class ? current_class() : Class::Handle(Z),
+ parameterizing_class ? Function::Handle(Z) : innermost_function(),
+ index,
+ type_parameter_name,
+ type_parameter_bound,
+ declaration_pos);
type_parameters_array.Add(
&AbstractType::ZoneHandle(Z, type_parameter.raw()));
if (FLAG_enable_mirrors && metadata_pos.IsReal()) {
@@ -5460,18 +5505,20 @@
ReportError("right angle bracket expected");
}
const TypeArguments& type_parameters =
- TypeArguments::Handle(Z,
- NewTypeArguments(type_parameters_array));
- cls.set_type_parameters(type_parameters);
+ TypeArguments::Handle(Z, NewTypeArguments(type_parameters_array));
+ if (parameterizing_class) {
+ current_class().set_type_parameters(type_parameters);
+ } else {
+ innermost_function().set_type_parameters(type_parameters);
+ }
// Try to resolve the upper bounds, which will at least resolve the
// referenced type parameters.
const intptr_t num_types = type_parameters.Length();
for (intptr_t i = 0; i < num_types; i++) {
type_parameter ^= type_parameters.TypeAt(i);
type_parameter_bound = type_parameter.bound();
- ResolveTypeFromClass(cls,
- ClassFinalizer::kResolveTypeParameters,
- &type_parameter_bound);
+ ResolveType(ClassFinalizer::kResolveTypeParameters,
+ &type_parameter_bound);
type_parameter.set_bound(type_parameter_bound);
}
}
@@ -5687,7 +5734,6 @@
TRACE_PARSER("ParseTopLevelFunction");
const TokenPosition decl_begin_pos = TokenPos();
AbstractType& result_type = Type::Handle(Z, Type::DynamicType());
- const bool is_static = true;
bool is_external = false;
bool is_patch = false;
if (is_patch_source() && IsPatchAnnotation(metadata_pos)) {
@@ -5703,7 +5749,9 @@
} else {
// Parse optional type.
if (IsFunctionReturnType()) {
- result_type = ParseType(ClassFinalizer::kResolveTypeParameters);
+ // It is too early to resolve the type here, since it can be a result type
+ // referring to a not yet declared function type parameter.
+ result_type = ParseType(ClassFinalizer::kDoNotResolve);
}
}
const TokenPosition name_pos = TokenPos();
@@ -5724,16 +5772,30 @@
// A setter named x= may co-exist with a function named x, thus we do
// not need to check setters.
+ Function& func = Function::Handle(Z,
+ Function::New(func_name,
+ RawFunction::kRegularFunction,
+ /* is_static = */ true,
+ /* is_const = */ false,
+ /* is_abstract = */ false,
+ is_external,
+ /* is_native = */ false, // May change.
+ owner,
+ decl_begin_pos));
+
+ ASSERT(innermost_function().IsNull());
+ innermost_function_ = func.raw();
+
if (CurrentToken() == Token::kLT) {
- // Type parameters of generic function.
- // TODO(hausner): handle type parameters.
if (!FLAG_generic_method_syntax) {
ReportError("generic functions not supported");
}
- TokenPosition type_arg_pos = TokenPos();
- if (!TryParseTypeParameters()) {
- ReportError(type_arg_pos, "error in type parameters");
- }
+ ParseTypeParameters(false); // Not parameterizing class, but function.
+ }
+ // At this point, the type parameters have been parsed, so we can resolve the
+ // result type.
+ if (!result_type.IsNull()) {
+ ResolveType(ClassFinalizer::kResolveTypeParameters, &result_type);
}
CheckToken(Token::kLPAREN);
@@ -5771,19 +5833,10 @@
function_end_pos = TokenPos();
ExpectSemicolon();
is_native = true;
+ func.set_is_native(true);
} else {
ReportError("function block expected");
}
- Function& func = Function::Handle(Z,
- Function::New(func_name,
- RawFunction::kRegularFunction,
- is_static,
- /* is_const = */ false,
- /* is_abstract = */ false,
- is_external,
- is_native,
- owner,
- decl_begin_pos));
func.set_result_type(result_type);
func.set_end_token_pos(function_end_pos);
func.set_modifier(func_modifier);
@@ -5794,6 +5847,8 @@
func.set_native_name(*native_name);
}
AddFormalParamsToFunction(¶ms, func);
+ ASSERT(innermost_function().raw() == func.raw());
+ innermost_function_ = Function::null();
top_level->AddFunction(func);
if (!is_patch) {
library_.AddObject(func, func_name);
@@ -7637,6 +7692,14 @@
}
+void Parser::CaptureFunctionInstantiator() {
+ ASSERT(FunctionLevel() > 0);
+ const String* variable_name = &Symbols::FunctionInstantiatorVar();
+ current_block_->scope->CaptureVariable(
+ current_block_->scope->LookupVariable(*variable_name, true));
+}
+
+
AstNode* Parser::LoadReceiver(TokenPosition token_pos) {
// A nested function may access 'this', referring to the receiver of the
// outermost enclosing function.
@@ -7836,7 +7899,9 @@
ConsumeToken();
result_type = Type::VoidType();
} else if (IsFunctionReturnType()) {
- result_type = ParseType(ClassFinalizer::kCanonicalize);
+ // It is too early to resolve the type here, since it can be a result type
+ // referring to a not yet declared function type parameter.
+ result_type = ParseType(ClassFinalizer::kDoNotResolve);
}
const TokenPosition name_pos = TokenPos();
variable_name = ExpectIdentifier("function name expected");
@@ -7858,19 +7923,6 @@
}
}
- if (CurrentToken() == Token::kLT) {
- if (!FLAG_generic_method_syntax) {
- ReportError("generic functions not supported");
- }
- TokenPosition type_arg_pos = TokenPos();
- // TODO(hausner): handle type parameters of generic function.
- if (!TryParseTypeParameters()) {
- ReportError(type_arg_pos, "error in type parameters");
- }
- }
-
- CheckToken(Token::kLPAREN);
-
// Check whether we have parsed this closure function before, in a previous
// compilation. If so, reuse the function object, else create a new one
// and register it in the current class.
@@ -7896,6 +7948,31 @@
}
}
+ ASSERT(function.parent_function() == innermost_function_.raw());
+ innermost_function_ = function.raw();
+
+ if (CurrentToken() == Token::kLT) {
+ if (!FLAG_generic_method_syntax) {
+ ReportError("generic functions not supported");
+ }
+ if (!found_func) {
+ ParseTypeParameters(false); // Not parameterizing class, but function.
+ } else {
+ TryParseTypeParameters();
+ }
+ }
+
+ if (!found_func && !result_type.IsFinalized()) {
+ // Now that type parameters are declared, the result type can be resolved
+ // and finalized.
+ ResolveType(ClassFinalizer::kResolveTypeParameters, &result_type);
+ result_type = ClassFinalizer::FinalizeType(
+ current_class(), result_type, ClassFinalizer::kCanonicalize);
+ function.set_result_type(result_type);
+ }
+
+ CheckToken(Token::kLPAREN);
+
// The function type needs to be finalized at compile time, since the closure
// may be type checked at run time when assigned to a function variable,
// passed as a function argument, or returned as a function result.
@@ -7943,6 +8020,7 @@
// variables of this function's scope that are referenced by the local
// function (and its inner nested functions) will be marked as captured.
+ ASSERT(AbstractType::Handle(Z, function.result_type()).IsResolved());
statements = Parser::ParseFunc(function, !is_literal);
INC_STAT(thread(), num_functions_parsed, 1);
@@ -8028,6 +8106,9 @@
new(Z) ClosureNode(function_pos, function, NULL,
statements != NULL ? statements->scope() : NULL);
+ ASSERT(innermost_function_.raw() == function.raw());
+ innermost_function_ = function.parent_function();
+
if (function_variable == NULL) {
ASSERT(is_literal);
return closure;
@@ -11795,6 +11876,46 @@
}
+AstNode* Parser::LoadTypeParameter(PrimaryNode* primary) {
+ const TokenPosition primary_pos = primary->token_pos();
+ TypeParameter& type_parameter = TypeParameter::ZoneHandle(Z);
+ type_parameter = TypeParameter::Cast(primary->primary()).raw();
+ if (type_parameter.IsClassTypeParameter()) {
+ if (ParsingStaticMember()) {
+ const String& name = String::Handle(Z, type_parameter.name());
+ ReportError(primary_pos,
+ "cannot access type parameter '%s' "
+ "from static function",
+ name.ToCString());
+ }
+ // TODO(regis): Verify that CaptureInstantiator() was already called
+ // and remove call below.
+ if (FunctionLevel() > 0) {
+ // Make sure that the class instantiator is captured.
+ CaptureInstantiator();
+ }
+ type_parameter ^= ClassFinalizer::FinalizeType(
+ current_class(), type_parameter, ClassFinalizer::kCanonicalize);
+ ASSERT(!type_parameter.IsMalformed());
+ return new(Z) TypeNode(primary_pos, type_parameter);
+ } else {
+ ASSERT(type_parameter.IsFunctionTypeParameter());
+ // TODO(regis): Verify that CaptureFunctionInstantiator() was already
+ // called if necessary.
+ // TODO(regis): Finalize type parameter and return as type node.
+ // For now, throw a type error.
+ Type& malformed_type = Type::ZoneHandle(Z);
+ malformed_type = ClassFinalizer::NewFinalizedMalformedType(
+ Error::Handle(Z), // No previous error.
+ script_,
+ primary_pos,
+ "function type parameter '%s' not yet supported",
+ String::Handle(Z, type_parameter.name()).ToCString());
+ return ThrowTypeError(primary_pos, malformed_type);
+ }
+}
+
+
AstNode* Parser::ParseSelectors(AstNode* primary, bool is_cascade) {
AstNode* left = primary;
while (true) {
@@ -11806,29 +11927,10 @@
ConsumeToken();
if (left->IsPrimaryNode()) {
PrimaryNode* primary_node = left->AsPrimaryNode();
- const TokenPosition primary_pos = primary_node->token_pos();
if (primary_node->primary().IsFunction()) {
left = LoadClosure(primary_node);
} else if (primary_node->primary().IsTypeParameter()) {
- if (ParsingStaticMember()) {
- const String& name = String::Handle(Z,
- TypeParameter::Cast(primary_node->primary()).name());
- ReportError(primary_pos,
- "cannot access type parameter '%s' "
- "from static function",
- name.ToCString());
- }
- if (FunctionLevel() > 0) {
- // Make sure that the instantiator is captured.
- CaptureInstantiator();
- }
- TypeParameter& type_parameter = TypeParameter::ZoneHandle(Z);
- type_parameter ^= ClassFinalizer::FinalizeType(
- current_class(),
- TypeParameter::Cast(primary_node->primary()),
- ClassFinalizer::kCanonicalize);
- ASSERT(!type_parameter.IsMalformed());
- left = new(Z) TypeNode(primary->token_pos(), type_parameter);
+ left = LoadTypeParameter(primary_node);
} else {
// Super field access handled in ParseSuperFieldAccess(),
// super calls handled in ParseSuperCall().
@@ -11846,8 +11948,9 @@
if (!FLAG_generic_method_syntax) {
ReportError("generic type arguments not supported.");
}
- // TODO(hausner): handle type arguments.
- ParseTypeArguments(ClassFinalizer::kIgnore);
+ // TODO(regis): Pass type arguments in generic call.
+ // For now, resolve type arguments and ignore.
+ ParseTypeArguments(ClassFinalizer::kCanonicalize);
}
if (left->IsPrimaryNode() &&
left->AsPrimaryNode()->primary().IsClass()) {
@@ -11915,25 +12018,7 @@
ASSERT(!type.IsMalformed());
array = new(Z) TypeNode(primary_pos, type);
} else if (primary_node->primary().IsTypeParameter()) {
- if (ParsingStaticMember()) {
- const String& name = String::ZoneHandle(Z,
- TypeParameter::Cast(primary_node->primary()).name());
- ReportError(primary_pos,
- "cannot access type parameter '%s' "
- "from static function",
- name.ToCString());
- }
- if (FunctionLevel() > 0) {
- // Make sure that the instantiator is captured.
- CaptureInstantiator();
- }
- TypeParameter& type_parameter = TypeParameter::ZoneHandle(Z);
- type_parameter ^= ClassFinalizer::FinalizeType(
- current_class(),
- TypeParameter::Cast(primary_node->primary()),
- ClassFinalizer::kCanonicalize);
- ASSERT(!type_parameter.IsMalformed());
- array = new(Z) TypeNode(primary_pos, type_parameter);
+ array = LoadTypeParameter(primary_node);
} else {
UNREACHABLE(); // Internal parser error.
}
@@ -11946,8 +12031,9 @@
if (!FLAG_generic_method_syntax) {
ReportError("generic type arguments not supported.");
}
- // TODO(hausner): handle type arguments.
- ParseTypeArguments(ClassFinalizer::kIgnore);
+ // TODO(regis): Pass type arguments in generic call.
+ // For now, resolve type arguments and ignore.
+ ParseTypeArguments(ClassFinalizer::kCanonicalize);
}
if (left->IsPrimaryNode()) {
PrimaryNode* primary_node = left->AsPrimaryNode();
@@ -11990,20 +12076,29 @@
false /* is_conditional */);
}
} else if (primary_node->primary().IsTypeParameter()) {
- const String& name = String::ZoneHandle(Z,
- TypeParameter::Cast(primary_node->primary()).name());
- if (ParsingStaticMember()) {
- // Treat as this.T(), because T is in scope.
- ReportError(primary_pos,
- "cannot access type parameter '%s' "
- "from static function",
- name.ToCString());
+ TypeParameter& type_parameter = TypeParameter::ZoneHandle(Z);
+ type_parameter = TypeParameter::Cast(primary_node->primary()).raw();
+ const String& name = String::ZoneHandle(Z, type_parameter.name());
+ if (type_parameter.IsClassTypeParameter()) {
+ if (ParsingStaticMember()) {
+ // Treat as this.T(), because T is in scope.
+ ReportError(primary_pos,
+ "cannot access type parameter '%s' "
+ "from static function",
+ name.ToCString());
+ } else {
+ // Treat as call to unresolved (instance) method.
+ selector = ParseInstanceCall(LoadReceiver(primary_pos),
+ name,
+ primary_pos,
+ false /* is_conditional */);
+ }
} else {
- // Treat as call to unresolved (instance) method.
- selector = ParseInstanceCall(LoadReceiver(primary_pos),
- name,
- primary_pos,
- false /* is_conditional */);
+ ASSERT(type_parameter.IsFunctionTypeParameter());
+ // TODO(regis): Should we throw a type error instead?
+ ReportError(primary_pos,
+ "illegal use of function type parameter '%s'",
+ name.ToCString());
}
} else if (primary_node->primary().IsClass()) {
const Class& type_class = Class::Cast(primary_node->primary());
@@ -12041,25 +12136,7 @@
ASSERT(!type.IsMalformed());
left = new(Z) TypeNode(primary_pos, type);
} else if (primary_node->primary().IsTypeParameter()) {
- if (ParsingStaticMember()) {
- const String& name = String::ZoneHandle(Z,
- TypeParameter::Cast(primary_node->primary()).name());
- ReportError(primary_pos,
- "cannot access type parameter '%s' "
- "from static function",
- name.ToCString());
- }
- if (FunctionLevel() > 0) {
- // Make sure that the instantiator is captured.
- CaptureInstantiator();
- }
- TypeParameter& type_parameter = TypeParameter::ZoneHandle(Z);
- type_parameter ^= ClassFinalizer::FinalizeType(
- current_class(),
- TypeParameter::Cast(primary_node->primary()),
- ClassFinalizer::kCanonicalize);
- ASSERT(!type_parameter.IsMalformed());
- left = new(Z) TypeNode(primary_pos, type_parameter);
+ left = LoadTypeParameter(primary_node);
} else if (primary_node->IsSuper()) {
// Return "super" to handle unary super operator calls,
// or to report illegal use of "super" otherwise.
@@ -12267,16 +12344,13 @@
}
-// Resolve the given type and its type arguments from the given scope class
-// according to the given type finalization mode.
-// If the given scope class is null, use the current library, but do not try to
-// resolve type parameters.
-// Not all involved type classes may get resolved yet, but at least the type
-// parameters of the given class will get resolved, thereby relieving the class
+// Resolve the given type and its type arguments from the current function and
+// current class according to the given type finalization mode.
+// Not all involved type classes may get resolved yet, but at least type
+// parameters will get resolved, thereby relieving the class
// finalizer from resolving type parameters out of context.
-void Parser::ResolveTypeFromClass(const Class& scope_class,
- ClassFinalizer::FinalizationKind finalization,
- AbstractType* type) {
+void Parser::ResolveType(ClassFinalizer::FinalizationKind finalization,
+ AbstractType* type) {
ASSERT(finalization >= ClassFinalizer::kResolveTypeParameters);
ASSERT(type != NULL);
if (type->IsResolved()) {
@@ -12290,39 +12364,56 @@
String::Handle(Z, unresolved_class.ident());
Class& resolved_type_class = Class::Handle(Z);
if (unresolved_class.library_prefix() == LibraryPrefix::null()) {
- if (!scope_class.IsNull()) {
- // First check if the type is a type parameter of the given scope class.
- const TypeParameter& type_parameter = TypeParameter::Handle(Z,
- scope_class.LookupTypeParameter(unresolved_class_name));
+ // First check if the type is a function type parameter.
+ if (!innermost_function().IsNull()) {
+ // TODO(regis): Shortcut this lookup if no generic functions in scope.
+ TypeParameter& type_parameter = TypeParameter::ZoneHandle(Z,
+ innermost_function().LookupTypeParameter(unresolved_class_name,
+ NULL));
if (!type_parameter.IsNull()) {
- // A type parameter is considered to be a malformed type when
- // referenced by a static member.
- if (ParsingStaticMember()) {
- ASSERT(scope_class.raw() == current_class().raw());
- *type = ClassFinalizer::NewFinalizedMalformedType(
- Error::Handle(Z), // No previous error.
- script_,
- type->token_pos(),
- "type parameter '%s' cannot be referenced "
- "from static member",
- String::Handle(Z, type_parameter.name()).ToCString());
- return;
- }
- // A type parameter cannot be parameterized, so make the type
- // malformed if type arguments have previously been parsed.
- if (type->arguments() != TypeArguments::null()) {
- *type = ClassFinalizer::NewFinalizedMalformedType(
- Error::Handle(Z), // No previous error.
- script_,
- type_parameter.token_pos(),
- "type parameter '%s' cannot be parameterized",
- String::Handle(Z, type_parameter.name()).ToCString());
- return;
- }
- *type = type_parameter.raw();
+ // TODO(regis): Check for absence of type arguments.
+ // For now, return as malformed type.
+ Type& malformed_type = Type::ZoneHandle(Z);
+ malformed_type = ClassFinalizer::NewFinalizedMalformedType(
+ Error::Handle(Z), // No previous error.
+ script_,
+ type->token_pos(),
+ "function type parameter '%s' not yet supported",
+ String::Handle(Z, type_parameter.name()).ToCString());
+ *type = malformed_type.raw();
return;
}
}
+ // Then check if the type is a class type parameter.
+ const TypeParameter& type_parameter = TypeParameter::Handle(Z,
+ current_class().LookupTypeParameter(unresolved_class_name));
+ if (!type_parameter.IsNull()) {
+ // A type parameter is considered to be a malformed type when
+ // referenced by a static member.
+ if (ParsingStaticMember()) {
+ *type = ClassFinalizer::NewFinalizedMalformedType(
+ Error::Handle(Z), // No previous error.
+ script_,
+ type->token_pos(),
+ "type parameter '%s' cannot be referenced "
+ "from static member",
+ String::Handle(Z, type_parameter.name()).ToCString());
+ return;
+ }
+ // A type parameter cannot be parameterized, so make the type
+ // malformed if type arguments have previously been parsed.
+ if (type->arguments() != TypeArguments::null()) {
+ *type = ClassFinalizer::NewFinalizedMalformedType(
+ Error::Handle(Z), // No previous error.
+ script_,
+ type_parameter.token_pos(),
+ "type parameter '%s' cannot be parameterized",
+ String::Handle(Z, type_parameter.name()).ToCString());
+ return;
+ }
+ *type = type_parameter.raw();
+ return;
+ }
// The referenced class may not have been parsed yet. It would be wrong
// to resolve it too early to an imported class of the same name. Only
// resolve the class when a finalized type is requested.
@@ -12358,7 +12449,7 @@
AbstractType& type_argument = AbstractType::Handle(Z);
for (intptr_t i = 0; i < num_arguments; i++) {
type_argument ^= arguments.TypeAt(i);
- ResolveTypeFromClass(scope_class, finalization, &type_argument);
+ ResolveType(finalization, &type_argument);
arguments.SetTypeAt(i, type_argument);
}
}
@@ -12640,7 +12731,8 @@
// If node is non NULL return an AST node corresponding to the identifier.
bool Parser::ResolveIdentInLocalScope(TokenPosition ident_pos,
const String &ident,
- AstNode** node) {
+ AstNode** node,
+ intptr_t* function_level) {
TRACE_PARSER("ResolveIdentInLocalScope");
// First try to find the identifier in the nested local scopes.
LocalVariable* local = LookupLocalScope(ident);
@@ -12651,6 +12743,9 @@
if (node != NULL) {
*node = new(Z) LoadLocalNode(ident_pos, local);
}
+ if (function_level != NULL) {
+ *function_level = local->owner()->function_level();
+ }
return true;
}
@@ -12687,6 +12782,9 @@
*node = GenerateStaticFieldLookup(field, ident_pos);
}
}
+ if (function_level != NULL) {
+ *function_level = 0;
+ }
return true;
}
@@ -12875,15 +12973,43 @@
// First try to find the variable in the local scope (block scope or
// class scope).
AstNode* resolved = NULL;
- ResolveIdentInLocalScope(ident_pos, ident, &resolved);
+ intptr_t resolved_func_level = 0;
+ ResolveIdentInLocalScope(ident_pos, ident, &resolved, &resolved_func_level);
+ if (!innermost_function().IsNull()) {
+ // TODO(regis): Shortcut this lookup if no generic functions in scope.
+ intptr_t type_param_func_level = FunctionLevel();
+ const TypeParameter& type_parameter = TypeParameter::ZoneHandle(Z,
+ innermost_function().LookupTypeParameter(ident,
+ &type_param_func_level));
+ if (!type_parameter.IsNull()) {
+ if ((resolved == NULL) || (resolved_func_level < type_param_func_level)) {
+ // The identifier is a function type parameter, possibly shadowing
+ // 'resolved'.
+ if (type_param_func_level < FunctionLevel()) {
+ // Make sure that the function instantiator is captured.
+ CaptureFunctionInstantiator();
+ }
+ // TODO(regis): Finalize type parameter and return as type node.
+ // For now, return as malformed type.
+ Type& malformed_type = Type::ZoneHandle(Z);
+ malformed_type = ClassFinalizer::NewFinalizedMalformedType(
+ Error::Handle(Z), // No previous error.
+ script_,
+ ident_pos,
+ "function type parameter '%s' not yet supported",
+ ident.ToCString());
+ return new(Z) TypeNode(ident_pos, malformed_type);
+ }
+ }
+ }
if (resolved == NULL) {
- // Check whether the identifier is a type parameter.
+ // Check whether the identifier is a class type parameter.
if (!current_class().IsNull()) {
TypeParameter& type_parameter = TypeParameter::ZoneHandle(Z,
current_class().LookupTypeParameter(ident));
if (!type_parameter.IsNull()) {
if (FunctionLevel() > 0) {
- // Make sure that the instantiator is captured.
+ // Make sure that the class instantiator is captured.
CaptureInstantiator();
}
type_parameter ^= ClassFinalizer::FinalizeType(
@@ -13011,7 +13137,7 @@
// is shadowed by a local declaration.
if (!is_top_level_ &&
(prefix->IsNull()) &&
- ResolveIdentInLocalScope(ident_pos, type_name, NULL)) {
+ ResolveIdentInLocalScope(ident_pos, type_name, NULL, NULL)) {
// The type is malformed. Skip over its type arguments.
ParseTypeArguments(ClassFinalizer::kIgnore);
return ClassFinalizer::NewFinalizedMalformedType(
@@ -13062,7 +13188,7 @@
AbstractType& type = AbstractType::Handle(
Z, Type::New(type_class, type_arguments, ident_pos, Heap::kOld));
if (finalization >= ClassFinalizer::kResolveTypeParameters) {
- ResolveTypeFromClass(current_class(), finalization, &type);
+ ResolveType(finalization, &type);
if (finalization >= ClassFinalizer::kCanonicalize) {
type ^= ClassFinalizer::FinalizeType(current_class(), type, finalization);
}
@@ -14264,7 +14390,30 @@
String& ident = *CurrentLiteral();
ConsumeToken();
if (prefix.IsNull()) {
- if (!ResolveIdentInLocalScope(qual_ident_pos, ident, &primary)) {
+ intptr_t primary_func_level = 0;
+ ResolveIdentInLocalScope(
+ qual_ident_pos, ident, &primary, &primary_func_level);
+ // Check whether the identifier is shadowed by a function type parameter.
+ if (!innermost_function().IsNull()) {
+ // TODO(regis): Shortcut this lookup if no generic functions in scope.
+ intptr_t type_param_func_level = FunctionLevel();
+ TypeParameter& type_param = TypeParameter::ZoneHandle(Z,
+ innermost_function().LookupTypeParameter(ident,
+ &type_param_func_level));
+ if (!type_param.IsNull()) {
+ if ((primary == NULL) ||
+ (primary_func_level < type_param_func_level)) {
+ // The identifier is a function type parameter, possibly shadowing
+ // already resolved 'primary'.
+ if (type_param_func_level < FunctionLevel()) {
+ // Make sure that the function instantiator is captured.
+ CaptureFunctionInstantiator();
+ }
+ return new(Z) PrimaryNode(qual_ident_pos, type_param);
+ }
+ }
+ }
+ if (primary == NULL) {
// Check whether the identifier is a type parameter.
if (!current_class().IsNull()) {
TypeParameter& type_param = TypeParameter::ZoneHandle(Z,
diff --git a/runtime/vm/parser.h b/runtime/vm/parser.h
index 224ae25..9134bb1 100644
--- a/runtime/vm/parser.h
+++ b/runtime/vm/parser.h
@@ -510,9 +510,8 @@
void ParseLibraryImportObsoleteSyntax();
void ParseLibraryIncludeObsoleteSyntax();
- void ResolveTypeFromClass(const Class& cls,
- ClassFinalizer::FinalizationKind finalization,
- AbstractType* type);
+ void ResolveType(ClassFinalizer::FinalizationKind finalization,
+ AbstractType* type);
RawAbstractType* ParseType(ClassFinalizer::FinalizationKind finalization,
bool allow_deferred_type = false,
bool consume_unresolved_prefix = true);
@@ -522,7 +521,7 @@
bool consume_unresolved_prefix,
LibraryPrefix* prefix);
- void ParseTypeParameters(const Class& cls);
+ void ParseTypeParameters(bool parameterizing_class);
RawTypeArguments* ParseTypeArguments(
ClassFinalizer::FinalizationKind finalization);
void ParseMethodOrConstructor(ClassDesc* members, MemberDesc* method);
@@ -661,9 +660,11 @@
LocalVariable* LookupTypeArgumentsParameter(LocalScope* from_scope,
bool test_only);
void CaptureInstantiator();
+ void CaptureFunctionInstantiator();
AstNode* LoadReceiver(TokenPosition token_pos);
AstNode* LoadFieldIfUnresolved(AstNode* node);
AstNode* LoadClosure(PrimaryNode* primary);
+ AstNode* LoadTypeParameter(PrimaryNode* primary);
InstanceGetterNode* CallGetter(TokenPosition token_pos,
AstNode* object,
const String& name);
@@ -826,7 +827,8 @@
bool IsInstantiatorRequired() const;
bool ResolveIdentInLocalScope(TokenPosition ident_pos,
const String &ident,
- AstNode** node);
+ AstNode** node,
+ intptr_t* function_level);
static const bool kResolveLocally = true;
static const bool kResolveIncludingImports = false;
diff --git a/runtime/vm/precompiler.cc b/runtime/vm/precompiler.cc
index 985617c..2981e17d 100644
--- a/runtime/vm/precompiler.cc
+++ b/runtime/vm/precompiler.cc
@@ -389,6 +389,7 @@
I->object_store()->set_completer_class(null_class);
I->object_store()->set_stream_iterator_class(null_class);
I->object_store()->set_symbol_class(null_class);
+ I->object_store()->set_compiletime_error_class(null_class);
}
DropClasses();
DropLibraries();
@@ -396,8 +397,9 @@
BindStaticCalls();
SwitchICCalls();
+ ShareMegamorphicBuckets();
DedupStackmaps();
- DedupStackmapLists();
+ DedupLists();
if (FLAG_dedup_instructions) {
// Reduces binary size but obfuscates profiler results.
@@ -2152,6 +2154,29 @@
}
+void Precompiler::ShareMegamorphicBuckets() {
+ const GrowableObjectArray& table = GrowableObjectArray::Handle(Z,
+ I->object_store()->megamorphic_cache_table());
+ if (table.IsNull()) return;
+ MegamorphicCache& cache = MegamorphicCache::Handle(Z);
+
+ const intptr_t capacity = 1;
+ const Array& buckets = Array::Handle(Z,
+ Array::New(MegamorphicCache::kEntryLength * capacity, Heap::kOld));
+ const Function& handler =
+ Function::Handle(Z, MegamorphicCacheTable::miss_handler(I));
+ MegamorphicCache::SetEntry(buckets, 0,
+ MegamorphicCache::smi_illegal_cid(), handler);
+
+ for (intptr_t i = 0; i < table.Length(); i++) {
+ cache ^= table.At(i);
+ cache.set_buckets(buckets);
+ cache.set_mask(capacity - 1);
+ cache.set_filled_entry_count(0);
+ }
+}
+
+
void Precompiler::DedupStackmaps() {
class DedupStackmapsVisitor : public FunctionVisitor {
public:
@@ -2202,50 +2227,73 @@
}
-void Precompiler::DedupStackmapLists() {
- class DedupStackmapListsVisitor : public FunctionVisitor {
+void Precompiler::DedupLists() {
+ class DedupListsVisitor : public FunctionVisitor {
public:
- explicit DedupStackmapListsVisitor(Zone* zone) :
+ explicit DedupListsVisitor(Zone* zone) :
zone_(zone),
- canonical_stackmap_lists_(),
+ canonical_lists_(),
code_(Code::Handle(zone)),
- stackmaps_(Array::Handle(zone)),
- stackmap_(Stackmap::Handle(zone)) {
+ list_(Array::Handle(zone)) {
}
void Visit(const Function& function) {
- if (!function.HasCode()) {
- return;
- }
code_ = function.CurrentCode();
- stackmaps_ = code_.stackmaps();
- if (stackmaps_.IsNull()) return;
+ if (!code_.IsNull()) {
+ list_ = code_.stackmaps();
+ if (!list_.IsNull()) {
+ list_ = DedupList(list_);
+ code_.set_stackmaps(list_);
+ }
+ }
- stackmaps_ = DedupStackmapList(stackmaps_);
- code_.set_stackmaps(stackmaps_);
+ list_ = function.parameter_types();
+ if (!list_.IsNull()) {
+ if (!function.IsSignatureFunction() &&
+ !function.IsClosureFunction() &&
+ (function.name() != Symbols::Call().raw()) &&
+ !list_.InVMHeap()) {
+ // Parameter types not needed for function type tests.
+ for (intptr_t i = 0; i < list_.Length(); i++) {
+ list_.SetAt(i, Object::dynamic_type());
+ }
+ }
+ list_ = DedupList(list_);
+ function.set_parameter_types(list_);
+ }
+
+ list_ = function.parameter_names();
+ if (!list_.IsNull()) {
+ if (!function.HasOptionalNamedParameters() &&
+ !list_.InVMHeap()) {
+ // Parameter names not needed for resolution.
+ for (intptr_t i = 0; i < list_.Length(); i++) {
+ list_.SetAt(i, Symbols::OptimizedOut());
+ }
+ }
+ list_ = DedupList(list_);
+ function.set_parameter_names(list_);
+ }
}
- RawArray* DedupStackmapList(const Array& stackmaps) {
- const Array* canonical_stackmap_list =
- canonical_stackmap_lists_.LookupValue(&stackmaps);
- if (canonical_stackmap_list == NULL) {
- canonical_stackmap_lists_.Insert(
- &Array::ZoneHandle(zone_, stackmaps.raw()));
- return stackmaps.raw();
+ RawArray* DedupList(const Array& list) {
+ const Array* canonical_list = canonical_lists_.LookupValue(&list);
+ if (canonical_list == NULL) {
+ canonical_lists_.Insert(&Array::ZoneHandle(zone_, list.raw()));
+ return list.raw();
} else {
- return canonical_stackmap_list->raw();
+ return canonical_list->raw();
}
}
private:
Zone* zone_;
- ArraySet canonical_stackmap_lists_;
+ ArraySet canonical_lists_;
Code& code_;
- Array& stackmaps_;
- Stackmap& stackmap_;
+ Array& list_;
};
- DedupStackmapListsVisitor visitor(Z);
+ DedupListsVisitor visitor(Z);
VisitFunctions(&visitor);
}
diff --git a/runtime/vm/precompiler.h b/runtime/vm/precompiler.h
index 774dbd5..67c54e1 100644
--- a/runtime/vm/precompiler.h
+++ b/runtime/vm/precompiler.h
@@ -382,8 +382,9 @@
void BindStaticCalls();
void SwitchICCalls();
+ void ShareMegamorphicBuckets();
void DedupStackmaps();
- void DedupStackmapLists();
+ void DedupLists();
void DedupInstructions();
void ResetPrecompilerState();
diff --git a/runtime/vm/raw_object.cc b/runtime/vm/raw_object.cc
index 2c2650f..991b2e0 100644
--- a/runtime/vm/raw_object.cc
+++ b/runtime/vm/raw_object.cc
@@ -442,6 +442,9 @@
visitor->VisitPointers(raw_obj->from(), raw_obj->to());
return Function::InstanceSize();
}
+#if defined(DART_PRECOMPILED_RUNTIME)
+ UNREACHABLE();
+#else
visitor->VisitPointers(raw_obj->from(), raw_obj->to_no_code());
if (ShouldVisitCode(raw_obj->ptr()->code_)) {
@@ -457,6 +460,7 @@
} else {
visitor->add_skipped_code_function(raw_obj);
}
+#endif
return Function::InstanceSize();
}
diff --git a/runtime/vm/raw_object.h b/runtime/vm/raw_object.h
index e249fde..9e40136 100644
--- a/runtime/vm/raw_object.h
+++ b/runtime/vm/raw_object.h
@@ -832,6 +832,8 @@
static bool ShouldVisitCode(RawCode* raw_code);
static bool CheckUsageCounter(RawFunction* raw_fun);
+ uword entry_point_; // Accessed from generated code.
+
RawObject** from() { return reinterpret_cast<RawObject**>(&ptr()->name_); }
RawString* name_;
RawObject* owner_; // Class or patch class or mixin class
@@ -839,6 +841,7 @@
RawAbstractType* result_type_;
RawArray* parameter_types_;
RawArray* parameter_names_;
+ RawTypeArguments* type_parameters_; // Array of TypeParameter.
RawObject* data_; // Additional data specific to the function kind.
RawObject** to_snapshot() {
return reinterpret_cast<RawObject**>(&ptr()->data_);
@@ -847,23 +850,28 @@
RawObject** to_no_code() {
return reinterpret_cast<RawObject**>(&ptr()->ic_data_array_);
}
- RawCode* code_; // Currently active code.
- RawCode* unoptimized_code_; // Unoptimized code, keep it after optimization.
+ RawCode* code_; // Currently active code. Accessed from generated code.
+ NOT_IN_PRECOMPILED(RawCode* unoptimized_code_); // Unoptimized code, keep it
+ // after optimization.
RawObject** to() {
+#if defined(DART_PRECOMPILED_RUNTIME)
+ return reinterpret_cast<RawObject**>(&ptr()->code_);
+#else
return reinterpret_cast<RawObject**>(&ptr()->unoptimized_code_);
+#endif
}
- uword entry_point_;
- TokenPosition token_pos_;
- TokenPosition end_token_pos_;
- int32_t usage_counter_; // Incremented while function is running.
+ NOT_IN_PRECOMPILED(TokenPosition token_pos_);
+ NOT_IN_PRECOMPILED(TokenPosition end_token_pos_);
+ NOT_IN_PRECOMPILED(int32_t usage_counter_); // Accessed from generated code
+ // (JIT only).
+ uint32_t kind_tag_; // See Function::KindTagBits.
int16_t num_fixed_parameters_;
int16_t num_optional_parameters_; // > 0: positional; < 0: named.
- int8_t deoptimization_counter_;
- int8_t was_compiled_;
- uint32_t kind_tag_; // See Function::KindTagBits.
- uint16_t optimized_instruction_count_;
- uint16_t optimized_call_site_count_;
+ NOT_IN_PRECOMPILED(uint16_t optimized_instruction_count_);
+ NOT_IN_PRECOMPILED(uint16_t optimized_call_site_count_);
+ NOT_IN_PRECOMPILED(int8_t deoptimization_counter_);
+ NOT_IN_PRECOMPILED(int8_t was_compiled_);
};
@@ -1113,15 +1121,14 @@
RAW_HEAP_OBJECT_IMPLEMENTATION(Code);
- uword entry_point_;
- uword checked_entry_point_;
+ uword entry_point_; // Accessed from generated code.
+ uword checked_entry_point_; // Accessed from generated code (AOT only).
RawObject** from() {
- return reinterpret_cast<RawObject**>(&ptr()->active_instructions_);
+ return reinterpret_cast<RawObject**>(&ptr()->object_pool_);
}
- RawInstructions* active_instructions_;
- RawInstructions* instructions_;
- RawObjectPool* object_pool_;
+ RawObjectPool* object_pool_; // Accessed from generated code.
+ RawInstructions* instructions_; // Accessed from generated code.
// If owner_ is Function::null() the owner is a regular stub.
// If owner_ is a Class the owner is the allocation stub for that class.
// Else, owner_ is a regular Dart Function.
@@ -1129,21 +1136,27 @@
RawExceptionHandlers* exception_handlers_;
RawPcDescriptors* pc_descriptors_;
RawArray* stackmaps_;
- RawArray* deopt_info_array_;
- RawArray* static_calls_target_table_; // (code-offset, function, code).
- RawLocalVarDescriptors* var_descriptors_;
- RawArray* inlined_metadata_;
- RawCodeSourceMap* code_source_map_;
- RawArray* comments_;
+ NOT_IN_PRECOMPILED(RawInstructions* active_instructions_);
+ NOT_IN_PRECOMPILED(RawArray* deopt_info_array_);
+ // (code-offset, function, code) triples.
+ NOT_IN_PRECOMPILED(RawArray* static_calls_target_table_);
+ NOT_IN_PRECOMPILED(RawLocalVarDescriptors* var_descriptors_);
+ NOT_IN_PRECOMPILED(RawArray* inlined_metadata_);
+ NOT_IN_PRECOMPILED(RawCodeSourceMap* code_source_map_);
+ NOT_IN_PRECOMPILED(RawArray* comments_);
// If return_address_metadata_ is a Smi, it is the offset to the prologue.
// Else, return_address_metadata_ is null.
- RawObject* return_address_metadata_;
+ NOT_IN_PRECOMPILED(RawObject* return_address_metadata_);
RawObject** to() {
+#if defined(DART_PRECOMPILED_RUNTIME)
+ return reinterpret_cast<RawObject**>(&ptr()->stackmaps_);
+#else
return reinterpret_cast<RawObject**>(&ptr()->return_address_metadata_);
+#endif
}
// Compilation timestamp.
- int64_t compile_timestamp_;
+ NOT_IN_PRECOMPILED(int64_t compile_timestamp_);
// state_bits_ is a bitfield with three fields:
// The optimized bit, the alive bit, and a count of the number of pointer
@@ -1152,7 +1165,7 @@
int32_t state_bits_;
// PC offsets for code patching.
- int32_t lazy_deopt_pc_offset_;
+ NOT_IN_PRECOMPILED(int32_t lazy_deopt_pc_offset_);
// Variable length data follows here.
int32_t* data() { OPEN_ARRAY_START(int32_t, int32_t); }
@@ -1525,7 +1538,7 @@
UNREACHABLE();
return NULL;
}
- int32_t deopt_id_; // Deoptimization id corresponding to this IC.
+ NOT_IN_PRECOMPILED(int32_t deopt_id_);
uint32_t state_bits_; // Number of arguments tested in IC, deopt reasons.
#if defined(TAG_IC_DATA)
intptr_t tag_; // Debugging, verifying that the icdata is assigned to the
@@ -1591,7 +1604,7 @@
}
TokenPosition token_pos_; // Source position in script_.
bool report_after_token_; // Report message at or after the token.
- int8_t kind_; // Of type LanguageError::Kind.
+ int8_t kind_; // Of type Report::Kind.
};
@@ -1735,10 +1748,14 @@
RawString* name_;
RawSmi* hash_;
RawAbstractType* bound_; // ObjectType if no explicit bound specified.
- RawObject** to() { return reinterpret_cast<RawObject**>(&ptr()->bound_); }
+ RawFunction* parameterized_function_;
+ RawObject** to() {
+ return reinterpret_cast<RawObject**>(&ptr()->parameterized_function_);
+ }
classid_t parameterized_class_id_;
TokenPosition token_pos_;
int16_t index_;
+ uint8_t parent_level_; // Max 255 levels of nested generic functions is OK.
int8_t type_state_;
friend class CidRewriteVisitor;
diff --git a/runtime/vm/raw_object_snapshot.cc b/runtime/vm/raw_object_snapshot.cc
index 39d377a..02ba160 100644
--- a/runtime/vm/raw_object_snapshot.cc
+++ b/runtime/vm/raw_object_snapshot.cc
@@ -764,11 +764,14 @@
bool is_optimized = Code::IsOptimized(ptr()->code_);
// Write out all the non object fields.
+#if !defined(DART_PRECOMPILED_RUNTIME)
writer->Write<int32_t>(ptr()->token_pos_.SnapshotEncode());
writer->Write<int32_t>(ptr()->end_token_pos_.SnapshotEncode());
+#endif
writer->Write<int16_t>(ptr()->num_fixed_parameters_);
writer->Write<int16_t>(ptr()->num_optional_parameters_);
writer->Write<uint32_t>(ptr()->kind_tag_);
+#if !defined(DART_PRECOMPILED_RUNTIME)
if (is_optimized) {
writer->Write<int32_t>(FLAG_optimization_counter_threshold);
} else {
@@ -777,6 +780,7 @@
writer->Write<int8_t>(ptr()->deoptimization_counter_);
writer->Write<uint16_t>(ptr()->optimized_instruction_count_);
writer->Write<uint16_t>(ptr()->optimized_call_site_count_);
+#endif
// Write out all the object pointer fields.
SnapshotWriterVisitor visitor(writer, kAsReference);
@@ -1542,7 +1546,7 @@
ICData& result = ICData::ZoneHandle(reader->zone(), ICData::New());
reader->AddBackRef(object_id, &result, kIsDeserialized);
- result.set_deopt_id(reader->Read<int32_t>());
+ NOT_IN_PRECOMPILED(result.set_deopt_id(reader->Read<int32_t>()));
result.set_state_bits(reader->Read<uint32_t>());
#if defined(TAG_IC_DATA)
result.set_tag(reader->Read<int16_t>());
@@ -1572,7 +1576,7 @@
writer->WriteTags(writer->GetObjectTags(this));
// Write out all the non object fields.
- writer->Write<int32_t>(ptr()->deopt_id_);
+ NOT_IN_PRECOMPILED(writer->Write<int32_t>(ptr()->deopt_id_));
writer->Write<uint32_t>(ptr()->state_bits_);
#if defined(TAG_IC_DATA)
writer->Write<int16_t>(ptr()->tag_);
diff --git a/runtime/vm/scavenger.cc b/runtime/vm/scavenger.cc
index cb028ce..fe366b0 100644
--- a/runtime/vm/scavenger.cc
+++ b/runtime/vm/scavenger.cc
@@ -9,6 +9,7 @@
#include "vm/isolate.h"
#include "vm/lockers.h"
#include "vm/object.h"
+#include "vm/object_set.h"
#include "vm/object_id_ring.h"
#include "vm/safepoint.h"
#include "vm/stack_frame.h"
@@ -745,6 +746,11 @@
}
+void Scavenger::AddRegionsToObjectSet(ObjectSet* set) const {
+ set->AddRegion(to_->start(), to_->end());
+}
+
+
RawObject* Scavenger::FindObject(FindObjectVisitor* visitor) const {
ASSERT(!scavenging_);
uword cur = FirstObjectStart();
diff --git a/runtime/vm/scavenger.h b/runtime/vm/scavenger.h
index 8fce1a4..798470c 100644
--- a/runtime/vm/scavenger.h
+++ b/runtime/vm/scavenger.h
@@ -22,6 +22,7 @@
class Heap;
class Isolate;
class JSONObject;
+class ObjectSet;
class ScavengerVisitor;
// Wrapper around VirtualMemory that adds caching and handles the empty case.
@@ -181,10 +182,7 @@
void VisitObjects(ObjectVisitor* visitor) const;
void VisitObjectPointers(ObjectPointerVisitor* visitor) const;
- void StartEndAddress(uword* start, uword* end) const {
- *start = to_->start();
- *end = to_->end();
- }
+ void AddRegionsToObjectSet(ObjectSet* set) const;
void WriteProtect(bool read_only);
diff --git a/runtime/vm/service_test.cc b/runtime/vm/service_test.cc
index ee534ef..378b65b 100644
--- a/runtime/vm/service_test.cc
+++ b/runtime/vm/service_test.cc
@@ -168,6 +168,7 @@
// Set the sticky error.
Dart_SetStickyError(result);
+ Dart_SetPausedOnExit(true);
EXPECT(Dart_HasStickyError());
{
diff --git a/runtime/vm/simulator_dbc.cc b/runtime/vm/simulator_dbc.cc
index e02cec3..67c1728 100644
--- a/runtime/vm/simulator_dbc.cc
+++ b/runtime/vm/simulator_dbc.cc
@@ -251,7 +251,7 @@
}
DART_FORCE_INLINE static uint8_t* GetTypedData(
- RawObject* obj, RawObject* index, intptr_t scale) {
+ RawObject* obj, RawObject* index) {
ASSERT(RawObject::IsTypedDataClassId(obj->GetClassId()));
RawTypedData* array = reinterpret_cast<RawTypedData*>(obj);
const intptr_t byte_offset = Smi::Value(RAW_CAST(Smi, index));
@@ -1969,8 +1969,67 @@
}
{
+ BYTECODE(DTruncate, A_D);
+ const double value = bit_cast<double, RawObject*>(FP[rD]);
+ FP[rA] = bit_cast<RawObject*, double>(trunc(value));
+ DISPATCH();
+ }
+
+ {
+ BYTECODE(DFloor, A_D);
+ const double value = bit_cast<double, RawObject*>(FP[rD]);
+ FP[rA] = bit_cast<RawObject*, double>(floor(value));
+ DISPATCH();
+ }
+
+ {
+ BYTECODE(DCeil, A_D);
+ const double value = bit_cast<double, RawObject*>(FP[rD]);
+ FP[rA] = bit_cast<RawObject*, double>(ceil(value));
+ DISPATCH();
+ }
+
+ {
+ BYTECODE(DoubleToFloat, A_D);
+ const double value = bit_cast<double, RawObject*>(FP[rD]);
+ const float valuef = static_cast<float>(value);
+ *reinterpret_cast<float*>(&FP[rA]) = valuef;
+ DISPATCH();
+ }
+
+ {
+ BYTECODE(FloatToDouble, A_D);
+ const float valuef = *reinterpret_cast<float*>(&FP[rD]);
+ const double value = static_cast<double>(valuef);
+ FP[rA] = bit_cast<RawObject*, double>(value);
+ DISPATCH();
+ }
+
+ {
+ BYTECODE(LoadIndexedFloat32, A_B_C);
+ uint8_t* data = SimulatorHelpers::GetTypedData(FP[rB], FP[rC]);
+ const uint32_t value = *reinterpret_cast<uint32_t*>(data);
+ const uint64_t value64 = value;
+ FP[rA] = reinterpret_cast<RawObject*>(value64);
+ DISPATCH();
+ }
+
+ {
+ BYTECODE(LoadIndexed4Float32, A_B_C);
+ ASSERT(RawObject::IsTypedDataClassId(FP[rB]->GetClassId()));
+ RawTypedData* array = reinterpret_cast<RawTypedData*>(FP[rB]);
+ RawSmi* index = RAW_CAST(Smi, FP[rC]);
+ ASSERT(SimulatorHelpers::CheckIndex(index, array->ptr()->length_));
+ const uint32_t value =
+ reinterpret_cast<uint32_t*>(array->ptr()->data())[Smi::Value(index)];
+ const uint64_t value64 = value; // sign extend to clear high bits.
+ FP[rA] = reinterpret_cast<RawObject*>(value64);
+ DISPATCH();
+ }
+
+ {
BYTECODE(LoadIndexedFloat64, A_B_C);
- uint8_t* data = SimulatorHelpers::GetTypedData(FP[rB], FP[rC], 3);
+ uint8_t* data = SimulatorHelpers::GetTypedData(FP[rB], FP[rC]);
*reinterpret_cast<uint64_t*>(&FP[rA]) = *reinterpret_cast<uint64_t*>(data);
DISPATCH();
}
@@ -1988,8 +2047,30 @@
}
{
+ BYTECODE(StoreIndexedFloat32, A_B_C);
+ uint8_t* data = SimulatorHelpers::GetTypedData(FP[rA], FP[rB]);
+ const uint64_t value = reinterpret_cast<uint64_t>(FP[rC]);
+ const uint32_t value32 = value;
+ *reinterpret_cast<uint32_t*>(data) = value32;
+ DISPATCH();
+ }
+
+ {
+ BYTECODE(StoreIndexed4Float32, A_B_C);
+ ASSERT(RawObject::IsTypedDataClassId(FP[rA]->GetClassId()));
+ RawTypedData* array = reinterpret_cast<RawTypedData*>(FP[rA]);
+ RawSmi* index = RAW_CAST(Smi, FP[rB]);
+ ASSERT(SimulatorHelpers::CheckIndex(index, array->ptr()->length_));
+ const uint64_t value = reinterpret_cast<uint64_t>(FP[rC]);
+ const uint32_t value32 = value;
+ reinterpret_cast<uint32_t*>(array->ptr()->data())[Smi::Value(index)] =
+ value32;
+ DISPATCH();
+ }
+
+ {
BYTECODE(StoreIndexedFloat64, A_B_C);
- uint8_t* data = SimulatorHelpers::GetTypedData(FP[rA], FP[rB], 3);
+ uint8_t* data = SimulatorHelpers::GetTypedData(FP[rA], FP[rB]);
*reinterpret_cast<uint64_t*>(data) = reinterpret_cast<uint64_t>(FP[rC]);
DISPATCH();
}
@@ -2126,6 +2207,48 @@
}
{
+ BYTECODE(DTruncate, A_D);
+ UNREACHABLE();
+ DISPATCH();
+ }
+
+ {
+ BYTECODE(DFloor, A_D);
+ UNREACHABLE();
+ DISPATCH();
+ }
+
+ {
+ BYTECODE(DCeil, A_D);
+ UNREACHABLE();
+ DISPATCH();
+ }
+
+ {
+ BYTECODE(DoubleToFloat, A_D);
+ UNREACHABLE();
+ DISPATCH();
+ }
+
+ {
+ BYTECODE(FloatToDouble, A_D);
+ UNREACHABLE();
+ DISPATCH();
+ }
+
+ {
+ BYTECODE(LoadIndexedFloat32, A_B_C);
+ UNREACHABLE();
+ DISPATCH();
+ }
+
+ {
+ BYTECODE(LoadIndexed4Float32, A_B_C);
+ UNREACHABLE();
+ DISPATCH();
+ }
+
+ {
BYTECODE(LoadIndexedFloat64, A_B_C);
UNREACHABLE();
DISPATCH();
@@ -2138,6 +2261,18 @@
}
{
+ BYTECODE(StoreIndexedFloat32, A_B_C);
+ UNREACHABLE();
+ DISPATCH();
+ }
+
+ {
+ BYTECODE(StoreIndexed4Float32, A_B_C);
+ UNREACHABLE();
+ DISPATCH();
+ }
+
+ {
BYTECODE(StoreIndexedFloat64, A_B_C);
UNREACHABLE();
DISPATCH();
@@ -2297,6 +2432,25 @@
// TODO(vegorov) allocation bytecodes can benefit from the new-space
// allocation fast-path that does not transition into the runtime system.
{
+ BYTECODE(AllocateUninitializedContext, A_D);
+ const uint16_t num_context_variables = rD;
+ const intptr_t instance_size = Context::InstanceSize(num_context_variables);
+ const uword start =
+ thread->heap()->new_space()->TryAllocate(instance_size);
+ if (LIKELY(start != 0)) {
+ uword tags = 0;
+ tags = RawObject::ClassIdTag::update(kContextCid, tags);
+ tags = RawObject::SizeTag::update(instance_size, tags);
+ *reinterpret_cast<uword*>(start + Array::tags_offset()) = tags;
+ *reinterpret_cast<uword*>(start + Context::num_variables_offset()) =
+ num_context_variables;
+ FP[rA] = reinterpret_cast<RawObject*>(start + kHeapObjectTag);
+ pc += 2;
+ }
+ DISPATCH();
+ }
+
+ {
BYTECODE(AllocateContext, A_D);
const uint16_t num_context_variables = rD;
{
@@ -2352,6 +2506,28 @@
}
{
+ BYTECODE(AllocateTOpt, A_D);
+ const uword tags = Smi::Value(RAW_CAST(Smi, LOAD_CONSTANT(rD)));
+ const intptr_t instance_size = RawObject::SizeTag::decode(tags);
+ const uword start = thread->heap()->new_space()->TryAllocate(instance_size);
+ if (LIKELY(start != 0)) {
+ RawObject* type_args = SP[0];
+ const intptr_t type_args_offset = Bytecode::DecodeD(*pc);
+ *reinterpret_cast<uword*>(start + Instance::tags_offset()) = tags;
+ *reinterpret_cast<RawObject**>(start + type_args_offset) = type_args;
+ for (intptr_t current_offset = sizeof(RawInstance);
+ current_offset < instance_size;
+ current_offset += kWordSize) {
+ *reinterpret_cast<RawObject**>(start + current_offset) = null_value;
+ }
+ FP[rA] = reinterpret_cast<RawObject*>(start + kHeapObjectTag);
+ SP -= 1; // Consume the type arguments on the stack.
+ pc += 4;
+ }
+ DISPATCH();
+ }
+
+ {
BYTECODE(AllocateT, 0);
SP[1] = SP[-0]; // Class object.
SP[2] = SP[-1]; // Type arguments
@@ -3002,7 +3178,7 @@
{
BYTECODE(StoreIndexedUint8, A_B_C);
- uint8_t* data = SimulatorHelpers::GetTypedData(FP[rA], FP[rB], 0);
+ uint8_t* data = SimulatorHelpers::GetTypedData(FP[rA], FP[rB]);
*data = Smi::Value(RAW_CAST(Smi, FP[rC]));
DISPATCH();
}
@@ -3028,7 +3204,7 @@
{
BYTECODE(StoreIndexedUint32, A_B_C);
- uint8_t* data = SimulatorHelpers::GetTypedData(FP[rA], FP[rB], 2);
+ uint8_t* data = SimulatorHelpers::GetTypedData(FP[rA], FP[rB]);
const uintptr_t value = reinterpret_cast<uintptr_t>(FP[rC]);
*reinterpret_cast<uint32_t*>(data) = static_cast<uint32_t>(value);
DISPATCH();
@@ -3047,28 +3223,28 @@
{
BYTECODE(LoadIndexedUint8, A_B_C);
- uint8_t* data = SimulatorHelpers::GetTypedData(FP[rB], FP[rC], 0);
+ uint8_t* data = SimulatorHelpers::GetTypedData(FP[rB], FP[rC]);
FP[rA] = Smi::New(*data);
DISPATCH();
}
{
BYTECODE(LoadIndexedInt8, A_B_C);
- uint8_t* data = SimulatorHelpers::GetTypedData(FP[rB], FP[rC], 0);
+ uint8_t* data = SimulatorHelpers::GetTypedData(FP[rB], FP[rC]);
FP[rA] = Smi::New(*reinterpret_cast<int8_t*>(data));
DISPATCH();
}
{
BYTECODE(LoadIndexedUint32, A_B_C);
- uint8_t* data = SimulatorHelpers::GetTypedData(FP[rB], FP[rC], 2);
+ uint8_t* data = SimulatorHelpers::GetTypedData(FP[rB], FP[rC]);
FP[rA] = reinterpret_cast<RawObject*>(*reinterpret_cast<uintptr_t*>(data));
DISPATCH();
}
{
BYTECODE(LoadIndexedInt32, A_B_C);
- uint8_t* data = SimulatorHelpers::GetTypedData(FP[rB], FP[rC], 2);
+ uint8_t* data = SimulatorHelpers::GetTypedData(FP[rB], FP[rC]);
FP[rA] = reinterpret_cast<RawObject*>(*reinterpret_cast<intptr_t*>(data));
DISPATCH();
}
diff --git a/runtime/vm/symbols.h b/runtime/vm/symbols.h
index 9aa510c..8730c9e 100644
--- a/runtime/vm/symbols.h
+++ b/runtime/vm/symbols.h
@@ -62,6 +62,7 @@
V(ImplicitClosure, "<implicit closure>") \
V(ClosureParameter, ":closure") \
V(TypeArgumentsParameter, ":type_arguments") \
+ V(FunctionInstantiatorVar, ":function_instantiator_var") \
V(AssertionError, "_AssertionError") \
V(CastError, "_CastError") \
V(TypeError, "_TypeError") \
@@ -69,6 +70,7 @@
V(AbstractClassInstantiationError, "AbstractClassInstantiationError") \
V(NoSuchMethodError, "NoSuchMethodError") \
V(CyclicInitializationError, "CyclicInitializationError") \
+ V(_CompileTimeError, "_CompileTimeError") \
V(ThrowNew, "_throwNew") \
V(ThrowNewIfNotLoaded, "_throwNewIfNotLoaded") \
V(CheckAssertion, "_checkAssertion") \
diff --git a/runtime/vm/verifier.cc b/runtime/vm/verifier.cc
index de125bf..a2ce0c3 100644
--- a/runtime/vm/verifier.cc
+++ b/runtime/vm/verifier.cc
@@ -69,9 +69,12 @@
void VerifyPointersVisitor::VerifyPointers(MarkExpectation mark_expectation) {
NoSafepointScope no_safepoint;
- Isolate* isolate = Isolate::Current();
+ Thread* thread = Thread::Current();
+ Isolate* isolate = thread->isolate();
+ StackZone stack_zone(thread);
ObjectSet* allocated_set =
- isolate->heap()->CreateAllocatedObjectSet(mark_expectation);
+ isolate->heap()->CreateAllocatedObjectSet(stack_zone.GetZone(),
+ mark_expectation);
VerifyPointersVisitor visitor(isolate, allocated_set);
// Visit all strongly reachable objects.
isolate->IterateObjectPointers(&visitor,
@@ -79,7 +82,6 @@
VerifyWeakPointersVisitor weak_visitor(&visitor);
// Visit weak handles and prologue weak handles.
isolate->VisitWeakPersistentHandles(&weak_visitor);
- delete allocated_set;
}
diff --git a/sdk/bin/dart2js b/sdk/bin/dart2js
index 248ab07..17559bf 100755
--- a/sdk/bin/dart2js
+++ b/sdk/bin/dart2js
@@ -52,41 +52,4 @@
DART2JS="$DART_ROOT/pkg/compiler/lib/src/dart2js.dart"
-if [[ `uname` == 'Darwin' ]]; then
- OUT_DIR="$DART_ROOT/xcodebuild/"
-else
- OUT_DIR="$DART_ROOT/out/"
-fi
-
-if [ -z "$DART_CONFIGURATION" ];
-then
- DIRS=$( ls "$OUT_DIR" )
- # list of possible configurations in decreasing desirability
- CONFIGS=("ReleaseX64" "ReleaseIA32" "DebugX64" "DebugIA32"
- "ReleaseARM" "ReleaseARM64" "ReleaseARMV5TE" "ReleaseMIPS"
- "DebugARM" "DebugARM64" "DebugARMV5TE" "DebugMIPS")
- DART_CONFIGURATION="None"
- for CONFIG in ${CONFIGS[*]}
- do
- for DIR in $DIRS;
- do
- if [ "$CONFIG" = "$DIR" ];
- then
- # choose most desirable configuration that is available and break
- DART_CONFIGURATION="$DIR"
- break 2
- fi
- done
- done
- if [ "$DART_CONFIGURATION" = "None" ]
- then
- echo "No valid dart configuration found in $OUT_DIR"
- exit 1
- fi
-fi
-
-BUILD_DIR="$OUT_DIR$DART_CONFIGURATION"
-
-PACKAGE_ROOT="$BUILD_DIR/packages/"
-
-exec "$DART" "${EXTRA_VM_OPTIONS[@]}" "--package-root=$PACKAGE_ROOT" "$DART2JS" "${EXTRA_OPTIONS[@]}" "$@"
+exec "$DART" "${EXTRA_VM_OPTIONS[@]}" "$DART2JS" "${EXTRA_OPTIONS[@]}" "$@"
diff --git a/sdk/bin/dart2js.bat b/sdk/bin/dart2js.bat
index 2869680..4c6669a 100644
--- a/sdk/bin/dart2js.bat
+++ b/sdk/bin/dart2js.bat
@@ -39,14 +39,7 @@
set DART2JS=%DART_ROOT%\pkg\compiler\lib\src\dart2js.dart
-rem DART_CONFIGURATION defaults to ReleaseX64
-if "%DART_CONFIGURATION%"=="" set DART_CONFIGURATION=ReleaseX64
-
-set BUILD_DIR=%DART_ROOT%\out\%DART_CONFIGURATION%
-
-set PACKAGE_ROOT=%BUILD_DIR%\packages
-
-"%DART%" %EXTRA_VM_OPTIONS% "--package-root=%PACKAGE_ROOT%" "%DART2JS%" %EXTRA_OPTIONS% %*
+"%DART%" %EXTRA_VM_OPTIONS% "%DART2JS%" %EXTRA_OPTIONS% %*
endlocal
diff --git a/sdk/bin/dartanalyzer b/sdk/bin/dartanalyzer
index 8f2274c..c508c62 100755
--- a/sdk/bin/dartanalyzer
+++ b/sdk/bin/dartanalyzer
@@ -45,42 +45,4 @@
ANALYZER="$DART_ROOT/pkg/analyzer_cli/bin/analyzer.dart"
-if [[ `uname` == 'Darwin' ]];
-then
- OUT_DIR="$DART_ROOT/xcodebuild/"
-else
- OUT_DIR="$DART_ROOT/out/"
-fi
-
-if [ -z "$DART_CONFIGURATION" ];
-then
- DIRS=$( ls "$OUT_DIR" )
- # list of possible configurations in decreasing desirability
- CONFIGS=("ReleaseX64" "ReleaseIA32" "DebugX64" "DebugIA32"
- "ReleaseARM" "ReleaseARM64" "ReleaseARMV5TE" "ReleaseMIPS"
- "DebugARM" "DebugARM64" "DebugARMV5TE" "DebugMIPS")
- DART_CONFIGURATION="None"
- for CONFIG in ${CONFIGS[*]}
- do
- for DIR in $DIRS;
- do
- if [ "$CONFIG" = "$DIR" ];
- then
- # choose most desirable configuration that is available and break
- DART_CONFIGURATION="$DIR"
- break 2
- fi
- done
- done
- if [ "$DART_CONFIGURATION" = "None" ]
- then
- echo "No valid dart configuration found in $OUT_DIR"
- exit 1
- fi
-fi
-
-BUILD_DIR="$OUT_DIR$DART_CONFIGURATION"
-
-PACKAGE_ROOT="$BUILD_DIR/packages/"
-
-exec "$DART" "${EXTRA_VM_OPTIONS[@]}" "--package-root=$PACKAGE_ROOT" "$ANALYZER" "$SDK_ARG" "$@"
+exec "$DART" "${EXTRA_VM_OPTIONS[@]}" "$ANALYZER" "$SDK_ARG" "$@"
diff --git a/sdk/bin/dartanalyzer.bat b/sdk/bin/dartanalyzer.bat
index 8130d98..f03dfbd 100644
--- a/sdk/bin/dartanalyzer.bat
+++ b/sdk/bin/dartanalyzer.bat
@@ -40,14 +40,7 @@
set ANALYZER=%DART_ROOT%\pkg\analyzer_cli\bin\analyzer.dart
-rem DART_CONFIGURATION defaults to ReleaseX64
-if "%DART_CONFIGURATION%"=="" set DART_CONFIGURATION=ReleaseX64
-
-set BUILD_DIR=%DART_ROOT%\out\%DART_CONFIGURATION%
-
-set PACKAGE_ROOT=%BUILD_DIR%\packages
-
-"%DART%" %EXTRA_VM_OPTIONS% "--package-root=%PACKAGE_ROOT%" "%ANALYZER%" "%SDK_ARG%" %*
+"%DART%" %EXTRA_VM_OPTIONS% "%ANALYZER%" "%SDK_ARG%" %*
endlocal
diff --git a/sdk/bin/dartdevc b/sdk/bin/dartdevc
index e285653..246f6b7 100755
--- a/sdk/bin/dartdevc
+++ b/sdk/bin/dartdevc
@@ -45,42 +45,4 @@
DEV_COMPILER="$DART_ROOT/pkg/dev_compiler/bin/dartdevc.dart"
-if [[ `uname` == 'Darwin' ]];
-then
- OUT_DIR="$DART_ROOT/xcodebuild/"
-else
- OUT_DIR="$DART_ROOT/out/"
-fi
-
-if [ -z "$DART_CONFIGURATION" ];
-then
- DIRS=$( ls "$OUT_DIR" )
- # list of possible configurations in decreasing desirability
- CONFIGS=("ReleaseX64" "ReleaseIA32" "DebugX64" "DebugIA32"
- "ReleaseARM" "ReleaseARM64" "ReleaseARMV5TE" "ReleaseMIPS"
- "DebugARM" "DebugARM64" "DebugARMV5TE" "DebugMIPS")
- DART_CONFIGURATION="None"
- for CONFIG in ${CONFIGS[*]}
- do
- for DIR in $DIRS;
- do
- if [ "$CONFIG" = "$DIR" ];
- then
- # choose most desirable configuration that is available and break
- DART_CONFIGURATION="$DIR"
- break 2
- fi
- done
- done
- if [ "$DART_CONFIGURATION" = "None" ]
- then
- echo "No valid dart configuration found in $OUT_DIR"
- exit 1
- fi
-fi
-
-BUILD_DIR="$OUT_DIR$DART_CONFIGURATION"
-
-PACKAGE_ROOT="$BUILD_DIR/packages/"
-
-exec "$DART" "${EXTRA_VM_OPTIONS[@]}" "--package-root=$PACKAGE_ROOT" "$DEV_COMPILER" "$SDK_ARG" "$@"
+exec "$DART" "${EXTRA_VM_OPTIONS[@]}" "$DEV_COMPILER" "$SDK_ARG" "$@"
diff --git a/sdk/bin/dartdevc.bat b/sdk/bin/dartdevc.bat
index f42c660..5c714ca 100644
--- a/sdk/bin/dartdevc.bat
+++ b/sdk/bin/dartdevc.bat
@@ -36,14 +36,7 @@
set DEV_COMPILER=%DART_ROOT%\third_party\pkg\dev_compiler\bin\dartdevc.dart
-rem DART_CONFIGURATION defaults to ReleaseX64
-if "%DART_CONFIGURATION%"=="" set DART_CONFIGURATION=ReleaseX64
-
-set BUILD_DIR=%DART_ROOT%\out\%DART_CONFIGURATION%
-
-set PACKAGE_ROOT=%BUILD_DIR%\packages
-
-"%DART%" %EXTRA_VM_OPTIONS% "--package-root=%PACKAGE_ROOT%" "DEV_COMPILER%" "%SDK_ARG%" %*
+"%DART%" %EXTRA_VM_OPTIONS% "DEV_COMPILER%" "%SDK_ARG%" %*
endlocal
diff --git a/sdk/bin/dartfmt b/sdk/bin/dartfmt
index ded1eac..a671c50 100755
--- a/sdk/bin/dartfmt
+++ b/sdk/bin/dartfmt
@@ -28,17 +28,4 @@
DARTFMT="$DART_ROOT/third_party/pkg_tested/dart_style/bin/format.dart"
-if [ -z "$DART_CONFIGURATION" ];
-then
- DART_CONFIGURATION="ReleaseX64"
-fi
-
-if [[ `uname` == 'Darwin' ]]; then
- BUILD_DIR="$DART_ROOT/xcodebuild/$DART_CONFIGURATION"
-else
- BUILD_DIR="$DART_ROOT/out/$DART_CONFIGURATION"
-fi
-
-PACKAGE_ROOT="$BUILD_DIR/packages/"
-
-exec "$DART" "--package-root=$PACKAGE_ROOT" "$DARTFMT" "$@"
+exec "$DART" "$DARTFMT" "$@"
diff --git a/sdk/bin/dartfmt.bat b/sdk/bin/dartfmt.bat
index c4ac9aa..edab2dd 100644
--- a/sdk/bin/dartfmt.bat
+++ b/sdk/bin/dartfmt.bat
@@ -27,14 +27,7 @@
set DARTFMT=%DART_ROOT%\third_party\pkg_tested\dart_style\bin\format.dart
-rem DART_CONFIGURATION defaults to ReleaseX64
-if "%DART_CONFIGURATION%"=="" set DART_CONFIGURATION=ReleaseX64
-
-set BUILD_DIR=%DART_ROOT%\out\%DART_CONFIGURATION%
-
-set PACKAGE_ROOT=%BUILD_DIR%\packages
-
-"%DART%" "--package-root=%PACKAGE_ROOT%" "%DARTFMT%" %*
+"%DART%" "%DARTFMT%" %*
endlocal
diff --git a/sdk/bin/pub b/sdk/bin/pub
index a8514ea..403635f 100755
--- a/sdk/bin/pub
+++ b/sdk/bin/pub
@@ -79,8 +79,7 @@
# Use the Dart binary in the built SDK so pub can find the version file next
# to it.
DART="$BUILD_DIR/dart-sdk/bin/dart"
-PACKAGES_DIR="$BUILD_DIR/packages/"
# Run pub.
PUB="$SDK_DIR/../third_party/pkg/pub/bin/pub.dart"
-exec "$DART" "${VM_OPTIONS[@]}" "--package-root=$PACKAGES_DIR" "$PUB" "$@"
+exec "$DART" "${VM_OPTIONS[@]}" "$PUB" "$@"
diff --git a/sdk/bin/pub.bat b/sdk/bin/pub.bat
index 55ff636..03c7bf0 100644
--- a/sdk/bin/pub.bat
+++ b/sdk/bin/pub.bat
@@ -31,12 +31,11 @@
rem Use the Dart binary in the built SDK so pub can find the version file next
rem to it.
set BUILD_DIR=%SDK_DIR%\..\out\ReleaseX64
-set PACKAGES_DIR=%BUILD_DIR%\packages
set DART=%BUILD_DIR%\dart-sdk\bin\dart
rem Run pub.
set PUB="%SDK_DIR%\..\third_party\pkg\pub\bin\pub.dart"
-"%DART%" %VM_OPTIONS% --package-root="%PACKAGES_DIR%" "%PUB%" %*
+"%DART%" %VM_OPTIONS% "%PUB%" %*
endlocal
diff --git a/sdk/lib/_internal/js_runtime/.packages b/sdk/lib/_internal/js_runtime/.packages
new file mode 100644
index 0000000..adf8b36
--- /dev/null
+++ b/sdk/lib/_internal/js_runtime/.packages
@@ -0,0 +1,2 @@
+# Generated by pub on 2015-12-07 17:08:11.724.
+js_runtime:lib/
diff --git a/tests/co19/co19-dartium.status b/tests/co19/co19-dartium.status
index 34b7cc1..91274b0 100644
--- a/tests/co19/co19-dartium.status
+++ b/tests/co19/co19-dartium.status
@@ -1013,8 +1013,6 @@
LibTest/isolate/Isolate/spawnUri_A01_t05: RuntimeError # Dart issue 15974
LibTest/isolate/Isolate/spawnUri_A01_t06: RuntimeError # Issue 27219
LibTest/isolate/Isolate/spawnUri_A01_t07: RuntimeError # Issue 27219
-LibTest/isolate/Isolate/spawnUri_A02_t01: RuntimeError # Dart issue 15974
-LibTest/isolate/Isolate/spawnUri_A02_t01: RuntimeError # Issue 27219
LibTest/isolate/Isolate/spawnUri_A02_t02: Skip # Dart issue 15974
LibTest/isolate/Isolate/spawnUri_A02_t03: Skip # Dart issue 15974
LibTest/isolate/Isolate/spawnUri_A02_t04: Skip # Dart issue 15974
@@ -1024,8 +1022,6 @@
LibTest/isolate/Isolate/spawn_A01_t04: RuntimeError, OK # Uses Isolate.spawn.
LibTest/isolate/Isolate/spawn_A01_t05: RuntimeError, OK # Uses Isolate.spawn.
LibTest/isolate/Isolate/spawn_A01_t06: RuntimeError # Issue 27219
-LibTest/isolate/Isolate/spawn_A02_t02: RuntimeError # Dart issue 15617
-LibTest/isolate/Isolate/spawn_A02_t02: RuntimeError # Issue 27219
LibTest/isolate/Isolate/spawn_A03_t01: RuntimeError # Issue 27219
LibTest/isolate/Isolate/spawn_A03_t02: RuntimeError # Issue 27219
LibTest/isolate/Isolate/spawn_A03_t03: RuntimeError # Issue 27219
diff --git a/tests/co19/co19-runtime.status b/tests/co19/co19-runtime.status
index df65d1f..e0845d9 100644
--- a/tests/co19/co19-runtime.status
+++ b/tests/co19/co19-runtime.status
@@ -82,6 +82,8 @@
LibTest/collection/ListMixin/ListMixin_class_A01_t01: Skip # Timeout
LibTest/collection/ListMixin/ListMixin_class_A01_t02: Skip # Timeout
LibTest/core/Uri/Uri_A06_t03: Skip # Timeout
+LibTest/isolate/Isolate/spawnUri_A01_t06: Pass, Fail # Issue 27378
+LibTest/isolate/Isolate/spawnUri_A01_t07: Pass, Fail # Issue 27378
[ $system == windows ]
LibTest/collection/ListMixin/ListMixin_class_A01_t02: Pass, Slow
@@ -230,6 +232,8 @@
Language/Types/Static_Types/deferred_type_t01: Skip # Requires deferred libraries
LibTest/async/DeferredLibrary/DeferredLibrary_A01_t01: Skip # Requires deferred libraries
LibTest/collection/DoubleLinkedQueue/DoubleLinkedQueue_class_A01_t01: Pass, Timeout
+LibTest/collection/IterableBase/IterableBase_class_A01_t02: Pass, Timeout
+LibTest/collection/IterableMixin/IterableMixin_class_A02_t01: Pass, Timeout
LibTest/collection/ListBase/ListBase_class_A01_t01: Pass, Timeout
LibTest/collection/ListBase/ListBase_class_A01_t02: Pass, Timeout
LibTest/collection/ListMixin/ListMixin_class_A01_t01: Pass, Timeout
diff --git a/tests/compiler/dart2js/analyze_all_test.dart b/tests/compiler/dart2js/analyze_all_test.dart
index 7039f93..9b1b6e3f 100644
--- a/tests/compiler/dart2js/analyze_all_test.dart
+++ b/tests/compiler/dart2js/analyze_all_test.dart
@@ -30,10 +30,8 @@
}
""";
-Future<DiagnosticCollector> run(
- String source,
- {bool analyzeAll,
- bool expectSuccess}) async {
+Future<DiagnosticCollector> run(String source,
+ {bool analyzeAll, bool expectSuccess}) async {
DiagnosticCollector collector = new DiagnosticCollector();
List<String> options = [];
@@ -53,20 +51,20 @@
test1() async {
DiagnosticCollector collector =
await run(SOURCE, analyzeAll: false, expectSuccess: true);
- Expect.isTrue(collector.warnings.isEmpty,
- 'Unexpected warnings: ${collector.warnings}');
- Expect.isTrue(collector.errors.isEmpty,
- 'Unexpected errors: ${collector.errors}');
+ Expect.isTrue(
+ collector.warnings.isEmpty, 'Unexpected warnings: ${collector.warnings}');
+ Expect.isTrue(
+ collector.errors.isEmpty, 'Unexpected errors: ${collector.errors}');
}
test2() async {
DiagnosticCollector collector =
await run(SOURCE, analyzeAll: true, expectSuccess: false);
- Expect.isTrue(collector.warnings.isEmpty,
- 'unexpected warnings: ${collector.warnings}');
+ Expect.isTrue(
+ collector.warnings.isEmpty, 'unexpected warnings: ${collector.warnings}');
Expect.equals(2, collector.errors.length,
- 'expected exactly two errors, but got ${collector.errors}');
+ 'expected exactly two errors, but got ${collector.errors}');
CollectedMessage first = collector.errors.first;
Expect.equals(MessageKind.CONSTRUCTOR_IS_NOT_CONST, first.message.kind);
@@ -99,10 +97,10 @@
DiagnosticCollector collector =
await run(source, analyzeAll: true, expectSuccess: false);
- Expect.isTrue(collector.warnings.isEmpty,
- 'unexpected warnings: ${collector.warnings}');
+ Expect.isTrue(
+ collector.warnings.isEmpty, 'unexpected warnings: ${collector.warnings}');
Expect.equals(1, collector.errors.length,
- 'expected exactly one error, but got ${collector.errors}');
+ 'expected exactly one error, but got ${collector.errors}');
}
main() {
diff --git a/tests/compiler/dart2js/analyze_api_test.dart b/tests/compiler/dart2js/analyze_api_test.dart
index 908ae11..695efe2 100644
--- a/tests/compiler/dart2js/analyze_api_test.dart
+++ b/tests/compiler/dart2js/analyze_api_test.dart
@@ -8,6 +8,7 @@
import 'analyze_helper.dart';
import 'package:async_helper/async_helper.dart';
import 'package:compiler/src/diagnostics/messages.dart' show MessageKind;
+
/**
* Map of white-listed warnings and errors.
*
@@ -18,8 +19,7 @@
* the error/warning message in the list of white-listings for each file.
*/
// TODO(johnniwinther): Support canonical URIs as keys.
-const Map<String, List<String>> WHITE_LIST = const {
-};
+const Map<String, List<String>> WHITE_LIST = const {};
void main() {
var uriList = new List<Uri>();
diff --git a/tests/compiler/dart2js/analyze_dart2js_helpers_test.dart b/tests/compiler/dart2js/analyze_dart2js_helpers_test.dart
index d4d85ef..c5cd57e 100644
--- a/tests/compiler/dart2js/analyze_dart2js_helpers_test.dart
+++ b/tests/compiler/dart2js/analyze_dart2js_helpers_test.dart
@@ -7,28 +7,21 @@
import 'dart:io';
import 'package:async_helper/async_helper.dart';
-import 'package:compiler/compiler_new.dart' show
- Diagnostic;
-import 'package:compiler/src/apiimpl.dart' show
- CompilerImpl;
+import 'package:compiler/compiler_new.dart' show Diagnostic;
+import 'package:compiler/src/apiimpl.dart' show CompilerImpl;
import 'package:compiler/src/commandline_options.dart';
-import 'package:compiler/src/constants/expressions.dart' show
- ConstructedConstantExpression;
-import 'package:compiler/src/dart_types.dart' show
- InterfaceType;
-import 'package:compiler/src/diagnostics/source_span.dart' show
- SourceSpan;
+import 'package:compiler/src/constants/expressions.dart'
+ show ConstructedConstantExpression;
+import 'package:compiler/src/dart_types.dart' show InterfaceType;
+import 'package:compiler/src/diagnostics/source_span.dart' show SourceSpan;
import 'package:compiler/src/elements/elements.dart';
-import 'package:compiler/src/filenames.dart' show
- nativeToUriPath;
+import 'package:compiler/src/filenames.dart' show nativeToUriPath;
import 'package:compiler/src/resolution/semantic_visitor.dart';
-import 'package:compiler/src/resolution/tree_elements.dart' show
- TreeElements;
-import 'package:compiler/src/source_file_provider.dart' show
- FormattingDiagnosticHandler;
+import 'package:compiler/src/resolution/tree_elements.dart' show TreeElements;
+import 'package:compiler/src/source_file_provider.dart'
+ show FormattingDiagnosticHandler;
import 'package:compiler/src/tree/tree.dart';
-import 'package:compiler/src/universe/call_structure.dart' show
- CallStructure;
+import 'package:compiler/src/universe/call_structure.dart' show CallStructure;
import 'package:expect/expect.dart';
import 'memory_compiler.dart';
@@ -39,13 +32,14 @@
List<String> options = <String>[
Flags.analyzeOnly,
Flags.analyzeMain,
- '--categories=Client,Server'];
+ '--categories=Client,Server'
+ ];
if (verbose) {
options.add(Flags.verbose);
}
asyncTest(() async {
- CompilerImpl compiler = compilerFor(
- options: options, showDiagnostics: verbose);
+ CompilerImpl compiler =
+ compilerFor(options: options, showDiagnostics: verbose);
FormattingDiagnosticHandler diagnostics =
new FormattingDiagnosticHandler(compiler.provider);
Directory dir =
@@ -122,66 +116,44 @@
Uri uri = analyzedElement.implementation.sourcePosition.uri;
SourceSpan span = new SourceSpan.fromNode(uri, node);
diagnostics.report(null, span.uri, span.begin, span.end,
- "Helper used in production code.",
- Diagnostic.ERROR);
+ "Helper used in production code.", Diagnostic.ERROR);
errors.add(span);
}
}
@override
- void visitTopLevelFieldInvoke(
- Send node,
- FieldElement field,
- NodeList arguments,
- CallStructure callStructure,
- _) {
+ void visitTopLevelFieldInvoke(Send node, FieldElement field,
+ NodeList arguments, CallStructure callStructure, _) {
checkAccess(node, field);
apply(arguments);
}
@override
- void visitTopLevelGetterInvoke(
- Send node,
- GetterElement getter,
- NodeList arguments,
- CallStructure callStructure,
- _) {
+ void visitTopLevelGetterInvoke(Send node, GetterElement getter,
+ NodeList arguments, CallStructure callStructure, _) {
checkAccess(node, getter);
apply(arguments);
}
@override
- void visitTopLevelFunctionInvoke(
- Send node,
- MethodElement method,
- NodeList arguments,
- CallStructure callStructure,
- _) {
+ void visitTopLevelFunctionInvoke(Send node, MethodElement method,
+ NodeList arguments, CallStructure callStructure, _) {
checkAccess(node, method);
apply(arguments);
}
@override
- void visitTopLevelFieldGet(
- Send node,
- FieldElement field,
- _) {
+ void visitTopLevelFieldGet(Send node, FieldElement field, _) {
checkAccess(node, field);
}
@override
- void visitTopLevelGetterGet(
- Send node,
- GetterElement getter,
- _) {
+ void visitTopLevelGetterGet(Send node, GetterElement getter, _) {
checkAccess(node, getter);
}
@override
- void visitTopLevelFunctionGet(
- Send node,
- MethodElement method,
- _) {
+ void visitTopLevelFunctionGet(Send node, MethodElement method, _) {
checkAccess(node, method);
}
@@ -237,9 +209,7 @@
@override
void visitConstConstructorInvoke(
- NewExpression node,
- ConstructedConstantExpression constant,
- _) {
+ NewExpression node, ConstructedConstantExpression constant, _) {
checkAccess(node, constant.target);
}
}
diff --git a/tests/compiler/dart2js/analyze_dart2js_test.dart b/tests/compiler/dart2js/analyze_dart2js_test.dart
index f5fc77c..1b1736f 100644
--- a/tests/compiler/dart2js/analyze_dart2js_test.dart
+++ b/tests/compiler/dart2js/analyze_dart2js_test.dart
@@ -21,16 +21,14 @@
*/
// TODO(johnniwinther): Support canonical URIs as keys and message kinds as
// values.
-const Map<String,List<String>> WHITE_LIST = const {
-};
+const Map<String, List<String>> WHITE_LIST = const {};
void main() {
var uri = currentDirectory.resolve('pkg/compiler/lib/src/dart2js.dart');
asyncTest(() => analyze([uri], WHITE_LIST, checkResults: checkResults));
}
-bool checkResults(Compiler compiler,
- CollectingDiagnosticHandler handler) {
+bool checkResults(Compiler compiler, CollectingDiagnosticHandler handler) {
checkRelatedTypes(compiler);
return !handler.hasHint;
-}
\ No newline at end of file
+}
diff --git a/tests/compiler/dart2js/analyze_helper.dart b/tests/compiler/dart2js/analyze_helper.dart
index fb06d78..779f389 100644
--- a/tests/compiler/dart2js/analyze_helper.dart
+++ b/tests/compiler/dart2js/analyze_helper.dart
@@ -9,12 +9,10 @@
import 'package:compiler/compiler.dart' as api;
import 'package:compiler/src/apiimpl.dart';
import 'package:compiler/src/commandline_options.dart';
-import 'package:compiler/src/diagnostics/messages.dart' show
- Message,
- MessageKind;
+import 'package:compiler/src/diagnostics/messages.dart'
+ show Message, MessageKind;
import 'package:compiler/src/filenames.dart';
-import 'package:compiler/src/options.dart' show
- CompilerOptions;
+import 'package:compiler/src/options.dart' show CompilerOptions;
import 'package:compiler/src/source_file_provider.dart';
import 'package:compiler/src/util/uri_extras.dart';
import 'diagnostic_helper.dart';
@@ -41,18 +39,18 @@
bool lastWasWhitelisted = false;
bool showWhitelisted = true;
- Map<String, Map<dynamic/*String|MessageKind*/, int>> whiteListMap
- = new Map<String, Map<dynamic/*String|MessageKind*/, int>>();
+ Map<String, Map<dynamic /*String|MessageKind*/, int>> whiteListMap =
+ new Map<String, Map<dynamic /*String|MessageKind*/, int>>();
List<MessageKind> skipList;
List<CollectedMessage> collectedMessages = <CollectedMessage>[];
CollectingDiagnosticHandler(
- Map<String, List/*<String|MessageKind>*/> whiteList,
+ Map<String, List/*<String|MessageKind>*/ > whiteList,
this.skipList,
SourceFileProvider provider)
: super(provider) {
whiteList.forEach((String file, List/*<String|MessageKind>*/ messageParts) {
- var useMap = new Map<dynamic/*String|MessageKind*/, int>();
+ var useMap = new Map<dynamic /*String|MessageKind*/, int>();
for (var messagePart in messageParts) {
useMap[messagePart] = 0;
}
@@ -73,7 +71,7 @@
for (var messagePart in whiteListMap[file].keys) {
if (whiteListMap[file][messagePart] == 0) {
print("Whitelisting '$messagePart' is unused in '$file'. "
- "Remove the whitelisting from the whitelist map.");
+ "Remove the whitelisting from the whitelist map.");
allUsed = false;
}
}
@@ -87,8 +85,8 @@
print('Unexpected messages:');
print('----------------------------------------------------------------');
for (CollectedMessage message in collectedMessages) {
- super.report(message.message, message.uri, message.begin,
- message.end, message.text, message.kind);
+ super.report(message.message, message.uri, message.begin, message.end,
+ message.text, message.kind);
}
print('----------------------------------------------------------------');
}
@@ -99,7 +97,7 @@
for (var messagePart in whiteListMap[file].keys) {
int useCount = whiteListMap[file][messagePart];
print("Whitelisted message '$messagePart' suppressed $useCount "
- "time(s) in '$file'.");
+ "time(s) in '$file'.");
}
}
}
@@ -134,7 +132,7 @@
@override
void report(Message message, Uri uri, int begin, int end, String text,
- api.Diagnostic kind) {
+ api.Diagnostic kind) {
if (kind == api.Diagnostic.WARNING) {
if (checkWhiteList(uri, message, text)) {
// Suppress whitelisted warnings.
@@ -173,24 +171,27 @@
}
lastWasWhitelisted = false;
if (kind != api.Diagnostic.VERBOSE_INFO) {
- collectedMessages.add(new CollectedMessage(
- message, uri, begin, end, text, kind));
+ collectedMessages
+ .add(new CollectedMessage(message, uri, begin, end, text, kind));
}
super.report(message, uri, begin, end, text, kind);
}
}
-typedef bool CheckResults(CompilerImpl compiler,
- CollectingDiagnosticHandler handler);
+typedef bool CheckResults(
+ CompilerImpl compiler, CollectingDiagnosticHandler handler);
enum AnalysisMode {
/// Analyze all declarations in all libraries in one go.
ALL,
+
/// Analyze all declarations in the main library.
MAIN,
+
/// Analyze all declarations in the given URIs one at a time. This mode can
/// handle URIs for parts (i.e. skips these).
URI,
+
/// Analyze all declarations reachable from the entry point.
TREE_SHAKING,
}
@@ -200,12 +201,12 @@
///
/// Messages can be generally allowed using [skipList] or on a per-file basis
/// using [whiteList].
-Future analyze(List<Uri> uriList,
- Map<String, List/*<String|MessageKind>*/> whiteList,
- {AnalysisMode mode: AnalysisMode.ALL,
- CheckResults checkResults,
- List<String> options: const <String>[],
- List<MessageKind> skipList: const <MessageKind>[]}) async {
+Future analyze(
+ List<Uri> uriList, Map<String, List/*<String|MessageKind>*/ > whiteList,
+ {AnalysisMode mode: AnalysisMode.ALL,
+ CheckResults checkResults,
+ List<String> options: const <String>[],
+ List<MessageKind> skipList: const <MessageKind>[]}) async {
String testFileName =
relativize(Uri.base, Platform.script, Platform.isWindows);
@@ -220,12 +221,14 @@
""");
var libraryRoot = currentDirectory.resolve('sdk/');
- var packageRoot =
- currentDirectory.resolve(Platform.packageRoot);
+ var packageConfig = currentDirectory.resolve('.packages');
var provider = new CompilerSourceFileProvider();
var handler = new CollectingDiagnosticHandler(whiteList, skipList, provider);
- options = <String>[Flags.analyzeOnly, '--categories=Client,Server',
- Flags.showPackageWarnings]..addAll(options);
+ options = <String>[
+ Flags.analyzeOnly,
+ '--categories=Client,Server',
+ Flags.showPackageWarnings
+ ]..addAll(options);
switch (mode) {
case AnalysisMode.URI:
case AnalysisMode.MAIN:
@@ -249,7 +252,7 @@
handler,
new CompilerOptions.parse(
libraryRoot: libraryRoot,
- packageRoot: packageRoot,
+ packageConfig: packageConfig,
options: options,
environment: {}));
String MESSAGE = """
diff --git a/tests/compiler/dart2js/analyze_only_test.dart b/tests/compiler/dart2js/analyze_only_test.dart
index e0a9948..13e7e53 100644
--- a/tests/compiler/dart2js/analyze_only_test.dart
+++ b/tests/compiler/dart2js/analyze_only_test.dart
@@ -18,7 +18,7 @@
import 'output_collector.dart';
runCompiler(String main, List<String> options,
- onValue(String code, List errors, List warnings)) {
+ onValue(String code, List errors, List warnings)) {
List errors = new List();
List warnings = new List();
@@ -27,8 +27,8 @@
return new Future<String>.value(main);
}
- void localHandler(Uri uri, int begin, int end,
- String message, Diagnostic kind) {
+ void localHandler(
+ Uri uri, int begin, int end, String message, Diagnostic kind) {
dummy.handler(uri, begin, end, message, kind);
if (kind == Diagnostic.ERROR) {
errors.add(message);
@@ -42,137 +42,121 @@
print('options: $options\n');
asyncStart();
OutputCollector outputCollector = new OutputCollector();
- Future<CompilationResult> result =
- compile(new Uri(scheme: 'main'),
- new Uri(scheme: 'lib', path: '/'),
- new Uri(scheme: 'package', path: '/'),
- localProvider, localHandler, options, outputCollector);
- result.then((_) {
- onValue(outputCollector.getOutput('', 'js'), errors, warnings);
- }, onError: (e, st) {
- throw 'Compilation failed: ${e} ${st}';
- }).then(asyncSuccess).catchError((error, stack) {
- print('\n\n-----------------------------------------------');
- print('main source:\n$main');
- print('options: $options\n');
- print('threw:\n $error\n$stack');
- print('-----------------------------------------------\n\n');
- throw error;
- });
+ Future<CompilationResult> result = compile(
+ new Uri(scheme: 'main'),
+ new Uri(scheme: 'lib', path: '/'),
+ new Uri(scheme: 'package', path: '/'),
+ localProvider,
+ localHandler,
+ options,
+ outputCollector);
+ result
+ .then((_) {
+ onValue(outputCollector.getOutput('', 'js'), errors, warnings);
+ }, onError: (e, st) {
+ throw 'Compilation failed: ${e} ${st}';
+ })
+ .then(asyncSuccess)
+ .catchError((error, stack) {
+ print('\n\n-----------------------------------------------');
+ print('main source:\n$main');
+ print('options: $options\n');
+ print('threw:\n $error\n$stack');
+ print('-----------------------------------------------\n\n');
+ throw error;
+ });
}
main() {
- runCompiler(
- "",
- [Flags.generateCodeWithCompileTimeErrors],
- (String code, List errors, List warnings) {
- Expect.isNotNull(code);
- Expect.isTrue(errors.isEmpty, 'errors is not empty: $errors');
- MessageTemplate template =
- MessageTemplate.TEMPLATES[MessageKind.MISSING_MAIN];
- Expect.equals(
- "${template.message({'main': 'main'})}",
- warnings.single);
- });
+ runCompiler("", [Flags.generateCodeWithCompileTimeErrors],
+ (String code, List errors, List warnings) {
+ Expect.isNotNull(code);
+ Expect.isTrue(errors.isEmpty, 'errors is not empty: $errors');
+ MessageTemplate template =
+ MessageTemplate.TEMPLATES[MessageKind.MISSING_MAIN];
+ Expect.equals("${template.message({'main': 'main'})}", warnings.single);
+ });
+
+ runCompiler("main() {}", [Flags.generateCodeWithCompileTimeErrors],
+ (String code, List errors, List warnings) {
+ Expect.isNotNull(code);
+ Expect.isTrue(errors.isEmpty);
+ Expect.isTrue(warnings.isEmpty);
+ });
+
+ runCompiler("", [Flags.analyzeOnly],
+ (String code, List errors, List warnings) {
+ Expect.isNull(code);
+ Expect.isTrue(errors.isEmpty, 'errors is not empty: $errors');
+ MessageTemplate template =
+ MessageTemplate.TEMPLATES[MessageKind.CONSIDER_ANALYZE_ALL];
+ Expect.equals("${template.message({'main': 'main'})}", warnings.single);
+ });
+
+ runCompiler("main() {}", [Flags.analyzeOnly],
+ (String code, List errors, List warnings) {
+ Expect.isNull(code);
+ Expect.isTrue(errors.isEmpty);
+ Expect.isTrue(warnings.isEmpty);
+ });
+
+ runCompiler("Foo foo; // Unresolved but not analyzed.", [Flags.analyzeOnly],
+ (String code, List errors, List warnings) {
+ Expect.isNull(code);
+ Expect.isTrue(errors.isEmpty, 'errors is not empty: $errors');
+ MessageTemplate template =
+ MessageTemplate.TEMPLATES[MessageKind.CONSIDER_ANALYZE_ALL];
+ Expect.equals("${template.message({'main': 'main'})}", warnings.single);
+ });
runCompiler(
- "main() {}",
- [Flags.generateCodeWithCompileTimeErrors],
- (String code, List errors, List warnings) {
- Expect.isNotNull(code);
- Expect.isTrue(errors.isEmpty);
- Expect.isTrue(warnings.isEmpty);
- });
-
- runCompiler(
- "",
- [Flags.analyzeOnly],
- (String code, List errors, List warnings) {
- Expect.isNull(code);
- Expect.isTrue(errors.isEmpty, 'errors is not empty: $errors');
- MessageTemplate template =
- MessageTemplate.TEMPLATES[MessageKind.CONSIDER_ANALYZE_ALL];
- Expect.equals(
- "${template.message({'main': 'main'})}",
- warnings.single);
- });
-
- runCompiler(
- "main() {}",
- [Flags.analyzeOnly],
- (String code, List errors, List warnings) {
- Expect.isNull(code);
- Expect.isTrue(errors.isEmpty);
- Expect.isTrue(warnings.isEmpty);
- });
-
- runCompiler(
- "Foo foo; // Unresolved but not analyzed.",
- [Flags.analyzeOnly],
- (String code, List errors, List warnings) {
- Expect.isNull(code);
- Expect.isTrue(errors.isEmpty, 'errors is not empty: $errors');
- MessageTemplate template =
- MessageTemplate.TEMPLATES[MessageKind.CONSIDER_ANALYZE_ALL];
- Expect.equals(
- "${template.message({'main': 'main'})}",
- warnings.single);
- });
-
- runCompiler(
- """main() {
+ """main() {
Foo foo; // Unresolved and analyzed.
}""",
- [Flags.analyzeOnly],
- (String code, List errors, List warnings) {
- Expect.isNull(code);
- Expect.isTrue(errors.isEmpty);
- Expect.equals(1, warnings.length);
- Expect.equals(
- "Cannot resolve type 'Foo'.", warnings[0].toString());
- });
+ [Flags.analyzeOnly], (String code, List errors, List warnings) {
+ Expect.isNull(code);
+ Expect.isTrue(errors.isEmpty);
+ Expect.equals(1, warnings.length);
+ Expect.equals("Cannot resolve type 'Foo'.", warnings[0].toString());
+ });
runCompiler(
- """main() {
+ """main() {
Foo foo; // Unresolved and analyzed.
}""",
- [Flags.analyzeOnly, Flags.analyzeSignaturesOnly],
- (String code, List errors, List warnings) {
- Expect.isNull(code);
- Expect.isTrue(errors.isEmpty);
- Expect.isTrue(warnings.isEmpty);
- });
+ [Flags.analyzeOnly, Flags.analyzeSignaturesOnly],
+ (String code, List errors, List warnings) {
+ Expect.isNull(code);
+ Expect.isTrue(errors.isEmpty);
+ Expect.isTrue(warnings.isEmpty);
+ });
+
+ runCompiler("Foo foo; // Unresolved and analyzed.", [
+ Flags.analyzeOnly,
+ Flags.analyzeAll
+ ], (String code, List errors, List warnings) {
+ Expect.isNull(code);
+ Expect.isTrue(errors.isEmpty);
+ Expect.equals("Cannot resolve type 'Foo'.", warnings[0].toString());
+ });
runCompiler(
- "Foo foo; // Unresolved and analyzed.",
- [Flags.analyzeOnly, Flags.analyzeAll],
- (String code, List errors, List warnings) {
- Expect.isNull(code);
- Expect.isTrue(errors.isEmpty);
- Expect.equals(
- "Cannot resolve type 'Foo'.", warnings[0].toString());
- });
-
- runCompiler(
- """Foo foo; // Unresolved and analyzed.
+ """Foo foo; // Unresolved and analyzed.
main() {}""",
- [Flags.analyzeOnly, Flags.analyzeAll],
- (String code, List errors, List warnings) {
- Expect.isNull(code);
- Expect.isTrue(errors.isEmpty, 'Unexpected errors: $errors.');
- Expect.equals(1, warnings.length, 'Unexpected warning count: $warnings.');
- Expect.equals(
- "Cannot resolve type 'Foo'.", warnings[0].toString());
- });
+ [Flags.analyzeOnly, Flags.analyzeAll],
+ (String code, List errors, List warnings) {
+ Expect.isNull(code);
+ Expect.isTrue(errors.isEmpty, 'Unexpected errors: $errors.');
+ Expect.equals(1, warnings.length, 'Unexpected warning count: $warnings.');
+ Expect.equals("Cannot resolve type 'Foo'.", warnings[0].toString());
+ });
- runCompiler(
- "",
- [Flags.analyzeOnly, Flags.analyzeAll],
- (String code, List errors, List warnings) {
- Expect.isNull(code);
- Expect.isTrue(errors.isEmpty);
- Expect.isTrue(warnings.isEmpty);
- });
+ runCompiler("", [Flags.analyzeOnly, Flags.analyzeAll],
+ (String code, List errors, List warnings) {
+ Expect.isNull(code);
+ Expect.isTrue(errors.isEmpty);
+ Expect.isTrue(warnings.isEmpty);
+ });
// --analyze-signatures-only implies --analyze-only
runCompiler("", [Flags.analyzeSignaturesOnly, Flags.analyzeAll],
@@ -195,8 +179,7 @@
runCompiler(
"""main() {}
foo() native 'foo';""",
- [Flags.analyzeOnly],
- (String code, List errors, List warnings) {
+ [Flags.analyzeOnly], (String code, List errors, List warnings) {
Expect.isNull(code);
Expect.isTrue(
errors.single.startsWith("'native' modifier is not supported."));
diff --git a/tests/compiler/dart2js/analyze_test_test.dart b/tests/compiler/dart2js/analyze_test_test.dart
index ebf8622..caa69cd 100644
--- a/tests/compiler/dart2js/analyze_test_test.dart
+++ b/tests/compiler/dart2js/analyze_test_test.dart
@@ -7,13 +7,10 @@
import 'dart:io';
import 'package:async_helper/async_helper.dart';
-import 'package:compiler/src/apiimpl.dart' show
- CompilerImpl;
+import 'package:compiler/src/apiimpl.dart' show CompilerImpl;
import 'package:compiler/src/commandline_options.dart';
-import 'package:compiler/src/diagnostics/messages.dart' show
- MessageKind;
-import 'package:compiler/src/filenames.dart' show
- nativeToUriPath;
+import 'package:compiler/src/diagnostics/messages.dart' show MessageKind;
+import 'package:compiler/src/filenames.dart' show nativeToUriPath;
import 'analyze_helper.dart';
import 'memory_compiler.dart';
@@ -25,10 +22,13 @@
* the error/warning message in the list of white-listings for each file.
*/
// TODO(johnniwinther): Support canonical URIs as keys.
-const Map<String, List/*<String|MessageKind>*/> WHITE_LIST = const {
- "/test/src/util/": const [
- "Library 'package:async/async.dart' doesn't export a "
- "'ForkableStream' declaration.",
+const Map<String, List/*<String|MessageKind>*/ > WHITE_LIST = const {
+ "/test/lib/src/util/": const [
+ "Library 'package:async/async.dart' doesn't export a "
+ "'ForkableStream' declaration.",
+ ],
+ "/utils.dart": const [
+ "Duplicated library name 'utils'.",
],
};
@@ -79,8 +79,8 @@
if (line.startsWith('Analyzing uri: ')) {
int filenameOffset = line.indexOf('tests/compiler/dart2js/');
if (filenameOffset != -1) {
- uriList.add(Uri.base.resolve(
- nativeToUriPath(line.substring(filenameOffset))));
+ uriList.add(Uri.base
+ .resolve(nativeToUriPath(line.substring(filenameOffset))));
}
}
}
@@ -98,10 +98,7 @@
if (uriList.isEmpty) {
uriList = computeInputUris(filter: filter);
}
- await analyze(
- uriList,
- WHITE_LIST,
- mode: AnalysisMode.URI,
- options: options);
+ await analyze(uriList, WHITE_LIST,
+ mode: AnalysisMode.URI, options: options);
});
}
diff --git a/tests/compiler/dart2js/analyze_unused_dart2js_test.dart b/tests/compiler/dart2js/analyze_unused_dart2js_test.dart
index 292c2c9..6440587 100644
--- a/tests/compiler/dart2js/analyze_unused_dart2js_test.dart
+++ b/tests/compiler/dart2js/analyze_unused_dart2js_test.dart
@@ -20,36 +20,35 @@
// Node.asAssert, Node.asLiteralBool is never used.
"lib/src/tree/nodes.dart": const [
- "The method 'asAssert' is never called.",
- "The method 'asLiteralBool' is never called."],
+ "The method 'asAssert' is never called.",
+ "The method 'asLiteralBool' is never called."
+ ],
// Uncalled methods in SemanticSendVisitor and subclasses.
- "lib/src/resolution/semantic_visitor.dart": const [
- "The method 'error"],
+ "lib/src/resolution/semantic_visitor.dart": const ["The method 'error"],
"lib/src/resolution/semantic_visitor_mixins.dart": const [
- "The class 'SuperBulkMixin'",
- "The class 'Base",
- "The method 'error",
- "The method 'visit"],
+ "The class 'SuperBulkMixin'",
+ "The class 'Base",
+ "The method 'error",
+ "The method 'visit"
+ ],
// Uncalled type predicate. Keep while related predicates are used.
- "lib/src/ssa/nodes.dart": const [
- "The method 'isArray' is never called"],
+ "lib/src/ssa/nodes.dart": const ["The method 'isArray' is never called"],
// Serialization code is only used in test.
- "lib/src/serialization/": const [
- "is never"],
+ "lib/src/serialization/": const ["is never"],
"lib/src/universe/universe.dart": const [
- "The method 'getterInvocationsByName' is never called.",
- "The method 'setterInvocationsByName' is never called."],
+ "The method 'getterInvocationsByName' is never called.",
+ "The method 'setterInvocationsByName' is never called."
+ ],
};
void main() {
- var uri = currentDirectory.resolve(
- 'pkg/compiler/lib/src/use_unused_api.dart');
- asyncTest(() => analyze(
- [uri],
+ var uri =
+ currentDirectory.resolve('pkg/compiler/lib/src/use_unused_api.dart');
+ asyncTest(() => analyze([uri],
// TODO(johnniwinther): Use [WHITE_LIST] again when
// [Compiler.reportUnusedCode] is reenabled.
const {}, // WHITE_LIST
@@ -58,31 +57,29 @@
}
bool checkResults(Compiler compiler, CollectingDiagnosticHandler handler) {
- var helperUri = currentDirectory.resolve(
- 'pkg/compiler/lib/src/helpers/helpers.dart');
+ var helperUri =
+ currentDirectory.resolve('pkg/compiler/lib/src/helpers/helpers.dart');
void checkLive(member) {
if (member.isFunction) {
if (compiler.enqueuer.resolution.hasBeenProcessed(member)) {
- compiler.reporter.reportHintMessage(
- member, MessageKind.GENERIC,
+ compiler.reporter.reportHintMessage(member, MessageKind.GENERIC,
{'text': "Helper function in production code '$member'."});
}
} else if (member.isClass) {
if (member.isResolved) {
- compiler.reporter.reportHintMessage(
- member, MessageKind.GENERIC,
+ compiler.reporter.reportHintMessage(member, MessageKind.GENERIC,
{'text': "Helper class in production code '$member'."});
} else {
member.forEachLocalMember(checkLive);
}
} else if (member.isTypedef) {
if (member.isResolved) {
- compiler.reporter.reportHintMessage(
- member, MessageKind.GENERIC,
+ compiler.reporter.reportHintMessage(member, MessageKind.GENERIC,
{'text': "Helper typedef in production code '$member'."});
}
}
}
+
compiler.libraryLoader.lookupLibrary(helperUri).forEachLocalMember(checkLive);
return handler.checkResults();
}
diff --git a/tests/compiler/dart2js/arithmetic_simplification_test.dart b/tests/compiler/dart2js/arithmetic_simplification_test.dart
index a0a0efa..09b1e32 100644
--- a/tests/compiler/dart2js/arithmetic_simplification_test.dart
+++ b/tests/compiler/dart2js/arithmetic_simplification_test.dart
@@ -41,7 +41,6 @@
}
""";
-
const String INT_TIMES_ONE = """
int foo(x) => x;
void main() {
@@ -81,13 +80,13 @@
var oneTimes = new RegExp(r"1 \*");
asyncTest(() => Future.wait([
- compileAndDoNotMatch(INT_PLUS_ZERO, 'main', plusZero),
- compileAndDoNotMatch(ZERO_PLUS_INT, 'main', zeroPlus),
- compileAndMatch(NUM_PLUS_ZERO, 'main', plusZero),
- compileAndMatch(ZERO_PLUS_NUM, 'main', zeroPlus),
- compileAndDoNotMatch(INT_TIMES_ONE, 'main', timesOne),
- compileAndDoNotMatch(ONE_TIMES_INT, 'main', oneTimes),
- compileAndDoNotMatch(NUM_TIMES_ONE, 'main', timesOne),
- compileAndDoNotMatch(ONE_TIMES_NUM, 'main', oneTimes),
- ]));
+ compileAndDoNotMatch(INT_PLUS_ZERO, 'main', plusZero),
+ compileAndDoNotMatch(ZERO_PLUS_INT, 'main', zeroPlus),
+ compileAndMatch(NUM_PLUS_ZERO, 'main', plusZero),
+ compileAndMatch(ZERO_PLUS_NUM, 'main', zeroPlus),
+ compileAndDoNotMatch(INT_TIMES_ONE, 'main', timesOne),
+ compileAndDoNotMatch(ONE_TIMES_INT, 'main', oneTimes),
+ compileAndDoNotMatch(NUM_TIMES_ONE, 'main', timesOne),
+ compileAndDoNotMatch(ONE_TIMES_NUM, 'main', oneTimes),
+ ]));
}
diff --git a/tests/compiler/dart2js/array_static_intercept_test.dart b/tests/compiler/dart2js/array_static_intercept_test.dart
index bd0a02f..dbe3978 100644
--- a/tests/compiler/dart2js/array_static_intercept_test.dart
+++ b/tests/compiler/dart2js/array_static_intercept_test.dart
@@ -16,9 +16,9 @@
main() {
asyncTest(() => compile(TEST_ONE, entry: 'foo', check: (String generated) {
- Expect.isTrue(generated.contains(r'.add$1('));
- Expect.isTrue(generated.contains(r'.removeLast$0('));
- Expect.isTrue(generated.contains(r'.length'),
- "Unexpected code to contain '.length':\n$generated");
- }));
+ Expect.isTrue(generated.contains(r'.add$1('));
+ Expect.isTrue(generated.contains(r'.removeLast$0('));
+ Expect.isTrue(generated.contains(r'.length'),
+ "Unexpected code to contain '.length':\n$generated");
+ }));
}
diff --git a/tests/compiler/dart2js/array_tracing_mirror_test.dart b/tests/compiler/dart2js/array_tracing_mirror_test.dart
index 6a083ca..4b28acb 100644
--- a/tests/compiler/dart2js/array_tracing_mirror_test.dart
+++ b/tests/compiler/dart2js/array_tracing_mirror_test.dart
@@ -36,8 +36,6 @@
var compiler = result.compiler;
var element = compiler.mainFunction;
var code = compiler.backend.getGeneratedCode(element);
- Expect.isTrue(code.contains('return 2'),
- "Unexpected code:\n$code");
+ Expect.isTrue(code.contains('return 2'), "Unexpected code:\n$code");
});
}
-
diff --git a/tests/compiler/dart2js/async_await_js_transform_test.dart b/tests/compiler/dart2js/async_await_js_transform_test.dart
index f5df58c..0a11fbb 100644
--- a/tests/compiler/dart2js/async_await_js_transform_test.dart
+++ b/tests/compiler/dart2js/async_await_js_transform_test.dart
@@ -20,40 +20,47 @@
}
void testAsyncTransform(String source, String expected) {
- testTransform(source, expected, new AsyncRewriter(
- null, // The diagnostic helper should not be used in these tests.
- null,
- asyncHelper: new VariableUse("thenHelper"),
- newCompleter: new VariableUse("Completer"),
- wrapBody: new VariableUse("_wrapJsFunctionForAsync"),
- safeVariableName: (String name) => "__$name",
- bodyName: new StringBackedName("body")));
+ testTransform(
+ source,
+ expected,
+ new AsyncRewriter(
+ null, // The diagnostic helper should not be used in these tests.
+ null,
+ asyncHelper: new VariableUse("thenHelper"),
+ newCompleter: new VariableUse("Completer"),
+ wrapBody: new VariableUse("_wrapJsFunctionForAsync"),
+ safeVariableName: (String name) => "__$name",
+ bodyName: new StringBackedName("body")));
}
void testSyncStarTransform(String source, String expected) {
- testTransform(source, expected, new SyncStarRewriter(
- null,
- null,
- endOfIteration: new VariableUse("endOfIteration"),
- newIterable: new VariableUse("newIterable"),
- yieldStarExpression: new VariableUse("yieldStar"),
- uncaughtErrorExpression: new VariableUse("uncaughtError"),
- safeVariableName: (String name) => "__$name",
- bodyName: new StringBackedName("body")));
+ testTransform(
+ source,
+ expected,
+ new SyncStarRewriter(null, null,
+ endOfIteration: new VariableUse("endOfIteration"),
+ newIterable: new VariableUse("newIterable"),
+ yieldStarExpression: new VariableUse("yieldStar"),
+ uncaughtErrorExpression: new VariableUse("uncaughtError"),
+ safeVariableName: (String name) => "__$name",
+ bodyName: new StringBackedName("body")));
}
main() {
- testAsyncTransform( /// 01: ok
-r"""function() async {
+ testAsyncTransform(
+
+ /// 01: ok
+ r"""function() async {
var closures = [new A.main_closure()], v0 = await closures, v1 = 0, v2, v3;
if (v1 < 0 || v1 >= v0.length)
H.ioore(v0, v1);
v2 = 4;
v3 = 2;
P.print(v0[v1].call$2(v2, v3));
-}"""
-, /// 01: ok
- r"""function() {
+}""",
+
+ /// 01: ok
+ r"""function() {
var __goto = 0, __completer = new Completer(), __handler = 1, __currentError, closures, v0, v1, v2, v3;
var body = _wrapJsFunctionForAsync(function(__errorCode, __result) {
if (__errorCode === 1) {
@@ -84,15 +91,18 @@
}
});
return thenHelper(null, body, __completer);
-}"""
- ) /// 01: ok
- ;
+}""")
- testAsyncTransform("""
+ /// 01: ok
+ ;
+
+ testAsyncTransform(
+ """
function(a) async {
print(this.x); // Ensure `this` is translated in the helper function.
await foo();
-}""", """
+}""",
+ """
function(a) {
var __goto = 0, __completer = new Completer(), __handler = 1, __currentError, __self = this;
var body = _wrapJsFunctionForAsync(function(__errorCode, __result) {
@@ -119,7 +129,8 @@
return thenHelper(null, body, __completer);
}""");
- testAsyncTransform("""
+ testAsyncTransform(
+ """
function(b) async {
try {
__outer: while (true) { // Overlapping label name.
@@ -142,7 +153,8 @@
return 3; // Return from finally with no pending finally.
}
return 4;
- }""", """
+ }""",
+ """
function(b) {
var __goto = 0, __completer = new Completer(), __returnValue, __handler = 2, __currentError, __next = [], __helper;
var body = _wrapJsFunctionForAsync(function(__errorCode, __result) {
@@ -243,7 +255,8 @@
return thenHelper(null, body, __completer);
}""");
- testAsyncTransform("""
+ testAsyncTransform(
+ """
function(c) async {
var a, b, c, d, e, f;
a = b++; // post- and preincrements.
@@ -252,7 +265,8 @@
d = ++(await foo()).a;
e = foo1()[await foo2()]--;
f = --foo1()[await foo2()];
-}""", """
+}""",
+ """
function(c) {
var __goto = 0, __completer = new Completer(), __handler = 1, __currentError, a, b, c, d, e, f, __temp1;
var body = _wrapJsFunctionForAsync(function(__errorCode, __result) {
@@ -298,7 +312,8 @@
return thenHelper(null, body, __completer);
}""");
- testAsyncTransform("""
+ testAsyncTransform(
+ """
function(d2) async {
var a, b, c, d, e, f, g, h; // empty initializer
a = foo1() || await foo2(); // short circuiting operators
@@ -309,7 +324,8 @@
f = await foo1() && foo2();
g = await foo1() && await foo2();
h = foo1() && foo2();
- }""", """
+ }""",
+ """
function(d2) {
var __goto = 0, __completer = new Completer(), __handler = 1, __currentError, a, b, c, d, e, f, g, h, __temp1;
var body = _wrapJsFunctionForAsync(function(__errorCode, __result) {
@@ -431,7 +447,8 @@
return thenHelper(null, body, __completer);
}""");
- testAsyncTransform("""
+ testAsyncTransform(
+ """
function(x, y) async {
while (true) {
switch(y) { // Switch with no awaits in case key expressions
@@ -446,7 +463,8 @@
foo(); // No default
}
}
-}""", """
+}""",
+ """
function(x, y) {
var __goto = 0, __completer = new Completer(), __handler = 1, __currentError;
var body = _wrapJsFunctionForAsync(function(__errorCode, __result) {
@@ -525,7 +543,8 @@
return thenHelper(null, body, __completer);
}""");
- testAsyncTransform("""
+ testAsyncTransform(
+ """
function(f) async {
do {
var a = await foo();
@@ -535,7 +554,8 @@
continue;
} while (await foo());
}
- """, """
+ """,
+ """
function(f) {
var __goto = 0, __completer = new Completer(), __handler = 1, __currentError, a;
var body = _wrapJsFunctionForAsync(function(__errorCode, __result) {
@@ -586,7 +606,8 @@
return thenHelper(null, body, __completer);
}""");
- testAsyncTransform("""
+ testAsyncTransform(
+ """
function(g) async {
for (var i = 0; i < await foo1(); i += await foo2()) {
if (foo(i))
@@ -600,7 +621,8 @@
print(await(foo(i)));
}
}
-""", """
+""",
+ """
function(g) {
var __goto = 0, __completer = new Completer(), __returnValue, __handler = 2, __currentError, i, __temp1;
var body = _wrapJsFunctionForAsync(function(__errorCode, __result) {
@@ -676,7 +698,8 @@
return thenHelper(null, body, __completer);
}""");
- testAsyncTransform("""
+ testAsyncTransform(
+ """
function(a, h) async {
var x = {"a": foo1(), "b": await foo2(), "c": foo3()};
x["a"] = 2; // Different assignments
@@ -685,7 +708,8 @@
x[(await foo1()).a = await foo2()] = 5;
(await foo1())[await foo2()] = await foo3(6);
}
- """, """
+ """,
+ """
function(a, h) {
var __goto = 0, __completer = new Completer(), __handler = 1, __currentError, x, __temp1, __temp2;
var body = _wrapJsFunctionForAsync(function(__errorCode, __result) {
@@ -751,7 +775,8 @@
return thenHelper(null, body, __completer);
}""");
- testAsyncTransform("""
+ testAsyncTransform(
+ """
function(c, i) async {
try {
var x = c ? await foo() : foo(); // conditional
@@ -766,7 +791,8 @@
}
}
}
-""", """
+""",
+ """
function(c, i) {
var __goto = 0, __completer = new Completer(), __handler = 1, __currentError, __next = [], x, y, __error, __error1;
var body = _wrapJsFunctionForAsync(function(__errorCode, __result) {
@@ -868,7 +894,8 @@
return thenHelper(null, body, __completer);
}""");
- testAsyncTransform("""
+ testAsyncTransform(
+ """
function(x, y, j) async {
print(await(foo(x))); // calls
(await print)(foo(x));
@@ -876,7 +903,8 @@
await (print(foo(await x)));
print(foo(x, await y, z));
}
- """, """
+ """,
+ """
function(x, y, j) {
var __goto = 0, __completer = new Completer(), __handler = 1, __currentError, __temp1, __temp2, __temp3;
var body = _wrapJsFunctionForAsync(function(__errorCode, __result) {
@@ -934,7 +962,8 @@
return thenHelper(null, body, __completer);
}""");
- testAsyncTransform("""
+ testAsyncTransform(
+ """
function(x, y, k) async {
while (await(foo())) {
lab: { // labelled statement
@@ -959,7 +988,8 @@
foo();
}
}
-}""", """
+}""",
+ """
function(x, y, k) {
var __goto = 0, __completer = new Completer(), __returnValue, __handler = 2, __currentError, __temp1;
var body = _wrapJsFunctionForAsync(function(__errorCode, __result) {
@@ -1074,7 +1104,8 @@
return thenHelper(null, body, __completer);
}""");
- testAsyncTransform("""
+ testAsyncTransform(
+ """
function(l) async {
switch(await l) {
case 1:
@@ -1087,7 +1118,8 @@
print(2);
break;
}
- }""", """
+ }""",
+ """
function(l) {
var __goto = 0, __completer = new Completer(), __handler = 1, __currentError;
var body = _wrapJsFunctionForAsync(function(__errorCode, __result) {
@@ -1123,7 +1155,8 @@
return thenHelper(null, body, __completer);
}""");
- testAsyncTransform("""
+ testAsyncTransform(
+ """
function(m) async {
var exception = 1;
try {
@@ -1139,7 +1172,8 @@
exception += 10;
}
print(exception);
- }""", """
+ }""",
+ """
function(m) {
var __goto = 0, __completer = new Completer(), __handler = 1, __currentError, __next = [], exception, __exception;
var body = _wrapJsFunctionForAsync(function(__errorCode, __result) {
@@ -1202,12 +1236,14 @@
return thenHelper(null, body, __completer);
}""");
- testSyncStarTransform("""
+ testSyncStarTransform(
+ """
function(a) sync* {
// Ensure that return of a value is treated as first evaluating the value, and
// then returning.
return foo();
-}""", """
+}""",
+ """
function(__a) {
return new newIterable(function() {
var a = __a;
diff --git a/tests/compiler/dart2js/async_compiler_input_provider_test.dart b/tests/compiler/dart2js/async_compiler_input_provider_test.dart
index c7bc35b..b178c3e 100644
--- a/tests/compiler/dart2js/async_compiler_input_provider_test.dart
+++ b/tests/compiler/dart2js/async_compiler_input_provider_test.dart
@@ -47,13 +47,13 @@
Uri packageRoot = script.resolve('./packages/');
asyncTest(() => compiler.compile(entrypoint, libraryRoot, packageRoot,
- provideInput, handleDiagnostic, []).then((code) {
- Expect.isNotNull(code);
- }));
+ provideInput, handleDiagnostic, []).then((code) {
+ Expect.isNotNull(code);
+ }));
}
-void handleDiagnostic(Uri uri, int begin, int end, String message,
- compiler.Diagnostic kind) {
+void handleDiagnostic(
+ Uri uri, int begin, int end, String message, compiler.Diagnostic kind) {
print(message);
if (kind != compiler.Diagnostic.VERBOSE_INFO) {
throw 'Unexpected diagnostic kind $kind';
diff --git a/tests/compiler/dart2js/bad_loop_test.dart b/tests/compiler/dart2js/bad_loop_test.dart
index bc6d43d..979c8ad 100644
--- a/tests/compiler/dart2js/bad_loop_test.dart
+++ b/tests/compiler/dart2js/bad_loop_test.dart
@@ -6,8 +6,7 @@
import 'memory_source_file_helper.dart';
import "package:async_helper/async_helper.dart";
-import 'package:compiler/compiler.dart'
- show Diagnostic;
+import 'package:compiler/compiler.dart' show Diagnostic;
import 'package:compiler/src/options.dart' show CompilerOptions;
import 'package:compiler/src/old_to_new_api.dart';
@@ -19,8 +18,8 @@
var provider = new MemorySourceFileProvider(MEMORY_SOURCE_FILES);
int warningCount = 0;
int errorCount = 0;
- void diagnosticHandler(Uri uri, int begin, int end,
- String message, Diagnostic kind) {
+ void diagnosticHandler(
+ Uri uri, int begin, int end, String message, Diagnostic kind) {
if (kind == Diagnostic.VERBOSE_INFO) {
return;
}
@@ -37,14 +36,12 @@
new LegacyCompilerInput(provider.readStringFromUri),
new LegacyCompilerOutput(),
new LegacyCompilerDiagnostics(diagnosticHandler),
- new CompilerOptions(
- libraryRoot: libraryRoot,
- packageRoot: packageRoot));
+ new CompilerOptions(libraryRoot: libraryRoot, packageRoot: packageRoot));
asyncTest(() => compiler.run(Uri.parse('memory:main.dart')).then((_) {
- Expect.isTrue(compiler.compilationFailed);
- Expect.equals(5, errorCount);
- Expect.equals(1, warningCount);
- }));
+ Expect.isTrue(compiler.compilationFailed);
+ Expect.equals(5, errorCount);
+ Expect.equals(1, warningCount);
+ }));
}
const Map MEMORY_SOURCE_FILES = const {
diff --git a/tests/compiler/dart2js/bad_output_io_test.dart b/tests/compiler/dart2js/bad_output_io_test.dart
index ebda63f..5c12e71 100644
--- a/tests/compiler/dart2js/bad_output_io_test.dart
+++ b/tests/compiler/dart2js/bad_output_io_test.dart
@@ -9,16 +9,14 @@
import 'dart:io' show exit;
import 'package:expect/expect.dart';
-import 'package:compiler/compiler.dart'
- show Diagnostic;
+import 'package:compiler/compiler.dart' show Diagnostic;
import 'package:compiler/src/dart2js.dart'
- show exitFunc, compileFunc, compile, diagnosticHandler;
+ show exitFunc, compileFunc, compile, diagnosticHandler;
import 'package:compiler/src/source_file_provider.dart'
- show FormattingDiagnosticHandler;
+ show FormattingDiagnosticHandler;
class CollectingFormattingDiagnosticHandler
implements FormattingDiagnosticHandler {
-
final provider = null;
bool showWarnings = true;
bool showHints = true;
@@ -34,7 +32,7 @@
final messages = [];
void info(var message, [kind]) {
- messages.add([message, kind]);
+ messages.add([message, kind]);
}
@override
diff --git a/tests/compiler/dart2js/begin_end_token_test.dart b/tests/compiler/dart2js/begin_end_token_test.dart
index 37949fb..fca0712 100644
--- a/tests/compiler/dart2js/begin_end_token_test.dart
+++ b/tests/compiler/dart2js/begin_end_token_test.dart
@@ -20,7 +20,7 @@
Expect.isTrue(begin <= end, debug);
if (hard) {
- Expect.stringEquals(expected, text.substring(begin, end), debug);
+ Expect.stringEquals(expected, text.substring(begin, end), debug);
}
}
diff --git a/tests/compiler/dart2js/benign_error_test.dart b/tests/compiler/dart2js/benign_error_test.dart
index 28c84dd..143239b 100644
--- a/tests/compiler/dart2js/benign_error_test.dart
+++ b/tests/compiler/dart2js/benign_error_test.dart
@@ -28,13 +28,12 @@
}
DiagnosticCollector collector = new DiagnosticCollector();
CompilationResult result = await runCompiler(
- memorySourceFiles: example,
- diagnosticHandler: collector);
+ memorySourceFiles: example, diagnosticHandler: collector);
Expect.isTrue(result.isSuccess);
- Expect.isTrue(
- collector.errors.any((message) => message.messageKind == kind));
+ Expect
+ .isTrue(collector.errors.any((message) => message.messageKind == kind));
Compiler compiler = result.compiler;
JavaScriptBackend backend = compiler.backend;
Expect.isNotNull(backend.generatedCode[compiler.mainFunction]);
}
-}
\ No newline at end of file
+}
diff --git a/tests/compiler/dart2js/boolified_operator_test.dart b/tests/compiler/dart2js/boolified_operator_test.dart
index 6a8bd9f..d632fed 100644
--- a/tests/compiler/dart2js/boolified_operator_test.dart
+++ b/tests/compiler/dart2js/boolified_operator_test.dart
@@ -54,29 +54,29 @@
RegExp regexp = new RegExp('=== true');
asyncTest(() => Future.wait([
- compile(TEST_EQUAL, entry: 'foo', check: (String generated) {
- Expect.isFalse(generated.contains('=== true'));
- Expect.isTrue(generated.contains('eqB'));
- }),
- compile(TEST_EQUAL_NULL, entry: 'foo', check: (String generated) {
- Expect.isFalse(generated.contains('=== true'));
- Expect.isTrue(generated.contains('== null'));
- }),
- compile(TEST_LESS, entry: 'foo', check: (String generated) {
- Expect.isFalse(generated.contains('=== true'));
- Expect.isTrue(generated.contains('ltB'));
- }),
- compile(TEST_LESS_EQUAL, entry: 'foo', check: (String generated) {
- Expect.isFalse(generated.contains('=== true'));
- Expect.isTrue(generated.contains('leB'));
- }),
- compile(TEST_GREATER, entry: 'foo', check: (String generated) {
- Expect.isFalse(generated.contains('=== true'));
- Expect.isTrue(generated.contains('gtB'));
- }),
- compile(TEST_GREATER_EQUAL, entry: 'foo', check: (String generated) {
- Expect.isFalse(generated.contains('=== true'));
- Expect.isTrue(generated.contains('geB'));
- }),
- ]));
+ compile(TEST_EQUAL, entry: 'foo', check: (String generated) {
+ Expect.isFalse(generated.contains('=== true'));
+ Expect.isTrue(generated.contains('eqB'));
+ }),
+ compile(TEST_EQUAL_NULL, entry: 'foo', check: (String generated) {
+ Expect.isFalse(generated.contains('=== true'));
+ Expect.isTrue(generated.contains('== null'));
+ }),
+ compile(TEST_LESS, entry: 'foo', check: (String generated) {
+ Expect.isFalse(generated.contains('=== true'));
+ Expect.isTrue(generated.contains('ltB'));
+ }),
+ compile(TEST_LESS_EQUAL, entry: 'foo', check: (String generated) {
+ Expect.isFalse(generated.contains('=== true'));
+ Expect.isTrue(generated.contains('leB'));
+ }),
+ compile(TEST_GREATER, entry: 'foo', check: (String generated) {
+ Expect.isFalse(generated.contains('=== true'));
+ Expect.isTrue(generated.contains('gtB'));
+ }),
+ compile(TEST_GREATER_EQUAL, entry: 'foo', check: (String generated) {
+ Expect.isFalse(generated.contains('=== true'));
+ Expect.isTrue(generated.contains('geB'));
+ }),
+ ]));
}
diff --git a/tests/compiler/dart2js/boolify_test.dart b/tests/compiler/dart2js/boolify_test.dart
index 7d2a7b9..12685a3 100644
--- a/tests/compiler/dart2js/boolify_test.dart
+++ b/tests/compiler/dart2js/boolify_test.dart
@@ -18,6 +18,6 @@
main() {
asyncTest(() => compile(TEST, entry: 'foo', check: (String generated) {
- Expect.isTrue(generated.contains('foo() !== true)'));
- }));
+ Expect.isTrue(generated.contains('foo() !== true)'));
+ }));
}
diff --git a/tests/compiler/dart2js/builtin_equals_test.dart b/tests/compiler/dart2js/builtin_equals_test.dart
index 57656c0..e60bdd5 100644
--- a/tests/compiler/dart2js/builtin_equals_test.dart
+++ b/tests/compiler/dart2js/builtin_equals_test.dart
@@ -19,11 +19,11 @@
main() {
asyncTest(() => compile(TEST, entry: 'foo', enableTypeAssertions: true,
- check: (String generated) {
- Expect.isTrue(!generated.contains('eqB'));
+ check: (String generated) {
+ Expect.isTrue(!generated.contains('eqB'));
- RegExp regexp = new RegExp('==');
- Iterator<Match> matches = regexp.allMatches(generated).iterator;
- checkNumberOfMatches(matches, 4);
- }));
+ RegExp regexp = new RegExp('==');
+ Iterator<Match> matches = regexp.allMatches(generated).iterator;
+ checkNumberOfMatches(matches, 4);
+ }));
}
diff --git a/tests/compiler/dart2js/builtin_interceptor_test.dart b/tests/compiler/dart2js/builtin_interceptor_test.dart
index 24e3a2c..a9ae6b2 100644
--- a/tests/compiler/dart2js/builtin_interceptor_test.dart
+++ b/tests/compiler/dart2js/builtin_interceptor_test.dart
@@ -27,14 +27,14 @@
main() {
asyncTest(() => Future.wait([
- compile(TEST_ONE, entry: 'foo', check: (String generated) {
- Expect.isTrue(generated.contains("return 3;"));
- }),
- compile(TEST_TWO, entry: 'foo', check: (String generated) {
- Expect.isTrue(generated.contains("return 3;"));
- }),
- compile(TEST_THREE, entry: 'foo', check: (String generated) {
- Expect.isTrue(generated.contains("push(2);"));
- }),
- ]));
+ compile(TEST_ONE, entry: 'foo', check: (String generated) {
+ Expect.isTrue(generated.contains("return 3;"));
+ }),
+ compile(TEST_TWO, entry: 'foo', check: (String generated) {
+ Expect.isTrue(generated.contains("return 3;"));
+ }),
+ compile(TEST_THREE, entry: 'foo', check: (String generated) {
+ Expect.isTrue(generated.contains("push(2);"));
+ }),
+ ]));
}
diff --git a/tests/compiler/dart2js/call_site_simple_type_inferer_test.dart b/tests/compiler/dart2js/call_site_simple_type_inferer_test.dart
index 0bb8f37..8a6e86b 100644
--- a/tests/compiler/dart2js/call_site_simple_type_inferer_test.dart
+++ b/tests/compiler/dart2js/call_site_simple_type_inferer_test.dart
@@ -8,18 +8,15 @@
import 'compiler_helper.dart';
import 'type_mask_test_helper.dart';
-void compileAndFind(String code,
- String className,
- String memberName,
- bool disableInlining,
- check(compiler, element)) {
+void compileAndFind(String code, String className, String memberName,
+ bool disableInlining, check(compiler, element)) {
Uri uri = new Uri(scheme: 'source');
var compiler = compilerFor(code, uri, disableInlining: disableInlining);
asyncTest(() => compiler.run(uri).then((_) {
- var cls = findElement(compiler, className);
- var member = cls.lookupLocalMember(memberName);
- return check(compiler, member);
- }));
+ var cls = findElement(compiler, className);
+ var member = cls.lookupLocalMember(memberName);
+ return check(compiler, member);
+ }));
}
const String TEST_1 = r"""
@@ -210,22 +207,16 @@
""";
void doTest(String test, bool enableInlining, Function f) {
- compileAndFind(
- test,
- 'A',
- 'x',
- enableInlining,
- (compiler, element) {
- var expectedTypes = f(compiler);
- var signature = element.functionSignature;
- int index = 0;
- var inferrer = compiler.globalInference.typesInferrer;
- signature.forEachParameter((Element element) {
- Expect.equals(expectedTypes[index++],
- simplify(inferrer.getTypeOfElement(element), compiler),
- test);
- });
- Expect.equals(index, expectedTypes.length);
+ compileAndFind(test, 'A', 'x', enableInlining, (compiler, element) {
+ var expectedTypes = f(compiler);
+ var signature = element.functionSignature;
+ int index = 0;
+ var inferrer = compiler.globalInference.typesInferrer;
+ signature.forEachParameter((Element element) {
+ Expect.equals(expectedTypes[index++],
+ simplify(inferrer.getTypeOfElement(element), compiler), test);
+ });
+ Expect.equals(index, expectedTypes.length);
});
}
@@ -246,40 +237,66 @@
runTest(TEST_5, (compiler) => [compiler.commonMasks.numType]);
runTest(TEST_6, (compiler) => [compiler.commonMasks.numType]);
runTest(TEST_7a, (compiler) => [subclassOfInterceptor(compiler)]);
- runTest(TEST_7b,
- (compiler) => [compiler.commonMasks.dynamicType.nonNullable()]);
+ runTest(
+ TEST_7b, (compiler) => [compiler.commonMasks.dynamicType.nonNullable()]);
- runTest(TEST_8, (compiler) => [compiler.commonMasks.uint31Type,
- subclassOfInterceptor(compiler),
- compiler.commonMasks.dynamicType.nonNullable()]);
- runTest(TEST_9, (compiler) => [compiler.commonMasks.uint31Type,
- compiler.commonMasks.uint31Type]);
- runTest(TEST_10, (compiler) => [compiler.commonMasks.uint31Type,
- compiler.commonMasks.uint31Type]);
- runTest(TEST_11, (compiler) => [subclassOfInterceptor(compiler),
- subclassOfInterceptor(compiler)]);
+ runTest(
+ TEST_8,
+ (compiler) => [
+ compiler.commonMasks.uint31Type,
+ subclassOfInterceptor(compiler),
+ compiler.commonMasks.dynamicType.nonNullable()
+ ]);
+ runTest(
+ TEST_9,
+ (compiler) =>
+ [compiler.commonMasks.uint31Type, compiler.commonMasks.uint31Type]);
+ runTest(
+ TEST_10,
+ (compiler) =>
+ [compiler.commonMasks.uint31Type, compiler.commonMasks.uint31Type]);
+ runTest(
+ TEST_11,
+ (compiler) =>
+ [subclassOfInterceptor(compiler), subclassOfInterceptor(compiler)]);
- runTest(TEST_12, (compiler) => [compiler.commonMasks.stringType,
- compiler.commonMasks.uint31Type]);
+ runTest(
+ TEST_12,
+ (compiler) =>
+ [compiler.commonMasks.stringType, compiler.commonMasks.uint31Type]);
runTest(TEST_13, (compiler) => [compiler.commonMasks.numType]);
- runTest(TEST_14, (compiler) => [compiler.commonMasks.uint31Type,
- compiler.commonMasks.stringType]);
+ runTest(
+ TEST_14,
+ (compiler) =>
+ [compiler.commonMasks.uint31Type, compiler.commonMasks.stringType]);
- runTest(TEST_15, (compiler) => [compiler.commonMasks.stringType,
- compiler.commonMasks.boolType]);
+ runTest(
+ TEST_15,
+ (compiler) =>
+ [compiler.commonMasks.stringType, compiler.commonMasks.boolType]);
- runTest(TEST_16, (compiler) => [compiler.commonMasks.uint31Type,
- compiler.commonMasks.uint31Type,
- compiler.commonMasks.stringType]);
+ runTest(
+ TEST_16,
+ (compiler) => [
+ compiler.commonMasks.uint31Type,
+ compiler.commonMasks.uint31Type,
+ compiler.commonMasks.stringType
+ ]);
- runTest(TEST_17, (compiler) => [compiler.commonMasks.uint31Type,
- compiler.commonMasks.boolType,
- compiler.commonMasks.doubleType]);
+ runTest(
+ TEST_17,
+ (compiler) => [
+ compiler.commonMasks.uint31Type,
+ compiler.commonMasks.boolType,
+ compiler.commonMasks.doubleType
+ ]);
- runTest(TEST_18, (compiler) => [subclassOfInterceptor(compiler),
- subclassOfInterceptor(compiler)]);
+ runTest(
+ TEST_18,
+ (compiler) =>
+ [subclassOfInterceptor(compiler), subclassOfInterceptor(compiler)]);
}
void main() {
diff --git a/tests/compiler/dart2js/check_elements_invariants_test.dart b/tests/compiler/dart2js/check_elements_invariants_test.dart
index 7216a05..e0c5ee5 100644
--- a/tests/compiler/dart2js/check_elements_invariants_test.dart
+++ b/tests/compiler/dart2js/check_elements_invariants_test.dart
@@ -6,24 +6,21 @@
import 'package:async_helper/async_helper.dart';
import 'package:compiler/src/apiimpl.dart';
import 'package:expect/expect.dart';
-import 'package:compiler/src/elements/elements.dart'
- show ClassElement;
+import 'package:compiler/src/elements/elements.dart' show ClassElement;
import 'package:compiler/src/resolution/class_members.dart'
show ClassMemberMixin;
import 'memory_compiler.dart';
-
-const String DART2JS_SOURCE =
- 'pkg/compiler/lib/src/dart2js.dart';
+const String DART2JS_SOURCE = 'pkg/compiler/lib/src/dart2js.dart';
const List<String> DART2JS_OPTIONS = const <String>[
- '--categories=Client,Server',
- '--disable-type-inference'
- ];
+ '--categories=Client,Server',
+ '--disable-type-inference'
+];
Iterable<ClassElement> computeLiveClasses(CompilerImpl compiler) {
return new Set<ClassElement>()
- ..addAll(compiler.resolverWorld.directlyInstantiatedClasses)
- ..addAll(compiler.codegenWorld.directlyInstantiatedClasses);
+ ..addAll(compiler.resolverWorld.directlyInstantiatedClasses)
+ ..addAll(compiler.codegenWorld.directlyInstantiatedClasses);
}
void checkClassInvariants(ClassElement cls) {
@@ -40,7 +37,7 @@
computeLiveClasses(result.compiler).forEach(checkClassInvariants);
}
-void main () {
+void main() {
var uri = Uri.base.resolve(DART2JS_SOURCE);
asyncTest(() => checkElementInvariantsAfterCompiling(uri));
}
diff --git a/tests/compiler/dart2js/check_members_test.dart b/tests/compiler/dart2js/check_members_test.dart
index a8271be..26a5a53 100644
--- a/tests/compiler/dart2js/check_members_test.dart
+++ b/tests/compiler/dart2js/check_members_test.dart
@@ -14,61 +14,61 @@
/// the warnings of each category.
const Map<String, dynamic> TESTS = const {
// Instance methods.
- 'language/check_method_override_test.dart': null,
- 'co19/src/Language/Classes/Instance_Methods/'
- 'override_more_parameters_t01.dart': null,
- 'co19/src/Language/Classes/Instance_Methods/'
- 'override_more_parameters_t02.dart': null,
- 'co19/src/Language/Classes/Instance_Methods/'
- 'override_fewer_parameters_t01.dart': null,
- 'co19/src/Language/Classes/Instance_Methods/'
- 'override_fewer_parameters_t02.dart': null,
- 'co19/src/Language/Classes/Instance_Methods/'
- 'override_named_parameters_t01.dart': null,
- 'co19/src/Language/Classes/Instance_Methods/'
- 'override_named_parameters_t02.dart': null,
- 'co19/src/Language/Classes/Instance_Methods/'
- 'override_named_parameters_t03.dart': null,
- 'co19/src/Language/Classes/Instance_Methods/'
- 'override_named_parameters_t04.dart': null,
- 'co19/src/Language/Classes/Instance_Methods/'
- 'override_named_parameters_t05.dart': null,
- 'co19/src/Language/Classes/Instance_Methods/'
- 'override_named_parameters_t06.dart': null,
- 'co19/src/Language/Classes/Instance_Methods/'
- 'override_subtype_t01.dart': null,
- 'co19/src/Language/Classes/Instance_Methods/'
- 'override_subtype_t02.dart': null,
- 'co19/src/Language/Classes/Instance_Methods/'
- 'override_subtype_t03.dart': null,
- 'co19/src/Language/Classes/Instance_Methods/'
- 'override_subtype_t04.dart': null,
- 'co19/src/Language/Classes/Instance_Methods/'
- 'override_subtype_t05.dart': null,
- 'co19/src/Language/Classes/Instance_Methods/'
- 'override_subtype_t06.dart': null,
- 'co19/src/Language/Classes/Instance_Methods/'
- 'same_name_static_member_in_superclass_t01.dart': null,
- 'co19/src/Language/Classes/Instance_Methods/'
- 'same_name_static_member_in_superclass_t02.dart': null,
- 'co19/src/Language/Classes/Instance_Methods/'
- 'same_name_static_member_in_superclass_t04.dart': null,
- 'co19/src/Language/Classes/Instance_Methods/'
- 'same_name_static_member_in_superclass_t05.dart': null,
- 'co19/src/Language/Classes/Instance_Methods/'
- 'same_name_static_member_in_superclass_t06.dart': null,
- 'co19/src/Language/Classes/Instance_Methods/'
- 'same_name_static_member_in_superclass_t07.dart': null,
- 'co19/src/Language/Classes/Instance_Methods/'
- 'same_name_static_member_in_superclass_t08.dart': null,
- 'co19/src/Language/Classes/Instance_Methods/'
- 'same_name_static_member_in_superclass_t09.dart': null,
+ 'language/check_method_override_test.dart': null,
+ 'co19/src/Language/Classes/Instance_Methods/'
+ 'override_more_parameters_t01.dart': null,
+ 'co19/src/Language/Classes/Instance_Methods/'
+ 'override_more_parameters_t02.dart': null,
+ 'co19/src/Language/Classes/Instance_Methods/'
+ 'override_fewer_parameters_t01.dart': null,
+ 'co19/src/Language/Classes/Instance_Methods/'
+ 'override_fewer_parameters_t02.dart': null,
+ 'co19/src/Language/Classes/Instance_Methods/'
+ 'override_named_parameters_t01.dart': null,
+ 'co19/src/Language/Classes/Instance_Methods/'
+ 'override_named_parameters_t02.dart': null,
+ 'co19/src/Language/Classes/Instance_Methods/'
+ 'override_named_parameters_t03.dart': null,
+ 'co19/src/Language/Classes/Instance_Methods/'
+ 'override_named_parameters_t04.dart': null,
+ 'co19/src/Language/Classes/Instance_Methods/'
+ 'override_named_parameters_t05.dart': null,
+ 'co19/src/Language/Classes/Instance_Methods/'
+ 'override_named_parameters_t06.dart': null,
+ 'co19/src/Language/Classes/Instance_Methods/'
+ 'override_subtype_t01.dart': null,
+ 'co19/src/Language/Classes/Instance_Methods/'
+ 'override_subtype_t02.dart': null,
+ 'co19/src/Language/Classes/Instance_Methods/'
+ 'override_subtype_t03.dart': null,
+ 'co19/src/Language/Classes/Instance_Methods/'
+ 'override_subtype_t04.dart': null,
+ 'co19/src/Language/Classes/Instance_Methods/'
+ 'override_subtype_t05.dart': null,
+ 'co19/src/Language/Classes/Instance_Methods/'
+ 'override_subtype_t06.dart': null,
+ 'co19/src/Language/Classes/Instance_Methods/'
+ 'same_name_static_member_in_superclass_t01.dart': null,
+ 'co19/src/Language/Classes/Instance_Methods/'
+ 'same_name_static_member_in_superclass_t02.dart': null,
+ 'co19/src/Language/Classes/Instance_Methods/'
+ 'same_name_static_member_in_superclass_t04.dart': null,
+ 'co19/src/Language/Classes/Instance_Methods/'
+ 'same_name_static_member_in_superclass_t05.dart': null,
+ 'co19/src/Language/Classes/Instance_Methods/'
+ 'same_name_static_member_in_superclass_t06.dart': null,
+ 'co19/src/Language/Classes/Instance_Methods/'
+ 'same_name_static_member_in_superclass_t07.dart': null,
+ 'co19/src/Language/Classes/Instance_Methods/'
+ 'same_name_static_member_in_superclass_t08.dart': null,
+ 'co19/src/Language/Classes/Instance_Methods/'
+ 'same_name_static_member_in_superclass_t09.dart': null,
// Getters.
- 'co19/src/Language/Classes/Getters/override_t01.dart': null,
- 'co19/src/Language/Classes/Getters/override_t02.dart': null,
- 'co19/src/Language/Classes/Getters/override_t03.dart': null,
- 'co19/src/Language/Classes/Getters/override_t04.dart': null,
+ 'co19/src/Language/Classes/Getters/override_t01.dart': null,
+ 'co19/src/Language/Classes/Getters/override_t02.dart': null,
+ 'co19/src/Language/Classes/Getters/override_t03.dart': null,
+ 'co19/src/Language/Classes/Getters/override_t04.dart': null,
};
void main() {
diff --git a/tests/compiler/dart2js/class_codegen2_test.dart b/tests/compiler/dart2js/class_codegen2_test.dart
index 7b4f479..f85d0f3 100644
--- a/tests/compiler/dart2js/class_codegen2_test.dart
+++ b/tests/compiler/dart2js/class_codegen2_test.dart
@@ -89,10 +89,10 @@
// { a: true, }. Make sure this doesn't happen again.
RegExp danglingComma = new RegExp(r',[ \n]*}');
- asyncTest(() => Future.forEach([TEST_ONE, TEST_TWO, TEST_THREE, TEST_FOUR],
- (test) {
- return compileAll(test).then((generated) {
- Expect.isFalse(danglingComma.hasMatch(generated));
- });
- }));
+ asyncTest(
+ () => Future.forEach([TEST_ONE, TEST_TWO, TEST_THREE, TEST_FOUR], (test) {
+ return compileAll(test).then((generated) {
+ Expect.isFalse(danglingComma.hasMatch(generated));
+ });
+ }));
}
diff --git a/tests/compiler/dart2js/class_codegen_test.dart b/tests/compiler/dart2js/class_codegen_test.dart
index 58c49bd..d744468 100644
--- a/tests/compiler/dart2js/class_codegen_test.dart
+++ b/tests/compiler/dart2js/class_codegen_test.dart
@@ -65,9 +65,11 @@
twoClasses() {
asyncTest(() => compileAll(TEST_ONE).then((generated) {
- Expect.isTrue(generated.contains(new RegExp('A: {[ \n]*"\\^": "Object;"')));
- Expect.isTrue(generated.contains(new RegExp('B: {[ \n]*"\\^": "Object;"')));
- }));
+ Expect.isTrue(
+ generated.contains(new RegExp('A: {[ \n]*"\\^": "Object;"')));
+ Expect.isTrue(
+ generated.contains(new RegExp('B: {[ \n]*"\\^": "Object;"')));
+ }));
}
subClass() {
@@ -82,15 +84,15 @@
fieldTest() {
asyncTest(() => compileAll(TEST_FOUR).then((generated) {
- Expect.isTrue(generated.contains(
- new RegExp('B: {[ \n]*"\\^": "A;y,z,x",[ \n]*static:')));
- }));
+ Expect.isTrue(generated
+ .contains(new RegExp('B: {[ \n]*"\\^": "A;y,z,x",[ \n]*static:')));
+ }));
}
constructor1() {
asyncTest(() => compileAll(TEST_FIVE).then((generated) {
- Expect.isTrue(generated.contains(new RegExp(r"new [$A-Z]+\.A\(a\);")));
- }));
+ Expect.isTrue(generated.contains(new RegExp(r"new [$A-Z]+\.A\(a\);")));
+ }));
}
main() {
diff --git a/tests/compiler/dart2js/class_order_test.dart b/tests/compiler/dart2js/class_order_test.dart
index 26850f0..e3629c1 100644
--- a/tests/compiler/dart2js/class_order_test.dart
+++ b/tests/compiler/dart2js/class_order_test.dart
@@ -37,10 +37,10 @@
RegExp regexp = new RegExp(r"foo\$0?:(.|\n)*bar\$0:(.|\n)*gee\$0:");
asyncTest(() => compileAll(TEST_ONE).then((generated) {
- Expect.isTrue(regexp.hasMatch(generated));
- }));
+ Expect.isTrue(regexp.hasMatch(generated));
+ }));
asyncTest(() => compileAll(TEST_TWO).then((generated) {
- Expect.isTrue(regexp.hasMatch(generated));
- }));
+ Expect.isTrue(regexp.hasMatch(generated));
+ }));
}
diff --git a/tests/compiler/dart2js/class_set_test.dart b/tests/compiler/dart2js/class_set_test.dart
index 1d3b04f..52f436f 100644
--- a/tests/compiler/dart2js/class_set_test.dart
+++ b/tests/compiler/dart2js/class_set_test.dart
@@ -9,8 +9,7 @@
import 'package:expect/expect.dart';
import 'package:async_helper/async_helper.dart';
import 'type_test_helper.dart';
-import 'package:compiler/src/elements/elements.dart'
- show Element, ClassElement;
+import 'package:compiler/src/elements/elements.dart' show Element, ClassElement;
import 'package:compiler/src/universe/class_set.dart';
import 'package:compiler/src/util/enumset.dart';
import 'package:compiler/src/util/util.dart';
@@ -24,7 +23,8 @@
}
testIterators() async {
- var env = await TypeEnvironment.create(r"""
+ var env = await TypeEnvironment.create(
+ r"""
/// A
/// / \
/// B C
@@ -39,7 +39,7 @@
class F extends C {}
class G extends C {}
""",
- mainSource: r"""
+ mainSource: r"""
main() {
new A();
new C();
@@ -61,8 +61,7 @@
ClassElement G = env.getElement("G");
void checkClass(ClassElement cls,
- {bool directlyInstantiated: false,
- bool indirectlyInstantiated: false}) {
+ {bool directlyInstantiated: false, bool indirectlyInstantiated: false}) {
ClassHierarchyNode node = world.getClassHierarchyNode(cls);
Expect.isNotNull(node, "Expected ClassHierarchyNode for $cls.");
Expect.equals(
@@ -81,7 +80,6 @@
"$cls.");
}
-
checkClass(A, directlyInstantiated: true, indirectlyInstantiated: true);
checkClass(B, indirectlyInstantiated: true);
checkClass(C, directlyInstantiated: true, indirectlyInstantiated: true);
@@ -92,11 +90,8 @@
ClassHierarchyNodeIterator iterator;
- void checkState(
- ClassElement root,
- {ClassElement currentNode,
- List<List<ClassElement>> stack}) {
-
+ void checkState(ClassElement root,
+ {ClassElement currentNode, List<List<ClassElement>> stack}) {
ClassElement classOf(ClassHierarchyNode node) {
return node != null ? node.cls : null;
}
@@ -115,11 +110,10 @@
sb.write('\n currentNode: $foundCurrentNode');
sb.write('\n stack: $foundStack\n}');
- Expect.equals(root, foundRoot,
- "Expected root $root in $sb.");
+ Expect.equals(root, foundRoot, "Expected root $root in $sb.");
if (currentNode == null) {
- Expect.isNull(iterator.currentNode,
- "Unexpected non-null currentNode in $sb.");
+ Expect.isNull(
+ iterator.currentNode, "Unexpected non-null currentNode in $sb.");
} else {
Expect.isNotNull(foundCurrentNode,
"Expected non-null currentNode ${currentNode} in $sb.");
@@ -127,20 +121,20 @@
"Expected currentNode $currentNode in $sb.");
}
if (stack == null) {
- Expect.isNull(foundStack,
- "Unexpected non-null stack in $sb.");
+ Expect.isNull(foundStack, "Unexpected non-null stack in $sb.");
} else {
- Expect.isNotNull(foundStack,
- "Expected non-null stack ${stack} in $sb.");
- Expect.listEquals(stack, foundStack,
+ Expect.isNotNull(foundStack, "Expected non-null stack ${stack} in $sb.");
+ Expect.listEquals(
+ stack,
+ foundStack,
"Expected stack ${stack}, "
"found ${foundStack} in $sb.");
}
}
iterator = new ClassHierarchyNodeIterable(
- world.getClassHierarchyNode(G),
- ClassHierarchyNode.ALL).iterator;
+ world.getClassHierarchyNode(G), ClassHierarchyNode.ALL)
+ .iterator;
checkState(G, currentNode: null, stack: null);
Expect.isNull(iterator.current);
Expect.isTrue(iterator.moveNext());
@@ -151,9 +145,9 @@
Expect.isNull(iterator.current);
iterator = new ClassHierarchyNodeIterable(
- world.getClassHierarchyNode(G),
- ClassHierarchyNode.ALL,
- includeRoot: false).iterator;
+ world.getClassHierarchyNode(G), ClassHierarchyNode.ALL,
+ includeRoot: false)
+ .iterator;
checkState(G, currentNode: null, stack: null);
Expect.isNull(iterator.current);
Expect.isFalse(iterator.moveNext());
@@ -161,8 +155,8 @@
Expect.isNull(iterator.current);
iterator = new ClassHierarchyNodeIterable(
- world.getClassHierarchyNode(C),
- ClassHierarchyNode.ALL).iterator;
+ world.getClassHierarchyNode(C), ClassHierarchyNode.ALL)
+ .iterator;
checkState(C, currentNode: null, stack: null);
Expect.isNull(iterator.current);
Expect.isTrue(iterator.moveNext());
@@ -182,8 +176,8 @@
Expect.isNull(iterator.current);
iterator = new ClassHierarchyNodeIterable(
- world.getClassHierarchyNode(D),
- ClassHierarchyNode.ALL).iterator;
+ world.getClassHierarchyNode(D), ClassHierarchyNode.ALL)
+ .iterator;
checkState(D, currentNode: null, stack: null);
Expect.isNull(iterator.current);
Expect.isTrue(iterator.moveNext());
@@ -194,8 +188,8 @@
Expect.isNull(iterator.current);
iterator = new ClassHierarchyNodeIterable(
- world.getClassHierarchyNode(B),
- ClassHierarchyNode.ALL).iterator;
+ world.getClassHierarchyNode(B), ClassHierarchyNode.ALL)
+ .iterator;
checkState(B, currentNode: null, stack: null);
Expect.isNull(iterator.current);
Expect.isTrue(iterator.moveNext());
@@ -209,9 +203,9 @@
Expect.isNull(iterator.current);
iterator = new ClassHierarchyNodeIterable(
- world.getClassHierarchyNode(B),
- ClassHierarchyNode.ALL,
- includeRoot: false).iterator;
+ world.getClassHierarchyNode(B), ClassHierarchyNode.ALL,
+ includeRoot: false)
+ .iterator;
checkState(B, currentNode: null, stack: null);
Expect.isNull(iterator.current);
Expect.isTrue(iterator.moveNext());
@@ -224,8 +218,9 @@
iterator = new ClassHierarchyNodeIterable(
world.getClassHierarchyNode(B),
new EnumSet<Instantiation>.fromValues(<Instantiation>[
- Instantiation.DIRECTLY_INSTANTIATED,
- Instantiation.UNINSTANTIATED])).iterator;
+ Instantiation.DIRECTLY_INSTANTIATED,
+ Instantiation.UNINSTANTIATED
+ ])).iterator;
checkState(B, currentNode: null, stack: null);
Expect.isNull(iterator.current);
Expect.isTrue(iterator.moveNext());
@@ -236,8 +231,8 @@
Expect.isNull(iterator.current);
iterator = new ClassHierarchyNodeIterable(
- world.getClassHierarchyNode(A),
- ClassHierarchyNode.ALL).iterator;
+ world.getClassHierarchyNode(A), ClassHierarchyNode.ALL)
+ .iterator;
checkState(A, currentNode: null, stack: null);
Expect.isNull(iterator.current);
Expect.isTrue(iterator.moveNext());
@@ -266,9 +261,9 @@
Expect.isNull(iterator.current);
iterator = new ClassHierarchyNodeIterable(
- world.getClassHierarchyNode(A),
- ClassHierarchyNode.ALL,
- includeRoot: false).iterator;
+ world.getClassHierarchyNode(A), ClassHierarchyNode.ALL,
+ includeRoot: false)
+ .iterator;
checkState(A, currentNode: null, stack: null);
Expect.isNull(iterator.current);
Expect.isTrue(iterator.moveNext());
@@ -296,8 +291,9 @@
iterator = new ClassHierarchyNodeIterable(
world.getClassHierarchyNode(A),
new EnumSet<Instantiation>.fromValues(<Instantiation>[
- Instantiation.DIRECTLY_INSTANTIATED,
- Instantiation.UNINSTANTIATED])).iterator;
+ Instantiation.DIRECTLY_INSTANTIATED,
+ Instantiation.UNINSTANTIATED
+ ])).iterator;
checkState(A, currentNode: null, stack: null);
Expect.isNull(iterator.current);
Expect.isTrue(iterator.moveNext());
@@ -323,11 +319,13 @@
Expect.isNull(iterator.current);
iterator = new ClassHierarchyNodeIterable(
- world.getClassHierarchyNode(A),
- new EnumSet<Instantiation>.fromValues(<Instantiation>[
- Instantiation.DIRECTLY_INSTANTIATED,
- Instantiation.UNINSTANTIATED]),
- includeRoot: false).iterator;
+ world.getClassHierarchyNode(A),
+ new EnumSet<Instantiation>.fromValues(<Instantiation>[
+ Instantiation.DIRECTLY_INSTANTIATED,
+ Instantiation.UNINSTANTIATED
+ ]),
+ includeRoot: false)
+ .iterator;
checkState(A, currentNode: null, stack: null);
Expect.isNull(iterator.current);
Expect.isTrue(iterator.moveNext());
@@ -351,7 +349,8 @@
}
testForEach() async {
- var env = await TypeEnvironment.create(r"""
+ var env = await TypeEnvironment.create(
+ r"""
/// A
/// / \
/// B C
@@ -371,7 +370,7 @@
class I extends F {}
class X {}
""",
- mainSource: r"""
+ mainSource: r"""
main() {
new A();
new C();
@@ -404,7 +403,9 @@
visited.add(cls);
}, ClassHierarchyNode.ALL);
- Expect.listEquals(expected, visited,
+ Expect.listEquals(
+ expected,
+ visited,
"Unexpected classes on $cls.forEachSubclass:\n"
"Actual: $visited, expected: $expected\n$classSet");
@@ -414,7 +415,9 @@
return IterationStep.CONTINUE;
}, ClassHierarchyNode.ALL);
- Expect.listEquals(expected, visited,
+ Expect.listEquals(
+ expected,
+ visited,
"Unexpected classes on $cls.forEachSubclass:\n"
"Actual: $visited, expected: $expected\n$classSet");
}
@@ -437,7 +440,9 @@
visited.add(cls);
}, ClassHierarchyNode.ALL);
- Expect.listEquals(expected, visited,
+ Expect.listEquals(
+ expected,
+ visited,
"Unexpected classes on $cls.forEachSubtype:\n"
"Actual: $visited, expected: $expected\n$classSet");
@@ -447,7 +452,9 @@
return IterationStep.CONTINUE;
}, ClassHierarchyNode.ALL);
- Expect.listEquals(expected, visited,
+ Expect.listEquals(
+ expected,
+ visited,
"Unexpected classes on $cls.forEachSubtype:\n"
"Actual: $visited, expected: $expected\n$classSet");
}
@@ -463,14 +470,11 @@
checkForEachSubtype(I, [I]);
checkForEachSubtype(X, [X, A, B, D, C, G, F, I, H, E]);
- void checkForEach(
- ClassElement cls,
- List<ClassElement> expected,
+ void checkForEach(ClassElement cls, List<ClassElement> expected,
{ClassElement stop,
- List<ClassElement> skipSubclasses: const <ClassElement>[],
- bool forEachSubtype: false,
- EnumSet<Instantiation> mask}) {
-
+ List<ClassElement> skipSubclasses: const <ClassElement>[],
+ bool forEachSubtype: false,
+ EnumSet<Instantiation> mask}) {
if (mask == null) {
mask = ClassHierarchyNode.ALL;
}
@@ -494,7 +498,9 @@
classSet.forEachSubclass(visit, mask);
}
- Expect.listEquals(expected, visited,
+ Expect.listEquals(
+ expected,
+ visited,
"Unexpected classes on $cls."
"forEach${forEachSubtype ? 'Subtype' : 'Subclass'} "
"(stop:$stop, skipSubclasses:$skipSubclasses):\n"
@@ -511,7 +517,8 @@
checkForEach(B, [B, D], stop: D, forEachSubtype: true);
checkForEach(B, [B, D, F, G], skipSubclasses: [F], forEachSubtype: true);
checkForEach(B, [B, F, I, H, G], skipSubclasses: [B], forEachSubtype: true);
- checkForEach(B, [B, D, F, I, H, G], skipSubclasses: [D], forEachSubtype: true);
+ checkForEach(B, [B, D, F, I, H, G],
+ skipSubclasses: [D], forEachSubtype: true);
checkForEach(X, [X, A, B, D, C, G, F, I, H, E], forEachSubtype: true);
checkForEach(X, [X, A, B, D], stop: D, forEachSubtype: true);
@@ -522,18 +529,12 @@
checkForEach(X, [X, A, B, D, C, G, F, I, H, E],
skipSubclasses: [D], forEachSubtype: true);
checkForEach(X, [A, D, C, G, F, I, H, E],
- forEachSubtype: true,
- mask: ClassHierarchyNode.DIRECTLY_INSTANTIATED);
+ forEachSubtype: true, mask: ClassHierarchyNode.DIRECTLY_INSTANTIATED);
checkForEach(X, [A, B, D, C, G, F, I, H, E],
- forEachSubtype: true,
- mask: ClassHierarchyNode.INSTANTIATED);
+ forEachSubtype: true, mask: ClassHierarchyNode.INSTANTIATED);
- void checkAny(
- ClassElement cls,
- List<ClassElement> expected,
- {ClassElement find,
- bool expectedResult,
- bool anySubtype: false}) {
+ void checkAny(ClassElement cls, List<ClassElement> expected,
+ {ClassElement find, bool expectedResult, bool anySubtype: false}) {
ClassSet classSet = world.getClassSet(cls);
List<ClassElement> visited = <ClassElement>[];
@@ -549,12 +550,16 @@
result = classSet.anySubclass(visit, ClassHierarchyNode.ALL);
}
- Expect.equals(expectedResult, result,
+ Expect.equals(
+ expectedResult,
+ result,
"Unexpected result on $cls."
"any${anySubtype ? 'Subtype' : 'Subclass'} "
"(find:$find).");
- Expect.listEquals(expected, visited,
+ Expect.listEquals(
+ expected,
+ visited,
"Unexpected classes on $cls."
"any${anySubtype ? 'Subtype' : 'Subclass'} "
"(find:$find):\n"
@@ -568,17 +573,13 @@
checkAny(B, [B, D, F, I, H, G], anySubtype: true, expectedResult: false);
checkAny(B, [B, D, F, I, H, G],
find: A, anySubtype: true, expectedResult: false);
- checkAny(B, [B, D],
- find: D, anySubtype: true, expectedResult: true);
- checkAny(B, [B, D, F, I],
- find: I, anySubtype: true, expectedResult: true);
+ checkAny(B, [B, D], find: D, anySubtype: true, expectedResult: true);
+ checkAny(B, [B, D, F, I], find: I, anySubtype: true, expectedResult: true);
checkAny(X, [X, A, B, D, C, G, F, I, H, E],
anySubtype: true, expectedResult: false);
- checkAny(X, [X, A],
- find: A, anySubtype: true, expectedResult: true);
- checkAny(X, [X, A, B, D],
- find: D, anySubtype: true, expectedResult: true);
+ checkAny(X, [X, A], find: A, anySubtype: true, expectedResult: true);
+ checkAny(X, [X, A, B, D], find: D, anySubtype: true, expectedResult: true);
checkAny(X, [X, A, B, D, C, G, F, I],
find: I, anySubtype: true, expectedResult: true);
}
diff --git a/tests/compiler/dart2js/closure_codegen_test.dart b/tests/compiler/dart2js/closure_codegen_test.dart
index ed1ef86..6f947e6 100644
--- a/tests/compiler/dart2js/closure_codegen_test.dart
+++ b/tests/compiler/dart2js/closure_codegen_test.dart
@@ -67,9 +67,9 @@
main() {
asyncTest(() => Future.wait([
- closureInvocation(false, "call"),
- closureInvocation(true, ""),
- closureBailout(false, "call"),
- closureBailout(true, ""),
- ]));
+ closureInvocation(false, "call"),
+ closureInvocation(true, ""),
+ closureBailout(false, "call"),
+ closureBailout(true, ""),
+ ]));
}
diff --git a/tests/compiler/dart2js/closure_tracer_test.dart b/tests/compiler/dart2js/closure_tracer_test.dart
index f8718e4..110ccd4 100644
--- a/tests/compiler/dart2js/closure_tracer_test.dart
+++ b/tests/compiler/dart2js/closure_tracer_test.dart
@@ -154,27 +154,27 @@
Uri uri = new Uri(scheme: 'source');
var compiler = compilerFor(TEST, uri);
asyncTest(() => compiler.run(uri).then((_) {
- var commonMasks = compiler.commonMasks;
- var typesInferrer = compiler.globalInference.typesInferrer;
+ var commonMasks = compiler.commonMasks;
+ var typesInferrer = compiler.globalInference.typesInferrer;
- checkType(String name, type) {
- var element = findElement(compiler, name);
- var mask = typesInferrer.getReturnTypeOfElement(element);
- Expect.equals(type.nullable(), simplify(mask, compiler), name);
- }
+ checkType(String name, type) {
+ var element = findElement(compiler, name);
+ var mask = typesInferrer.getReturnTypeOfElement(element);
+ Expect.equals(type.nullable(), simplify(mask, compiler), name);
+ }
- checkType('testFunctionStatement', commonMasks.uint31Type);
- checkType('testFunctionExpression', commonMasks.uint31Type);
- checkType('testStoredInInstance', commonMasks.uint31Type);
- checkType('testStoredInStatic', commonMasks.uint31Type);
- checkType('testStoredInMapOfList', commonMasks.uint31Type);
- checkType('testStoredInListOfList', commonMasks.uint31Type);
- checkType('testStoredInListOfListUsingInsert', commonMasks.uint31Type);
- checkType('testStoredInListOfListUsingAdd', commonMasks.uint31Type);
- checkType('testPassedInParameter', commonMasks.uint31Type);
- checkType('testStaticClosure1', commonMasks.uint31Type);
- checkType('testStaticClosure2', commonMasks.numType);
- checkType('testStaticClosure3', commonMasks.uint31Type);
- checkType('testStaticClosure4', commonMasks.numType);
- }));
+ checkType('testFunctionStatement', commonMasks.uint31Type);
+ checkType('testFunctionExpression', commonMasks.uint31Type);
+ checkType('testStoredInInstance', commonMasks.uint31Type);
+ checkType('testStoredInStatic', commonMasks.uint31Type);
+ checkType('testStoredInMapOfList', commonMasks.uint31Type);
+ checkType('testStoredInListOfList', commonMasks.uint31Type);
+ checkType('testStoredInListOfListUsingInsert', commonMasks.uint31Type);
+ checkType('testStoredInListOfListUsingAdd', commonMasks.uint31Type);
+ checkType('testPassedInParameter', commonMasks.uint31Type);
+ checkType('testStaticClosure1', commonMasks.uint31Type);
+ checkType('testStaticClosure2', commonMasks.numType);
+ checkType('testStaticClosure3', commonMasks.uint31Type);
+ checkType('testStaticClosure4', commonMasks.numType);
+ }));
}
diff --git a/tests/compiler/dart2js/code_motion_test.dart b/tests/compiler/dart2js/code_motion_test.dart
index ea4036b..69f1800 100644
--- a/tests/compiler/dart2js/code_motion_test.dart
+++ b/tests/compiler/dart2js/code_motion_test.dart
@@ -23,9 +23,9 @@
main() {
asyncTest(() => compile(TEST_ONE, entry: 'foo', check: (String generated) {
- RegExp regexp = new RegExp('a \\+ b');
- Iterator matches = regexp.allMatches(generated).iterator;
- Expect.isTrue(matches.moveNext());
- Expect.isFalse(matches.moveNext());
- }));
+ RegExp regexp = new RegExp('a \\+ b');
+ Iterator matches = regexp.allMatches(generated).iterator;
+ Expect.isTrue(matches.moveNext());
+ Expect.isFalse(matches.moveNext());
+ }));
}
diff --git a/tests/compiler/dart2js/codegen_helper.dart b/tests/compiler/dart2js/codegen_helper.dart
index cd45136..b578c56 100644
--- a/tests/compiler/dart2js/codegen_helper.dart
+++ b/tests/compiler/dart2js/codegen_helper.dart
@@ -14,18 +14,19 @@
Uri libraryRoot = script.resolve('../../../sdk/');
Uri packageRoot = script.resolve('./packages/');
- var provider = new MemorySourceFileProvider({ 'main.dart': code });
+ var provider = new MemorySourceFileProvider({'main.dart': code});
var handler = new FormattingDiagnosticHandler(provider);
Uri uri = Uri.parse('memory:main.dart');
- CompilerImpl compiler = new CompilerImpl(provider,
- const NullCompilerOutput(),
- handler,
- new CompilerOptions.parse(
- entryPoint: uri,
- libraryRoot: libraryRoot,
- packageRoot: packageRoot,
- options: options));
+ CompilerImpl compiler = new CompilerImpl(
+ provider,
+ const NullCompilerOutput(),
+ handler,
+ new CompilerOptions.parse(
+ entryPoint: uri,
+ libraryRoot: libraryRoot,
+ packageRoot: packageRoot,
+ options: options));
return compiler.run(uri).then((success) {
Expect.isTrue(success);
Map<String, String> result = new Map<String, String>();
diff --git a/tests/compiler/dart2js/combinator_hint_test.dart b/tests/compiler/dart2js/combinator_hint_test.dart
index f8b9c26..0518285 100644
--- a/tests/compiler/dart2js/combinator_hint_test.dart
+++ b/tests/compiler/dart2js/combinator_hint_test.dart
@@ -17,38 +17,33 @@
main() {}
""",
-
'hide_local.dart': """
import 'lib.dart' hide Foo;
main() {}
""",
-
'show_package.dart': """
import 'package:pkg/pkg.dart' show Foo;
main() {}
""",
-
'hide_package.dart': """
import 'package:pkg/pkg.dart' hide Foo;
main() {}
""",
-
'lib.dart': '',
-
'pkg/pkg/pkg.dart': '',
};
Future<Compiler> test(Uri entryPoint,
- {bool showPackageWarnings: false,
- bool suppressHints: false,
- int hints: 0,
- Compiler cachedCompiler}) async {
+ {bool showPackageWarnings: false,
+ bool suppressHints: false,
+ int hints: 0,
+ Compiler cachedCompiler}) async {
print('==================================================================');
print('test: $entryPoint showPackageWarnings=$showPackageWarnings '
- 'suppressHints=$suppressHints');
+ 'suppressHints=$suppressHints');
var options = [Flags.analyzeOnly];
if (showPackageWarnings) {
options.add(Flags.showPackageWarnings);
@@ -64,41 +59,36 @@
packageRoot: Uri.parse('memory:pkg/'),
diagnosticHandler: collector,
cachedCompiler: cachedCompiler);
- Expect.equals(0, collector.errors.length,
- 'Unexpected errors: ${collector.errors}');
+ Expect.equals(
+ 0, collector.errors.length, 'Unexpected errors: ${collector.errors}');
Expect.equals(0, collector.warnings.length,
- 'Unexpected warnings: ${collector.warnings}');
- Expect.equals(hints, collector.hints.length,
- 'Unexpected hints: ${collector.hints}');
- Expect.equals(0, collector.infos.length,
- 'Unexpected infos: ${collector.infos}');
+ 'Unexpected warnings: ${collector.warnings}');
+ Expect.equals(
+ hints, collector.hints.length, 'Unexpected hints: ${collector.hints}');
+ Expect.equals(
+ 0, collector.infos.length, 'Unexpected infos: ${collector.infos}');
print('==================================================================');
return result.compiler;
}
Future<Compiler> testUri(Uri entrypoint,
- {bool suppressed: false,
- Compiler cachedCompiler}) async {
- cachedCompiler = await test(
- entrypoint,
+ {bool suppressed: false, Compiler cachedCompiler}) async {
+ cachedCompiler = await test(entrypoint,
showPackageWarnings: true,
suppressHints: false,
hints: 1,
cachedCompiler: cachedCompiler);
- cachedCompiler = await test(
- entrypoint,
+ cachedCompiler = await test(entrypoint,
showPackageWarnings: false,
suppressHints: false,
hints: suppressed ? 0 : 1,
cachedCompiler: cachedCompiler);
- cachedCompiler = await test(
- entrypoint,
+ cachedCompiler = await test(entrypoint,
showPackageWarnings: true,
suppressHints: true,
hints: 0,
cachedCompiler: cachedCompiler);
- cachedCompiler = await test(
- entrypoint,
+ cachedCompiler = await test(entrypoint,
showPackageWarnings: false,
suppressHints: true,
hints: 0,
@@ -108,18 +98,13 @@
void main() {
asyncTest(() async {
- Compiler cachedCompiler = await testUri(
- Uri.parse('memory:show_local.dart'));
- cachedCompiler = await testUri(
- Uri.parse('memory:hide_local.dart'),
+ Compiler cachedCompiler =
+ await testUri(Uri.parse('memory:show_local.dart'));
+ cachedCompiler = await testUri(Uri.parse('memory:hide_local.dart'),
cachedCompiler: cachedCompiler);
- cachedCompiler = await testUri(
- Uri.parse('memory:show_package.dart'),
+ cachedCompiler = await testUri(Uri.parse('memory:show_package.dart'),
cachedCompiler: cachedCompiler);
- cachedCompiler = await testUri(
- Uri.parse('memory:hide_package.dart'),
- suppressed: true,
- cachedCompiler: cachedCompiler);
+ cachedCompiler = await testUri(Uri.parse('memory:hide_package.dart'),
+ suppressed: true, cachedCompiler: cachedCompiler);
});
}
-
diff --git a/tests/compiler/dart2js/command_line_split_test.dart b/tests/compiler/dart2js/command_line_split_test.dart
index 574e340..f4a2f43 100644
--- a/tests/compiler/dart2js/command_line_split_test.dart
+++ b/tests/compiler/dart2js/command_line_split_test.dart
@@ -13,30 +13,40 @@
Expect.listEquals(["foo\\", "bar"], splitLine(r"foo\ bar", windows: true));
Expect.listEquals(["foo'", '"bar'], splitLine(r"""foo\' \"bar"""));
- Expect.listEquals(["foo\\'", '"bar'],
- splitLine(r"""foo\' \"bar""", windows: true));
+ Expect.listEquals(
+ ["foo\\'", '"bar'], splitLine(r"""foo\' \"bar""", windows: true));
Expect.listEquals(["foo'", '"bar'], splitLine(r"""foo"'" '"'bar"""));
Expect.throws(() => splitLine(r"""foo"'" '"'bar""", windows: true),
- (e) => e is FormatException);
- Expect.listEquals(["foo'", "''bar"],
- splitLine(r"""foo"'" '"'bar" """, windows: true));
+ (e) => e is FormatException);
+ Expect.listEquals(
+ ["foo'", "''bar"], splitLine(r"""foo"'" '"'bar" """, windows: true));
Expect.listEquals(["foo", "bar"], splitLine("'f''o''o' " + '"b""a""r"'));
// TODO(johnniwinther): This is not actual Windows behavior: "b""a" is
// interpreted as b"a but "b""a""r" is interpreted as b"ar.
Expect.listEquals(["'f''o''o'", "bar"],
- splitLine("'f''o''o' " + '"b""a""r"', windows: true));
+ splitLine("'f''o''o' " + '"b""a""r"', windows: true));
- Expect.listEquals(["\n", "\r", "\t", "\b", "\f", "\v", "\\",
- "a", "Z", "-", '"', "'"],
- splitLine(r"""\n \r \t \b \f \v \\ \a \Z \- \" \'"""));
- Expect.listEquals(["\\n", "\\r", "\\t", "\\b", "\\f", "\\v",
- "\\", "\\a", "\\Z", "\\-", '"', "\\'"],
- splitLine(r"""\n \r \t \b \f \v \\ \a \Z \- \" \'""",
- windows: true));
- Expect.listEquals(["C:Users\foo\bar\baz.dart"],
- splitLine(r"C:\Users\foo\bar\baz.dart"));
+ Expect.listEquals(
+ ["\n", "\r", "\t", "\b", "\f", "\v", "\\", "a", "Z", "-", '"', "'"],
+ splitLine(r"""\n \r \t \b \f \v \\ \a \Z \- \" \'"""));
+ Expect.listEquals([
+ "\\n",
+ "\\r",
+ "\\t",
+ "\\b",
+ "\\f",
+ "\\v",
+ "\\",
+ "\\a",
+ "\\Z",
+ "\\-",
+ '"',
+ "\\'"
+ ], splitLine(r"""\n \r \t \b \f \v \\ \a \Z \- \" \'""", windows: true));
+ Expect.listEquals(
+ ["C:Users\foo\bar\baz.dart"], splitLine(r"C:\Users\foo\bar\baz.dart"));
Expect.listEquals([r"C:\Users\foo\bar\baz.dart"],
splitLine(r"C:\Users\foo\bar\baz.dart", windows: true));
@@ -46,6 +56,6 @@
splitLine(r'"C:\Users\foo\bar\name with spaces.dart"', windows: true));
Expect.throws(() => splitLine(r"\"), (e) => e is FormatException);
- Expect.throws(() => splitLine(r"\", windows: true),
- (e) => e is FormatException);
+ Expect.throws(
+ () => splitLine(r"\", windows: true), (e) => e is FormatException);
}
diff --git a/tests/compiler/dart2js/command_line_test.dart b/tests/compiler/dart2js/command_line_test.dart
index fe2842e..7ccc43d 100644
--- a/tests/compiler/dart2js/command_line_test.dart
+++ b/tests/compiler/dart2js/command_line_test.dart
@@ -19,8 +19,7 @@
await test([], exitCode: 1);
await test(['foo.dart']);
await test([Flags.resolveOnly, 'foo.dart'],
- resolveOnly: true,
- resolutionOutput: Uri.base.resolve('out.data'));
+ resolveOnly: true, resolutionOutput: Uri.base.resolve('out.data'));
await test(['--resolution-input=bar.dart', 'foo.dart'],
resolutionInputs: [Uri.base.resolve('bar.dart')]);
await test([Flags.resolveOnly, '--resolution-input=bar.dart', 'foo.dart'],
@@ -34,9 +33,9 @@
Future test(List<String> arguments,
{int exitCode,
- bool resolveOnly: false,
- Uri resolutionOutput,
- List<Uri> resolutionInputs}) async {
+ bool resolveOnly: false,
+ Uri resolutionOutput,
+ List<Uri> resolutionInputs}) async {
print('--------------------------------------------------------------------');
print('dart2js ${arguments.join(' ')}');
print('--------------------------------------------------------------------');
@@ -62,13 +61,13 @@
Expect.equals(exitCode, actualExitCode, "Unexpected exit code");
if (actualExitCode == null) {
Expect.isNotNull(options, "Missing options object");
- Expect.equals(resolveOnly, options.resolveOnly,
- "Unexpected resolveOnly value");
+ Expect.equals(
+ resolveOnly, options.resolveOnly, "Unexpected resolveOnly value");
Expect.equals(resolutionOutput, options.resolutionOutput,
"Unexpected resolutionOutput value");
if (resolutionInputs == null) {
- Expect.isNull(options.resolutionInputs,
- "Unexpected resolutionInputs value");
+ Expect.isNull(
+ options.resolutionInputs, "Unexpected resolutionInputs value");
} else {
Expect.listEquals(resolutionInputs, options.resolutionInputs,
"Unexpected resolutionInputs value");
@@ -77,4 +76,4 @@
entry.compileFunc = oldCompileFunc;
entry.exitFunc = oldExitFunc;
-}
\ No newline at end of file
+}
diff --git a/tests/compiler/dart2js/compile_with_empty_libraries_test.dart b/tests/compiler/dart2js/compile_with_empty_libraries_test.dart
index 6f6a94a..d16fe9e 100644
--- a/tests/compiler/dart2js/compile_with_empty_libraries_test.dart
+++ b/tests/compiler/dart2js/compile_with_empty_libraries_test.dart
@@ -13,6 +13,6 @@
main() {
Uri uri = new Uri(scheme: 'source');
MockCompiler compiler =
- new MockCompiler.internal(librariesOverride: (_) => '');
+ new MockCompiler.internal(librariesOverride: (_) => '');
asyncTest(() => compiler.run(uri));
}
diff --git a/tests/compiler/dart2js/compiler_helper.dart b/tests/compiler/dart2js/compiler_helper.dart
index 7c77463..ad2c0f7 100644
--- a/tests/compiler/dart2js/compiler_helper.dart
+++ b/tests/compiler/dart2js/compiler_helper.dart
@@ -7,12 +7,10 @@
import 'dart:async';
import "package:expect/expect.dart";
-import 'package:compiler/src/elements/elements.dart'
- as lego;
+import 'package:compiler/src/elements/elements.dart' as lego;
export 'package:compiler/src/elements/elements.dart';
-import 'package:compiler/src/js_backend/js_backend.dart'
- as js;
+import 'package:compiler/src/js_backend/js_backend.dart' as js;
import 'package:compiler/src/commandline_options.dart';
import 'package:compiler/src/common/codegen.dart';
@@ -22,16 +20,13 @@
export 'package:compiler/src/diagnostics/source_span.dart';
export 'package:compiler/src/diagnostics/spannable.dart';
-import 'package:compiler/src/types/types.dart'
- as types;
-export 'package:compiler/src/types/types.dart'
- show TypeMask;
+import 'package:compiler/src/types/types.dart' as types;
+export 'package:compiler/src/types/types.dart' show TypeMask;
import 'package:compiler/src/util/util.dart';
export 'package:compiler/src/util/util.dart';
-import 'package:compiler/src/compiler.dart'
- show Compiler;
+import 'package:compiler/src/compiler.dart' show Compiler;
export 'package:compiler/src/tree/tree.dart';
@@ -50,15 +45,15 @@
/// returning. If [useMock] is `true` the [MockCompiler] is used for
/// compilation, otherwise the memory compiler is used.
Future<String> compile(String code,
- {String entry: 'main',
- bool enableTypeAssertions: false,
- bool minify: false,
- bool analyzeAll: false,
- bool disableInlining: true,
- bool trustJSInteropTypeAnnotations: false,
- bool useMock: false,
- void check(String generatedEntry),
- bool returnAll: false}) async {
+ {String entry: 'main',
+ bool enableTypeAssertions: false,
+ bool minify: false,
+ bool analyzeAll: false,
+ bool disableInlining: true,
+ bool trustJSInteropTypeAnnotations: false,
+ bool useMock: false,
+ void check(String generatedEntry),
+ bool returnAll: false}) async {
OutputCollector outputCollector = returnAll ? new OutputCollector() : null;
if (useMock) {
// TODO(johnniwinther): Remove this when no longer needed by
@@ -77,8 +72,8 @@
lego.Element element = compiler.mainApp.find(entry);
if (element == null) return null;
compiler.phase = Compiler.PHASE_RESOLVING;
- compiler.backend.enqueueHelpers(compiler.enqueuer.resolution,
- compiler.globalDependencies);
+ compiler.backend.enqueueHelpers(
+ compiler.enqueuer.resolution, compiler.globalDependencies);
compiler.processQueue(compiler.enqueuer.resolution, element);
compiler.world.populate();
compiler.backend.onResolutionComplete();
@@ -94,8 +89,7 @@
}
return returnAll ? outputCollector.getOutput('', 'js') : generated;
} else {
- List<String> options = <String>[
- Flags.disableTypeInference];
+ List<String> options = <String>[Flags.disableTypeInference];
if (enableTypeAssertions) {
options.add(Flags.enableCheckedMode);
}
@@ -115,7 +109,7 @@
Map<String, String> source;
if (entry != 'main') {
- source = {'main.dart': "$code\n\nmain() => $entry;" };
+ source = {'main.dart': "$code\n\nmain() => $entry;"};
} else {
source = {'main.dart': code};
}
@@ -125,7 +119,7 @@
options: options,
outputProvider: outputCollector);
Expect.isTrue(result.isSuccess);
- Compiler compiler = result.compiler;
+ Compiler compiler = result.compiler;
lego.Element element = compiler.mainApp.find(entry);
js.JavaScriptBackend backend = compiler.backend;
String generated = backend.getGeneratedCode(element);
@@ -137,45 +131,46 @@
}
Future<String> compileAll(String code,
- {Map<String, String> coreSource,
- bool disableInlining: true,
- bool trustTypeAnnotations: false,
- bool minify: false,
- int expectedErrors,
- int expectedWarnings}) {
+ {Map<String, String> coreSource,
+ bool disableInlining: true,
+ bool trustTypeAnnotations: false,
+ bool minify: false,
+ int expectedErrors,
+ int expectedWarnings}) {
Uri uri = new Uri(scheme: 'source');
OutputCollector outputCollector = new OutputCollector();
- MockCompiler compiler = compilerFor(
- code, uri, coreSource: coreSource, disableInlining: disableInlining,
- minify: minify, expectedErrors: expectedErrors,
+ MockCompiler compiler = compilerFor(code, uri,
+ coreSource: coreSource,
+ disableInlining: disableInlining,
+ minify: minify,
+ expectedErrors: expectedErrors,
trustTypeAnnotations: trustTypeAnnotations,
expectedWarnings: expectedWarnings,
outputProvider: outputCollector);
compiler.diagnosticHandler = createHandler(compiler, code);
return compiler.run(uri).then((compilationSucceded) {
- Expect.isTrue(compilationSucceded,
- 'Unexpected compilation error(s): '
- '${compiler.diagnosticCollector.errors}');
+ Expect.isTrue(
+ compilationSucceded,
+ 'Unexpected compilation error(s): '
+ '${compiler.diagnosticCollector.errors}');
return outputCollector.getOutput('', 'js');
});
}
-Future compileAndCheck(String code,
- String name,
- check(MockCompiler compiler, lego.Element element),
- {int expectedErrors, int expectedWarnings}) {
+Future compileAndCheck(String code, String name,
+ check(MockCompiler compiler, lego.Element element),
+ {int expectedErrors, int expectedWarnings}) {
Uri uri = new Uri(scheme: 'source');
MockCompiler compiler = compilerFor(code, uri,
- expectedErrors: expectedErrors,
- expectedWarnings: expectedWarnings);
+ expectedErrors: expectedErrors, expectedWarnings: expectedWarnings);
return compiler.run(uri).then((_) {
lego.Element element = findElement(compiler, name);
return check(compiler, element);
});
}
-Future compileSources(Map<String, String> sources,
- check(MockCompiler compiler)) {
+Future compileSources(
+ Map<String, String> sources, check(MockCompiler compiler)) {
Uri base = new Uri(scheme: 'source', path: '/');
Uri mainUri = base.resolve('main.dart');
String mainCode = sources['main.dart'];
@@ -203,7 +198,7 @@
}
types.TypeMask findTypeMask(compiler, String name,
- [String how = 'nonNullExact']) {
+ [String how = 'nonNullExact']) {
var sourceName = name;
var element = compiler.mainApp.find(sourceName);
if (element == null) {
@@ -235,7 +230,7 @@
String getIntTypeCheck(String variable) {
return "\\($variable ?!== ?\\($variable ?\\| ?0\\)|"
- "\\($variable ?>>> ?0 ?!== ?$variable";
+ "\\($variable ?>>> ?0 ?!== ?$variable";
}
String getNumberTypeCheck(String variable) {
@@ -252,19 +247,18 @@
}
Future compileAndMatch(String code, String entry, RegExp regexp,
- {bool useMock: false}) {
- return compile(code, entry: entry,
- useMock: useMock,
+ {bool useMock: false}) {
+ return compile(code, entry: entry, useMock: useMock,
check: (String generated) {
- Expect.isTrue(regexp.hasMatch(generated),
- '"$generated" does not match /$regexp/');
+ Expect.isTrue(
+ regexp.hasMatch(generated), '"$generated" does not match /$regexp/');
});
}
Future compileAndDoNotMatch(String code, String entry, RegExp regexp) {
return compile(code, entry: entry, check: (String generated) {
- Expect.isFalse(regexp.hasMatch(generated),
- '"$generated" has a match in /$regexp/');
+ Expect.isFalse(
+ regexp.hasMatch(generated), '"$generated" has a match in /$regexp/');
});
}
diff --git a/tests/compiler/dart2js/concrete_type_inference_test.dart b/tests/compiler/dart2js/concrete_type_inference_test.dart
index 6a142cd..1be4e18 100644
--- a/tests/compiler/dart2js/concrete_type_inference_test.dart
+++ b/tests/compiler/dart2js/concrete_type_inference_test.dart
@@ -7,8 +7,7 @@
import 'package:async_helper/async_helper.dart';
import 'compiler_helper.dart';
-Future compileAndFind(String code, String name,
- check(compiler, element)) {
+Future compileAndFind(String code, String name, check(compiler, element)) {
Uri uri = new Uri(scheme: 'source');
var compiler = compilerFor(code, uri);
return compiler.run(uri).then((_) {
@@ -18,36 +17,26 @@
}
void checkPrintType(String expression, checkType(compiler, type)) {
- asyncTest(() => compileAndFind(
- 'main() { print($expression); }',
- 'print',
- (compiler, printElement) {
- var parameter =
- printElement.functionSignature.requiredParameters.first;
- var type =
- compiler.globalInference.results.typeOf(parameter);
+ asyncTest(() => compileAndFind('main() { print($expression); }', 'print',
+ (compiler, printElement) {
+ var parameter = printElement.functionSignature.requiredParameters.first;
+ var type = compiler.globalInference.results.typeOf(parameter);
+ checkType(compiler, type);
+ }));
+
+ asyncTest(() =>
+ compileAndFind('main() { var x = print; print($expression); }', 'print',
+ (compiler, printElement) {
+ var parameter = printElement.functionSignature.requiredParameters.first;
+ var type = compiler.globalInference.results.typeOf(parameter);
checkType(compiler, type);
}));
asyncTest(() => compileAndFind(
- 'main() { var x = print; print($expression); }',
- 'print',
- (compiler, printElement) {
- var parameter =
- printElement.functionSignature.requiredParameters.first;
- var type =
- compiler.globalInference.results.typeOf(parameter);
- checkType(compiler, type);
- }));
-
- asyncTest(() => compileAndFind(
- 'main() { print($expression); print($expression); }',
- 'print',
- (compiler, printElement) {
- var parameter =
- printElement.functionSignature.requiredParameters.first;
- var type =
- compiler.globalInference.results.typeOf(parameter);
+ 'main() { print($expression); print($expression); }', 'print',
+ (compiler, printElement) {
+ var parameter = printElement.functionSignature.requiredParameters.first;
+ var type = compiler.globalInference.results.typeOf(parameter);
checkType(compiler, type);
}));
}
@@ -77,28 +66,20 @@
}
void testOptionalParameters() {
- compileAndFind(
- 'fisk(a, [b, c]) {} main() { fisk(1); }',
- 'fisk',
+ compileAndFind('fisk(a, [b, c]) {} main() { fisk(1); }', 'fisk',
(compiler, fiskElement) {
- var firstParameter = fiskElement.functionSignature
- .requiredParameters[0];
- var secondParameter = fiskElement.functionSignature
- .optionalParameters[0];
- var thirdParameter = fiskElement.functionSignature
- .optionalParameters[1];
- var commonMasks = compiler.commonMasks;
- var inference = compiler.globalInference;
- Expect.identical(
- commonMasks.uint31Type,
- inference.results.typeOf(firstParameter));
- Expect.identical(
- commonMasks.nullType,
- inference.results.typeOf(secondParameter));
- Expect.identical(
- commonMasks.nullType,
- inference.results.typeOf(thirdParameter));
- });
+ var firstParameter = fiskElement.functionSignature.requiredParameters[0];
+ var secondParameter = fiskElement.functionSignature.optionalParameters[0];
+ var thirdParameter = fiskElement.functionSignature.optionalParameters[1];
+ var commonMasks = compiler.commonMasks;
+ var inference = compiler.globalInference;
+ Expect.identical(
+ commonMasks.uint31Type, inference.results.typeOf(firstParameter));
+ Expect.identical(
+ commonMasks.nullType, inference.results.typeOf(secondParameter));
+ Expect.identical(
+ commonMasks.nullType, inference.results.typeOf(thirdParameter));
+ });
}
void main() {
diff --git a/tests/compiler/dart2js/const_exp_test.dart b/tests/compiler/dart2js/const_exp_test.dart
index f45794c..a903a62 100644
--- a/tests/compiler/dart2js/const_exp_test.dart
+++ b/tests/compiler/dart2js/const_exp_test.dart
@@ -11,7 +11,9 @@
if (expectedOutput == null) {
expectedOutput = constantInitializer;
}
- return () => TypeEnvironment.create("""
+ return () => TypeEnvironment
+ .create(
+ """
class Class<T, S> {
final a;
final b;
@@ -27,79 +29,83 @@
const toplevelConstant = 0;
toplevelFunction() {}
const constant = $constantInitializer;
-""", expectNoWarningsOrErrors: true).then((env) {
- var element = env.getElement('constant');
- Expect.isNotNull(element, "Element 'constant' not found.");
- var constant = element.constant;
- var value = env.compiler.constants.getConstantValue(constant);
- Expect.isNotNull(constant,
- "No constant computed for '$element'.");
- Expect.equals(expectedOutput, constant.toDartText(),
- "Unexpected to string '${constant.toDartText()}' for constant "
- "'$constantInitializer' of value "
- "${value.toStructuredText()}");
- });
+""",
+ expectNoWarningsOrErrors: true)
+ .then((env) {
+ var element = env.getElement('constant');
+ Expect.isNotNull(element, "Element 'constant' not found.");
+ var constant = element.constant;
+ var value = env.compiler.constants.getConstantValue(constant);
+ Expect.isNotNull(constant, "No constant computed for '$element'.");
+ Expect.equals(
+ expectedOutput,
+ constant.toDartText(),
+ "Unexpected to string '${constant.toDartText()}' for constant "
+ "'$constantInitializer' of value "
+ "${value.toStructuredText()}");
+ });
}
void main() {
asyncTest(() => Future.forEach([
- test('null'),
- test('0'),
- test('1.5'),
- test('true'),
- test('false'),
- test('"f"'),
- test('"a" "b"', '"ab"'),
- test('const []'),
- test('const <int>[0, 1]'),
- test('const <dynamic>[0, 1]', 'const [0, 1]'),
- test('const {}'),
- test('const {0: 1, 2: 3}'),
- test('const <String, int>{"0": 1, "2": 3}'),
- test('const <String, dynamic>{"0": 1, "2": 3}'),
- test('const <dynamic, dynamic>{"0": 1, "2": 3}', 'const {"0": 1, "2": 3}'),
- test('const Class(0)'),
- test('const Class(0, b: 1)'),
- test('const Class(0, c: 2)'),
- test('const Class(0, b: 3, c: 4)'),
- test('const Class.named()'),
- test('const Class.named(0)'),
- test('const Class.named(0, 1)'),
- test('const Class.named(0, 1, 2)'),
- test('const Class<String, int>(0)'),
- test('const Class<String, dynamic>(0)'),
- test('const Class<dynamic, String>(0)'),
- test('const Class<dynamic, dynamic>(0)', 'const Class(0)'),
- test('toplevelConstant'),
- test('toplevelFunction'),
- test('Class.staticConstant'),
- test('Class.staticFunction'),
- test('#a'),
- test('1 + 2'),
- test('1 + 2 + 3'),
- test('1 + -2'),
- test('-1 + 2'),
- test('(1 + 2) + 3', '1 + 2 + 3'),
- test('1 + (2 + 3)', '1 + 2 + 3'),
- test('1 * 2'),
- test('1 * 2 + 3'),
- test('1 * (2 + 3)'),
- test('1 + 2 * 3'),
- test('(1 + 2) * 3'),
- test('false || identical(0, 1)'),
- test('!identical(0, 1)'),
- test('!identical(0, 1) || false'),
- test('!(identical(0, 1) || false)'),
- test('identical(0, 1) ? 3 * 4 + 5 : 6 + 7 * 8'),
- test('t ? f ? 0 : 1 : 2'),
- test('(t ? t : f) ? f ? 0 : 1 : 2'),
- test('t ? t : f ? f ? 0 : 1 : 2'),
- test('t ? t ? t : t : t ? t : t'),
- test('t ? (t ? t : t) : (t ? t : t)',
- 't ? t ? t : t : t ? t : t'),
- test('const [const <dynamic, dynamic>{0: true, "1": "c" "d"}, '
- 'const Class(const Class<dynamic, dynamic>(toplevelConstant))]',
- 'const [const {0: true, "1": "cd"}, '
- 'const Class(const Class(toplevelConstant))]'),
- ], (f) => f()));
-}
\ No newline at end of file
+ test('null'),
+ test('0'),
+ test('1.5'),
+ test('true'),
+ test('false'),
+ test('"f"'),
+ test('"a" "b"', '"ab"'),
+ test('const []'),
+ test('const <int>[0, 1]'),
+ test('const <dynamic>[0, 1]', 'const [0, 1]'),
+ test('const {}'),
+ test('const {0: 1, 2: 3}'),
+ test('const <String, int>{"0": 1, "2": 3}'),
+ test('const <String, dynamic>{"0": 1, "2": 3}'),
+ test('const <dynamic, dynamic>{"0": 1, "2": 3}',
+ 'const {"0": 1, "2": 3}'),
+ test('const Class(0)'),
+ test('const Class(0, b: 1)'),
+ test('const Class(0, c: 2)'),
+ test('const Class(0, b: 3, c: 4)'),
+ test('const Class.named()'),
+ test('const Class.named(0)'),
+ test('const Class.named(0, 1)'),
+ test('const Class.named(0, 1, 2)'),
+ test('const Class<String, int>(0)'),
+ test('const Class<String, dynamic>(0)'),
+ test('const Class<dynamic, String>(0)'),
+ test('const Class<dynamic, dynamic>(0)', 'const Class(0)'),
+ test('toplevelConstant'),
+ test('toplevelFunction'),
+ test('Class.staticConstant'),
+ test('Class.staticFunction'),
+ test('#a'),
+ test('1 + 2'),
+ test('1 + 2 + 3'),
+ test('1 + -2'),
+ test('-1 + 2'),
+ test('(1 + 2) + 3', '1 + 2 + 3'),
+ test('1 + (2 + 3)', '1 + 2 + 3'),
+ test('1 * 2'),
+ test('1 * 2 + 3'),
+ test('1 * (2 + 3)'),
+ test('1 + 2 * 3'),
+ test('(1 + 2) * 3'),
+ test('false || identical(0, 1)'),
+ test('!identical(0, 1)'),
+ test('!identical(0, 1) || false'),
+ test('!(identical(0, 1) || false)'),
+ test('identical(0, 1) ? 3 * 4 + 5 : 6 + 7 * 8'),
+ test('t ? f ? 0 : 1 : 2'),
+ test('(t ? t : f) ? f ? 0 : 1 : 2'),
+ test('t ? t : f ? f ? 0 : 1 : 2'),
+ test('t ? t ? t : t : t ? t : t'),
+ test('t ? (t ? t : t) : (t ? t : t)', 't ? t ? t : t : t ? t : t'),
+ test(
+ 'const [const <dynamic, dynamic>{0: true, "1": "c" "d"}, '
+ 'const Class(const Class<dynamic, dynamic>(toplevelConstant))]',
+ 'const [const {0: true, "1": "cd"}, '
+ 'const Class(const Class(toplevelConstant))]'),
+ ], (f) => f()));
+}
diff --git a/tests/compiler/dart2js/constant_expression_evaluate_test.dart b/tests/compiler/dart2js/constant_expression_evaluate_test.dart
index 3dd05ac..a3ab7e2 100644
--- a/tests/compiler/dart2js/constant_expression_evaluate_test.dart
+++ b/tests/compiler/dart2js/constant_expression_evaluate_test.dart
@@ -18,6 +18,7 @@
class TestData {
/// Declarations needed for the [constants].
final String declarations;
+
/// Tested constants.
final List constants;
@@ -27,19 +28,18 @@
class ConstantData {
/// Source code for the constant expression.
final String code;
+
/// Map from environment to expected constant value as structured text.
final Map<Map<String, String>, String> expectedValues;
- const ConstantData(this.code,
- this.expectedValues);
+ const ConstantData(this.code, this.expectedValues);
}
class MemoryEnvironment implements Environment {
final Compiler compiler;
final Map<String, String> env;
- MemoryEnvironment(this.compiler,
- [this.env = const <String, String>{}]);
+ MemoryEnvironment(this.compiler, [this.env = const <String, String>{}]);
@override
String readFromEnvironment(String name) => env[name];
@@ -47,57 +47,62 @@
const List<TestData> DATA = const [
const TestData('', const [
- const ConstantData('null', const { const {} : 'NullConstant' }),
- const ConstantData('false', const { const {} : 'BoolConstant(false)' }),
- const ConstantData('true', const { const {} : 'BoolConstant(true)' }),
- const ConstantData('0', const { const {} : 'IntConstant(0)' }),
- const ConstantData('0.0', const { const {} : 'DoubleConstant(0.0)' }),
- const ConstantData('"foo"', const { const {} : 'StringConstant("foo")' }),
- const ConstantData('1 + 2', const { const {} : 'IntConstant(3)' }),
- const ConstantData('-(1)', const { const {} : 'IntConstant(-1)' }),
- const ConstantData('1 == 2', const { const {} : 'BoolConstant(false)' }),
- const ConstantData('1 != 2', const { const {} : 'BoolConstant(true)' }),
- const ConstantData('"foo".length', const { const {} : 'IntConstant(3)' }),
- const ConstantData('identical(0, 1)',
- const { const {} : 'BoolConstant(false)' }),
- const ConstantData('"a" "b"', const { const {} : 'StringConstant("ab")' }),
- const ConstantData(r'"${null}"',
- const { const {} : 'StringConstant("null")' }),
- const ConstantData('identical',
- const { const {} : 'FunctionConstant(identical)' }),
- const ConstantData('true ? 0 : 1', const { const {} : 'IntConstant(0)' }),
- const ConstantData('proxy',
- const { const {} : 'ConstructedConstant(_Proxy())' }),
- const ConstantData('Object', const { const {} : 'TypeConstant(Object)' }),
+ const ConstantData('null', const {const {}: 'NullConstant'}),
+ const ConstantData('false', const {const {}: 'BoolConstant(false)'}),
+ const ConstantData('true', const {const {}: 'BoolConstant(true)'}),
+ const ConstantData('0', const {const {}: 'IntConstant(0)'}),
+ const ConstantData('0.0', const {const {}: 'DoubleConstant(0.0)'}),
+ const ConstantData('"foo"', const {const {}: 'StringConstant("foo")'}),
+ const ConstantData('1 + 2', const {const {}: 'IntConstant(3)'}),
+ const ConstantData('-(1)', const {const {}: 'IntConstant(-1)'}),
+ const ConstantData('1 == 2', const {const {}: 'BoolConstant(false)'}),
+ const ConstantData('1 != 2', const {const {}: 'BoolConstant(true)'}),
+ const ConstantData('"foo".length', const {const {}: 'IntConstant(3)'}),
+ const ConstantData(
+ 'identical(0, 1)', const {const {}: 'BoolConstant(false)'}),
+ const ConstantData('"a" "b"', const {const {}: 'StringConstant("ab")'}),
+ const ConstantData(
+ r'"${null}"', const {const {}: 'StringConstant("null")'}),
+ const ConstantData(
+ 'identical', const {const {}: 'FunctionConstant(identical)'}),
+ const ConstantData('true ? 0 : 1', const {const {}: 'IntConstant(0)'}),
+ const ConstantData(
+ 'proxy', const {const {}: 'ConstructedConstant(_Proxy())'}),
+ const ConstantData('Object', const {const {}: 'TypeConstant(Object)'}),
const ConstantData('const [0, 1]',
- const { const {} : 'ListConstant([IntConstant(0), IntConstant(1)])' }),
+ const {const {}: 'ListConstant([IntConstant(0), IntConstant(1)])'}),
const ConstantData('const <int>[0, 1]', const {
- const {} : 'ListConstant(<int>[IntConstant(0), IntConstant(1)])' }),
- const ConstantData('const {0: 1, 2: 3}',
- const { const {} :
- 'MapConstant({IntConstant(0): IntConstant(1), '
- 'IntConstant(2): IntConstant(3)})' }),
- const ConstantData('const <int, int>{0: 1, 2: 3}',
- const { const {} :
- 'MapConstant(<int, int>{IntConstant(0): IntConstant(1), '
- 'IntConstant(2): IntConstant(3)})' }),
- const ConstantData('const <int, int>{0: 1, 0: 2}',
- const { const {} :
- 'MapConstant(<int, int>{IntConstant(0): IntConstant(2)})' }),
+ const {}: 'ListConstant(<int>[IntConstant(0), IntConstant(1)])'
+ }),
+ const ConstantData('const {0: 1, 2: 3}', const {
+ const {}: 'MapConstant({IntConstant(0): IntConstant(1), '
+ 'IntConstant(2): IntConstant(3)})'
+ }),
+ const ConstantData('const <int, int>{0: 1, 2: 3}', const {
+ const {}: 'MapConstant(<int, int>{IntConstant(0): IntConstant(1), '
+ 'IntConstant(2): IntConstant(3)})'
+ }),
+ const ConstantData('const <int, int>{0: 1, 0: 2}', const {
+ const {}: 'MapConstant(<int, int>{IntConstant(0): IntConstant(2)})'
+ }),
const ConstantData(
- 'const bool.fromEnvironment("foo", defaultValue: false)',
- const { const {} : 'BoolConstant(false)',
- const {'foo': 'true'} : 'BoolConstant(true)'}),
+ 'const bool.fromEnvironment("foo", defaultValue: false)', const {
+ const {}: 'BoolConstant(false)',
+ const {'foo': 'true'}: 'BoolConstant(true)'
+ }),
const ConstantData(
- 'const int.fromEnvironment("foo", defaultValue: 42)',
- const { const {} : 'IntConstant(42)',
- const {'foo': '87'} : 'IntConstant(87)'}),
+ 'const int.fromEnvironment("foo", defaultValue: 42)', const {
+ const {}: 'IntConstant(42)',
+ const {'foo': '87'}: 'IntConstant(87)'
+ }),
const ConstantData(
- 'const String.fromEnvironment("foo", defaultValue: "bar")',
- const { const {} : 'StringConstant("bar")',
- const {'foo': 'foo'} : 'StringConstant("foo")'}),
+ 'const String.fromEnvironment("foo", defaultValue: "bar")', const {
+ const {}: 'StringConstant("bar")',
+ const {'foo': 'foo'}: 'StringConstant("foo")'
+ }),
]),
- const TestData('''
+ const TestData(
+ '''
const a = const bool.fromEnvironment("foo", defaultValue: true);
const b = const int.fromEnvironment("bar", defaultValue: 42);
@@ -117,44 +122,52 @@
final field3 = 99;
const D(a, b) : super(field2: a, field1: b);
}
-''', const [
- const ConstantData('const Object()',
- const { const {} : 'ConstructedConstant(Object())' }),
- const ConstantData('const A()',
- const { const {} : 'ConstructedConstant(A())' }),
- const ConstantData('const B(0)',
- const { const {} : 'ConstructedConstant(B(field1=IntConstant(0)))' }),
- const ConstantData('const B(const A())',
- const { const {} :
- 'ConstructedConstant(B(field1=ConstructedConstant(A())))' }),
- const ConstantData('const C()', const { const {} :
- 'ConstructedConstant(C(field1=IntConstant(42),'
- 'field2=BoolConstant(false)))' }),
- const ConstantData('const C(field1: 87)', const { const {} :
- 'ConstructedConstant(C(field1=IntConstant(87),'
- 'field2=BoolConstant(false)))' }),
- const ConstantData('const C(field2: true)', const { const {} :
- 'ConstructedConstant(C(field1=IntConstant(42),'
- 'field2=BoolConstant(true)))' }),
- const ConstantData('const C.named()', const { const {} :
- 'ConstructedConstant(C(field1=BoolConstant(false),'
- 'field2=BoolConstant(false)))' }),
- const ConstantData('const C.named(87)', const { const {} :
- 'ConstructedConstant(C(field1=IntConstant(87),'
- 'field2=IntConstant(87)))' }),
- const ConstantData('const C(field1: a, field2: b)', const {
- const {} :
- 'ConstructedConstant(C(field1=BoolConstant(true),'
- 'field2=IntConstant(42)))',
- const {'foo': 'false', 'bar': '87'} :
- 'ConstructedConstant(C(field1=BoolConstant(false),'
- 'field2=IntConstant(87)))', }),
- const ConstantData('const D(42, 87)', const { const {} :
- 'ConstructedConstant(D(field1=IntConstant(87),'
- 'field2=IntConstant(42),'
- 'field3=IntConstant(99)))' }),
- ]),
- const TestData('''
+''',
+ const [
+ const ConstantData('const Object()',
+ const {const {}: 'ConstructedConstant(Object())'}),
+ const ConstantData(
+ 'const A()', const {const {}: 'ConstructedConstant(A())'}),
+ const ConstantData('const B(0)',
+ const {const {}: 'ConstructedConstant(B(field1=IntConstant(0)))'}),
+ const ConstantData('const B(const A())', const {
+ const {}: 'ConstructedConstant(B(field1=ConstructedConstant(A())))'
+ }),
+ const ConstantData('const C()', const {
+ const {}: 'ConstructedConstant(C(field1=IntConstant(42),'
+ 'field2=BoolConstant(false)))'
+ }),
+ const ConstantData('const C(field1: 87)', const {
+ const {}: 'ConstructedConstant(C(field1=IntConstant(87),'
+ 'field2=BoolConstant(false)))'
+ }),
+ const ConstantData('const C(field2: true)', const {
+ const {}: 'ConstructedConstant(C(field1=IntConstant(42),'
+ 'field2=BoolConstant(true)))'
+ }),
+ const ConstantData('const C.named()', const {
+ const {}: 'ConstructedConstant(C(field1=BoolConstant(false),'
+ 'field2=BoolConstant(false)))'
+ }),
+ const ConstantData('const C.named(87)', const {
+ const {}: 'ConstructedConstant(C(field1=IntConstant(87),'
+ 'field2=IntConstant(87)))'
+ }),
+ const ConstantData('const C(field1: a, field2: b)', const {
+ const {}: 'ConstructedConstant(C(field1=BoolConstant(true),'
+ 'field2=IntConstant(42)))',
+ const {'foo': 'false', 'bar': '87'}:
+ 'ConstructedConstant(C(field1=BoolConstant(false),'
+ 'field2=IntConstant(87)))',
+ }),
+ const ConstantData('const D(42, 87)', const {
+ const {}: 'ConstructedConstant(D(field1=IntConstant(87),'
+ 'field2=IntConstant(42),'
+ 'field3=IntConstant(99)))'
+ }),
+ ]),
+ const TestData(
+ '''
class A<T> implements B {
final field1;
const A({this.field1:42});
@@ -166,30 +179,32 @@
class C<U> {
const factory C({field1}) = A<B<double>>;
}
-''', const [
- const ConstantData('const A()',
- const { const {} :
- 'ConstructedConstant(A<dynamic>(field1=IntConstant(42)))' }),
- const ConstantData('const A<int>(field1: 87)',
- const { const {} :
- 'ConstructedConstant(A<int>(field1=IntConstant(87)))' }),
- const ConstantData('const B()',
- const { const {} :
- 'ConstructedConstant(A<B<dynamic>>(field1=IntConstant(42)))' }),
- const ConstantData('const B<int>()',
- const { const {} :
- 'ConstructedConstant(A<B<int>>(field1=IntConstant(42)))' }),
- const ConstantData('const B<int>(field1: 87)',
- const { const {} :
- 'ConstructedConstant(A<B<int>>(field1=IntConstant(87)))' }),
- const ConstantData('const C<int>(field1: 87)',
- const { const {} :
- 'ConstructedConstant(A<B<double>>(field1=IntConstant(87)))' }),
- const ConstantData('const B<int>.named()',
- const { const {} :
- 'ConstructedConstant(A<int>(field1=IntConstant(42)))' }),
- ]),
- const TestData('''
+''',
+ const [
+ const ConstantData('const A()', const {
+ const {}: 'ConstructedConstant(A<dynamic>(field1=IntConstant(42)))'
+ }),
+ const ConstantData('const A<int>(field1: 87)', const {
+ const {}: 'ConstructedConstant(A<int>(field1=IntConstant(87)))'
+ }),
+ const ConstantData('const B()', const {
+ const {}: 'ConstructedConstant(A<B<dynamic>>(field1=IntConstant(42)))'
+ }),
+ const ConstantData('const B<int>()', const {
+ const {}: 'ConstructedConstant(A<B<int>>(field1=IntConstant(42)))'
+ }),
+ const ConstantData('const B<int>(field1: 87)', const {
+ const {}: 'ConstructedConstant(A<B<int>>(field1=IntConstant(87)))'
+ }),
+ const ConstantData('const C<int>(field1: 87)', const {
+ const {}: 'ConstructedConstant(A<B<double>>(field1=IntConstant(87)))'
+ }),
+ const ConstantData('const B<int>.named()', const {
+ const {}: 'ConstructedConstant(A<int>(field1=IntConstant(42)))'
+ }),
+ ]),
+ const TestData(
+ '''
const c = const int.fromEnvironment("foo", defaultValue: 5);
const d = const int.fromEnvironment("bar", defaultValue: 10);
@@ -201,18 +216,18 @@
class B extends A {
const B(a) : super(a, a * 2);
}
-''', const [
- const ConstantData('const A(c, d)', const {
- const {} :
- 'ConstructedConstant(A(field=IntConstant(15)))',
- const {'foo': '7', 'bar': '11'} :
- 'ConstructedConstant(A(field=IntConstant(18)))', }),
- const ConstantData('const B(d)', const {
- const {} :
- 'ConstructedConstant(B(field=IntConstant(30)))',
- const {'bar': '42'} :
- 'ConstructedConstant(B(field=IntConstant(126)))', }),
- ]),
+''',
+ const [
+ const ConstantData('const A(c, d)', const {
+ const {}: 'ConstructedConstant(A(field=IntConstant(15)))',
+ const {'foo': '7', 'bar': '11'}:
+ 'ConstructedConstant(A(field=IntConstant(18)))',
+ }),
+ const ConstantData('const B(d)', const {
+ const {}: 'ConstructedConstant(B(field=IntConstant(30)))',
+ const {'bar': '42'}: 'ConstructedConstant(B(field=IntConstant(126)))',
+ }),
+ ]),
];
main() {
@@ -237,13 +252,14 @@
constants.forEach((String name, ConstantData data) {
FieldElement field = library.localLookup(name);
ConstantExpression constant = field.constant;
- data.expectedValues.forEach(
- (Map<String, String> env, String expectedText) {
+ data.expectedValues.forEach((Map<String, String> env, String expectedText) {
Environment environment = new MemoryEnvironment(compiler, env);
ConstantValue value =
constant.evaluate(environment, DART_CONSTANT_SYSTEM);
String valueText = value.toStructuredText();
- Expect.equals(expectedText, valueText,
+ Expect.equals(
+ expectedText,
+ valueText,
"Unexpected value '${valueText}' for contant "
"`${constant.toDartText()}`, expected '${expectedText}'.");
});
diff --git a/tests/compiler/dart2js/constant_expression_test.dart b/tests/compiler/dart2js/constant_expression_test.dart
index 16ec71e..7013167 100644
--- a/tests/compiler/dart2js/constant_expression_test.dart
+++ b/tests/compiler/dart2js/constant_expression_test.dart
@@ -15,6 +15,7 @@
class TestData {
/// Declarations needed for the [constants].
final String declarations;
+
/// Tested constants.
final List constants;
@@ -24,20 +25,21 @@
class ConstantData {
/// Source code for the constant expression.
final String code;
+
/// The expected constant expression kind.
final ConstantExpressionKind kind;
+
/// ConstantExpression.getText() result if different from [code].
final String text;
+
/// The expected instance type for ConstructedConstantExpression.
final String type;
+
/// The expected instance fields for ConstructedConstantExpression.
final Map<String, String> fields;
- const ConstantData(String code,
- this.kind,
- {String text,
- this.type,
- this.fields})
+ const ConstantData(String code, this.kind,
+ {String text, this.type, this.fields})
: this.code = code,
this.text = text != null ? text : code;
}
@@ -58,7 +60,7 @@
const ConstantData('"foo".length', ConstantExpressionKind.STRING_LENGTH),
const ConstantData('identical(0, 1)', ConstantExpressionKind.IDENTICAL),
const ConstantData('"a" "b"', ConstantExpressionKind.CONCATENATE,
- text: '"ab"'),
+ text: '"ab"'),
const ConstantData('identical', ConstantExpressionKind.FUNCTION),
const ConstantData('true ? 0 : 1', ConstantExpressionKind.CONDITIONAL),
const ConstantData('proxy', ConstantExpressionKind.VARIABLE),
@@ -67,19 +69,18 @@
const ConstantData('const [0, 1]', ConstantExpressionKind.LIST),
const ConstantData('const <int>[0, 1]', ConstantExpressionKind.LIST),
const ConstantData('const {0: 1, 2: 3}', ConstantExpressionKind.MAP),
- const ConstantData('const <int, int>{0: 1, 2: 3}',
- ConstantExpressionKind.MAP),
const ConstantData(
- 'const bool.fromEnvironment("foo", defaultValue: false)',
+ 'const <int, int>{0: 1, 2: 3}', ConstantExpressionKind.MAP),
+ const ConstantData('const bool.fromEnvironment("foo", defaultValue: false)',
ConstantExpressionKind.BOOL_FROM_ENVIRONMENT),
- const ConstantData(
- 'const int.fromEnvironment("foo", defaultValue: 42)',
+ const ConstantData('const int.fromEnvironment("foo", defaultValue: 42)',
ConstantExpressionKind.INT_FROM_ENVIRONMENT),
const ConstantData(
'const String.fromEnvironment("foo", defaultValue: "bar")',
ConstantExpressionKind.STRING_FROM_ENVIRONMENT),
]),
- const TestData('''
+ const TestData(
+ '''
class A {
const A();
}
@@ -92,58 +93,54 @@
const C({field1: 42, this.field2: false}) : super(field1);
const C.named([field = false]) : this(field1: field, field2: field);
}
-''', const [
- const ConstantData('const Object()',
- ConstantExpressionKind.CONSTRUCTED,
- type: 'Object', fields: const {}),
- const ConstantData('const A()',
- ConstantExpressionKind.CONSTRUCTED,
- type: 'A', fields: const {}),
- const ConstantData('const B(0)',
- ConstantExpressionKind.CONSTRUCTED,
- type: 'B',
- fields: const {'field(B#field1)': '0'}),
- const ConstantData('const B(const A())',
- ConstantExpressionKind.CONSTRUCTED,
- type: 'B',
- fields: const {'field(B#field1)': 'const A()'}),
- const ConstantData('const C()',
- ConstantExpressionKind.CONSTRUCTED,
- type: 'C',
- fields: const {
- 'field(B#field1)': '42',
- 'field(C#field2)': 'false',
- }),
- const ConstantData('const C(field1: 87)',
- ConstantExpressionKind.CONSTRUCTED,
- type: 'C',
- fields: const {
- 'field(B#field1)': '87',
- 'field(C#field2)': 'false',
- }),
- const ConstantData('const C(field2: true)',
- ConstantExpressionKind.CONSTRUCTED,
- type: 'C',
- fields: const {
- 'field(B#field1)': '42',
- 'field(C#field2)': 'true',
- }),
- const ConstantData('const C.named()',
- ConstantExpressionKind.CONSTRUCTED,
- type: 'C',
- fields: const {
- 'field(B#field1)': 'false',
- 'field(C#field2)': 'false',
- }),
- const ConstantData('const C.named(87)',
- ConstantExpressionKind.CONSTRUCTED,
- type: 'C',
- fields: const {
- 'field(B#field1)': '87',
- 'field(C#field2)': '87',
- }),
- ]),
- const TestData('''
+''',
+ const [
+ const ConstantData('const Object()', ConstantExpressionKind.CONSTRUCTED,
+ type: 'Object', fields: const {}),
+ const ConstantData('const A()', ConstantExpressionKind.CONSTRUCTED,
+ type: 'A', fields: const {}),
+ const ConstantData('const B(0)', ConstantExpressionKind.CONSTRUCTED,
+ type: 'B', fields: const {'field(B#field1)': '0'}),
+ const ConstantData(
+ 'const B(const A())', ConstantExpressionKind.CONSTRUCTED,
+ type: 'B', fields: const {'field(B#field1)': 'const A()'}),
+ const ConstantData('const C()', ConstantExpressionKind.CONSTRUCTED,
+ type: 'C',
+ fields: const {
+ 'field(B#field1)': '42',
+ 'field(C#field2)': 'false',
+ }),
+ const ConstantData(
+ 'const C(field1: 87)', ConstantExpressionKind.CONSTRUCTED,
+ type: 'C',
+ fields: const {
+ 'field(B#field1)': '87',
+ 'field(C#field2)': 'false',
+ }),
+ const ConstantData(
+ 'const C(field2: true)', ConstantExpressionKind.CONSTRUCTED,
+ type: 'C',
+ fields: const {
+ 'field(B#field1)': '42',
+ 'field(C#field2)': 'true',
+ }),
+ const ConstantData(
+ 'const C.named()', ConstantExpressionKind.CONSTRUCTED,
+ type: 'C',
+ fields: const {
+ 'field(B#field1)': 'false',
+ 'field(C#field2)': 'false',
+ }),
+ const ConstantData(
+ 'const C.named(87)', ConstantExpressionKind.CONSTRUCTED,
+ type: 'C',
+ fields: const {
+ 'field(B#field1)': '87',
+ 'field(C#field2)': '87',
+ }),
+ ]),
+ const TestData(
+ '''
class A<T> implements B {
final field1;
const A({this.field1:42});
@@ -157,43 +154,42 @@
class C<U> {
const factory C({field1}) = A<B<double>>;
}
-''', const [
- const ConstantData('const A()', ConstantExpressionKind.CONSTRUCTED,
- type: 'A<dynamic>',
- fields: const {'field(A#field1)': '42'}),
- const ConstantData('const A<int>(field1: 87)',
- ConstantExpressionKind.CONSTRUCTED,
- type: 'A<int>',
- fields: const {'field(A#field1)': '87'}),
- const ConstantData('const B()', ConstantExpressionKind.CONSTRUCTED,
- type: 'A<B<dynamic>>',
- fields: const {
- 'field(A#field1)': '42',
- }),
- const ConstantData('const B<int>()', ConstantExpressionKind.CONSTRUCTED,
- type: 'A<B<int>>',
- fields: const {
- 'field(A#field1)': '42',
- }),
- const ConstantData('const B<int>(field1: 87)',
- ConstantExpressionKind.CONSTRUCTED,
- type: 'A<B<int>>',
- fields: const {
- 'field(A#field1)': '87',
- }),
- const ConstantData('const C<int>(field1: 87)',
- ConstantExpressionKind.CONSTRUCTED,
- type: 'A<B<double>>',
- fields: const {
- 'field(A#field1)': '87',
- }),
- const ConstantData('const B<int>.named()',
- ConstantExpressionKind.CONSTRUCTED,
- type: 'A<int>',
- fields: const {
- 'field(A#field1)': '42',
- }),
- ]),
+''',
+ const [
+ const ConstantData('const A()', ConstantExpressionKind.CONSTRUCTED,
+ type: 'A<dynamic>', fields: const {'field(A#field1)': '42'}),
+ const ConstantData(
+ 'const A<int>(field1: 87)', ConstantExpressionKind.CONSTRUCTED,
+ type: 'A<int>', fields: const {'field(A#field1)': '87'}),
+ const ConstantData('const B()', ConstantExpressionKind.CONSTRUCTED,
+ type: 'A<B<dynamic>>',
+ fields: const {
+ 'field(A#field1)': '42',
+ }),
+ const ConstantData('const B<int>()', ConstantExpressionKind.CONSTRUCTED,
+ type: 'A<B<int>>',
+ fields: const {
+ 'field(A#field1)': '42',
+ }),
+ const ConstantData(
+ 'const B<int>(field1: 87)', ConstantExpressionKind.CONSTRUCTED,
+ type: 'A<B<int>>',
+ fields: const {
+ 'field(A#field1)': '87',
+ }),
+ const ConstantData(
+ 'const C<int>(field1: 87)', ConstantExpressionKind.CONSTRUCTED,
+ type: 'A<B<double>>',
+ fields: const {
+ 'field(A#field1)': '87',
+ }),
+ const ConstantData(
+ 'const B<int>.named()', ConstantExpressionKind.CONSTRUCTED,
+ type: 'A<int>',
+ fields: const {
+ 'field(A#field1)': '42',
+ }),
+ ]),
];
main() {
@@ -212,35 +208,44 @@
sb.write('main() {}\n');
String source = sb.toString();
CompilationResult result = await runCompiler(
- memorySourceFiles: {'main.dart': source},
- options: ['--analyze-all']);
+ memorySourceFiles: {'main.dart': source}, options: ['--analyze-all']);
Compiler compiler = result.compiler;
var library = compiler.mainApp;
constants.forEach((String name, ConstantData data) {
FieldElement field = library.localLookup(name);
var constant = field.constant;
- Expect.equals(data.kind, constant.kind,
+ Expect.equals(
+ data.kind,
+ constant.kind,
"Unexpected kind '${constant.kind}' for contant "
"`${constant.toDartText()}`, expected '${data.kind}'.");
- Expect.equals(data.text, constant.toDartText(),
+ Expect.equals(
+ data.text,
+ constant.toDartText(),
"Unexpected text '${constant.toDartText()}' for contant, "
"expected '${data.text}'.");
if (data.type != null) {
String instanceType = constant.computeInstanceType().toString();
- Expect.equals(data.type, instanceType,
+ Expect.equals(
+ data.type,
+ instanceType,
"Unexpected type '$instanceType' for contant "
"`${constant.toDartText()}`, expected '${data.type}'.");
}
if (data.fields != null) {
Map instanceFields = constant.computeInstanceFields();
- Expect.equals(data.fields.length, instanceFields.length,
+ Expect.equals(
+ data.fields.length,
+ instanceFields.length,
"Unexpected field count ${instanceFields.length} for contant "
"`${constant.toDartText()}`, expected '${data.fields.length}'.");
instanceFields.forEach((field, expression) {
String name = '$field';
String expression = instanceFields[field].toDartText();
String expected = data.fields[name];
- Expect.equals(expected, expression,
+ Expect.equals(
+ expected,
+ expression,
"Unexpected field expression ${expression} for field '$name' in "
"contant `${constant.toDartText()}`, expected '${expected}'.");
});
diff --git a/tests/compiler/dart2js/constant_folding_codeUnitAt_test.dart b/tests/compiler/dart2js/constant_folding_codeUnitAt_test.dart
index 0bb8f6f..5e2ff3c 100644
--- a/tests/compiler/dart2js/constant_folding_codeUnitAt_test.dart
+++ b/tests/compiler/dart2js/constant_folding_codeUnitAt_test.dart
@@ -35,10 +35,9 @@
main() {
asyncTest(() => Future.wait([
- compileAndMatch(TEST_1, 'foo', new RegExp(r'return 72')),
- compileAndDoNotMatch(TEST_1, 'foo', new RegExp(r'Hello')),
-
- compileAndMatch(TEST_2, 'foo', new RegExp(r'Hello')),
- compileAndMatch(TEST_3, 'foo', new RegExp(r'Hello')),
- ]));
+ compileAndMatch(TEST_1, 'foo', new RegExp(r'return 72')),
+ compileAndDoNotMatch(TEST_1, 'foo', new RegExp(r'Hello')),
+ compileAndMatch(TEST_2, 'foo', new RegExp(r'Hello')),
+ compileAndMatch(TEST_3, 'foo', new RegExp(r'Hello')),
+ ]));
}
diff --git a/tests/compiler/dart2js/constant_folding_test.dart b/tests/compiler/dart2js/constant_folding_test.dart
index 82100cb..0c25553 100644
--- a/tests/compiler/dart2js/constant_folding_test.dart
+++ b/tests/compiler/dart2js/constant_folding_test.dart
@@ -59,38 +59,26 @@
main() {
asyncTest(() => Future.wait([
- compileAndMatch(
- NUMBER_FOLDING, 'main', new RegExp(r"print\(7\)")),
- compileAndMatch(
- NEGATIVE_NUMBER_FOLDING, 'main', new RegExp(r"print\(1\)")),
+ compileAndMatch(NUMBER_FOLDING, 'main', new RegExp(r"print\(7\)")),
+ compileAndMatch(
+ NEGATIVE_NUMBER_FOLDING, 'main', new RegExp(r"print\(1\)")),
+ compile(NULL_EQUALS_FOLDING, entry: 'foo', check: (String generated) {
+ RegExp regexp = new RegExp(r'a == null');
+ Expect.isTrue(regexp.hasMatch(generated));
- compile(NULL_EQUALS_FOLDING, entry: 'foo', check: (String generated) {
- RegExp regexp = new RegExp(r'a == null');
- Expect.isTrue(regexp.hasMatch(generated));
+ regexp = new RegExp(r'null == b');
+ Expect.isTrue(regexp.hasMatch(generated));
- regexp = new RegExp(r'null == b');
- Expect.isTrue(regexp.hasMatch(generated));
+ regexp = new RegExp(r'4 === c');
+ Expect.isTrue(regexp.hasMatch(generated));
- regexp = new RegExp(r'4 === c');
- Expect.isTrue(regexp.hasMatch(generated));
-
- regexp = new RegExp('"foo" === d');
- Expect.isTrue(regexp.hasMatch(generated));
- }),
-
- compileAndMatch(
- LIST_LENGTH_FOLDING, 'foo', new RegExp(r"return 3")),
-
- compileAndMatch(
- LIST_INDEX_FOLDING, 'foo', new RegExp(r"return 1")),
-
- compileAndDoNotMatch(
- LIST_INDEX_FOLDING, 'foo', new RegExp(r"ioore")),
-
- compileAndMatch(
- STRING_LENGTH_FOLDING, 'foo', new RegExp(r"return 3")),
-
- compileAndMatch(
- RANGE_ERROR_INDEX_FOLDING, 'foo', new RegExp(r"ioore")),
- ]));
+ regexp = new RegExp('"foo" === d');
+ Expect.isTrue(regexp.hasMatch(generated));
+ }),
+ compileAndMatch(LIST_LENGTH_FOLDING, 'foo', new RegExp(r"return 3")),
+ compileAndMatch(LIST_INDEX_FOLDING, 'foo', new RegExp(r"return 1")),
+ compileAndDoNotMatch(LIST_INDEX_FOLDING, 'foo', new RegExp(r"ioore")),
+ compileAndMatch(STRING_LENGTH_FOLDING, 'foo', new RegExp(r"return 3")),
+ compileAndMatch(RANGE_ERROR_INDEX_FOLDING, 'foo', new RegExp(r"ioore")),
+ ]));
}
diff --git a/tests/compiler/dart2js/constant_namer_test.dart b/tests/compiler/dart2js/constant_namer_test.dart
index 3e779ad..b59fbf66 100644
--- a/tests/compiler/dart2js/constant_namer_test.dart
+++ b/tests/compiler/dart2js/constant_namer_test.dart
@@ -28,10 +28,10 @@
}
asyncTest(() => compile(TEST_ONE, entry: 'test').then((String generated) {
- check(generated, '.List_12_53.');
- check(generated, '.Token_start_null.');
- check(generated, '.Token_end_null.');
- check(generated, '.Token_yes_12.');
- check(generated, '.Token_true_false.');
- }));
+ check(generated, '.List_12_53.');
+ check(generated, '.Token_start_null.');
+ check(generated, '.Token_end_null.');
+ check(generated, '.Token_yes_12.');
+ check(generated, '.Token_true_false.');
+ }));
}
diff --git a/tests/compiler/dart2js/container_mask_equal_test.dart b/tests/compiler/dart2js/container_mask_equal_test.dart
index e56167b..54e71e1 100644
--- a/tests/compiler/dart2js/container_mask_equal_test.dart
+++ b/tests/compiler/dart2js/container_mask_equal_test.dart
@@ -44,7 +44,7 @@
element = compiler.mainApp.find('d');
var mask4 = typesInferrer.getReturnTypeOfElement(element);
- Expect.notEquals(mask1.union(mask2, compiler.world),
- mask3.union(mask4, compiler.world));
+ Expect.notEquals(
+ mask1.union(mask2, compiler.world), mask3.union(mask4, compiler.world));
});
}
diff --git a/tests/compiler/dart2js/dart2js.status b/tests/compiler/dart2js/dart2js.status
index 1d6f241..9b3a477 100644
--- a/tests/compiler/dart2js/dart2js.status
+++ b/tests/compiler/dart2js/dart2js.status
@@ -6,7 +6,7 @@
compile_with_empty_libraries_test: Fail # Issue 24223
-kernel/binary_operators_test: Fail # Need to support 'is' checks
+kernel/*: Slow, Pass
boolified_operator_test: Fail # Issue 8001
diff --git a/tests/compiler/dart2js/dart2js_batch2_test.dart b/tests/compiler/dart2js/dart2js_batch2_test.dart
index 2bd2495..9aeec1d 100644
--- a/tests/compiler/dart2js/dart2js_batch2_test.dart
+++ b/tests/compiler/dart2js/dart2js_batch2_test.dart
@@ -14,8 +14,8 @@
copyDirectory(Directory sourceDir, Directory destinationDir) {
sourceDir.listSync().forEach((FileSystemEntity element) {
- String newPath = path.join(destinationDir.path,
- path.basename(element.path));
+ String newPath =
+ path.join(destinationDir.path, path.basename(element.path));
if (element is File) {
element.copySync(newPath);
} else if (element is Directory) {
@@ -51,9 +51,8 @@
Future launchDart2Js(_) {
String ext = Platform.isWindows ? '.bat' : '';
- String command =
- path.normalize(path.join(path.fromUri(Platform.script),
- '../../../../sdk/bin/dart2js${ext}'));
+ String command = path.normalize(path.join(
+ path.fromUri(Platform.script), '../../../../sdk/bin/dart2js${ext}'));
print("Running '$command --batch' from '${tmpDir}'.");
return Process.start(command, ['--batch'], workingDirectory: tmpDir.path);
}
@@ -66,21 +65,17 @@
process.stdin.close();
Future<String> output = process.stdout.transform(UTF8.decoder).join();
Future<String> errorOut = process.stderr.transform(UTF8.decoder).join();
- return Future.wait([output, errorOut])
- .then((result) {
- String stdoutOutput = result[0];
- String stderrOutput = result[1];
+ return Future.wait([output, errorOut]).then((result) {
+ String stdoutOutput = result[0];
+ String stderrOutput = result[1];
- Expect.isFalse(stdoutOutput.contains("crashed"));
- });
+ Expect.isFalse(stdoutOutput.contains("crashed"));
+ });
}
void main() {
var tmpDir;
asyncTest(() {
- return setup()
- .then(launchDart2Js)
- .then(runTests)
- .whenComplete(cleanUp);
+ return setup().then(launchDart2Js).then(runTests).whenComplete(cleanUp);
});
}
diff --git a/tests/compiler/dart2js/dart2js_batch_test.dart b/tests/compiler/dart2js/dart2js_batch_test.dart
index 55f8ca7..1d41bf0 100644
--- a/tests/compiler/dart2js/dart2js_batch_test.dart
+++ b/tests/compiler/dart2js/dart2js_batch_test.dart
@@ -16,8 +16,8 @@
copyDirectory(Directory sourceDir, Directory destinationDir) {
sourceDir.listSync().forEach((FileSystemEntity element) {
- String newPath = path.join(destinationDir.path,
- path.basename(element.path));
+ String newPath =
+ path.join(destinationDir.path, path.basename(element.path));
if (element is File) {
element.copySync(newPath);
} else if (element is Directory) {
@@ -72,26 +72,22 @@
process.stdin.close();
Future<String> output = process.stdout.transform(UTF8.decoder).join();
Future<String> errorOut = process.stderr.transform(UTF8.decoder).join();
- return Future.wait([output, errorOut])
- .then((result) {
- String stdoutOutput = result[0];
- String stderrOutput = result[1];
+ return Future.wait([output, errorOut]).then((result) {
+ String stdoutOutput = result[0];
+ String stderrOutput = result[1];
- Expect.equals(4, ">>> EOF STDERR".allMatches(stderrOutput).length);
- Expect.equals(4, ">>>".allMatches(stderrOutput).length);
+ Expect.equals(4, ">>> EOF STDERR".allMatches(stderrOutput).length);
+ Expect.equals(4, ">>>".allMatches(stderrOutput).length);
- Expect.equals(2, ">>> TEST OK".allMatches(stdoutOutput).length);
- Expect.equals(2, ">>> TEST FAIL".allMatches(stdoutOutput).length);
- Expect.equals(4, ">>>".allMatches(stdoutOutput).length);
- });
+ Expect.equals(2, ">>> TEST OK".allMatches(stdoutOutput).length);
+ Expect.equals(2, ">>> TEST FAIL".allMatches(stdoutOutput).length);
+ Expect.equals(4, ">>>".allMatches(stdoutOutput).length);
+ });
}
void main() {
var tmpDir;
asyncTest(() {
- return setup()
- .then(launchDart2Js)
- .then(runTests)
- .whenComplete(cleanUp);
+ return setup().then(launchDart2Js).then(runTests).whenComplete(cleanUp);
});
}
diff --git a/tests/compiler/dart2js/dart2js_resolver_test.dart b/tests/compiler/dart2js/dart2js_resolver_test.dart
index c04da4f..272cccd 100644
--- a/tests/compiler/dart2js/dart2js_resolver_test.dart
+++ b/tests/compiler/dart2js/dart2js_resolver_test.dart
@@ -12,8 +12,6 @@
main() {
asyncTest(() async {
List<Uri> uriList = computeInputUris();
- await resolver.resolve(uriList,
- packageRoot: Uri.base.resolve(Platform.packageRoot),
- platformConfig: "lib/dart_shared.platform");
+ await resolver.resolve(uriList, platformConfig: "lib/dart_shared.platform");
});
-}
\ No newline at end of file
+}
diff --git a/tests/compiler/dart2js/data/exit_code_helper.dart b/tests/compiler/dart2js/data/exit_code_helper.dart
index 52794b1..ab73b3a 100644
--- a/tests/compiler/dart2js/data/exit_code_helper.dart
+++ b/tests/compiler/dart2js/data/exit_code_helper.dart
@@ -1,3 +1 @@
-void main() {
-
-}
\ No newline at end of file
+void main() {}
diff --git a/tests/compiler/dart2js/data/mirrors_helper.dart b/tests/compiler/dart2js/data/mirrors_helper.dart
index 7ffae11..23544c1 100644
--- a/tests/compiler/dart2js/data/mirrors_helper.dart
+++ b/tests/compiler/dart2js/data/mirrors_helper.dart
@@ -8,11 +8,9 @@
library mirrors_helper;
-typedef E Func<E,F extends Foo>(F f);
+typedef E Func<E, F extends Foo>(F f);
-main() {
-
-}
+main() {}
/// Singleline doc comment.
@Metadata(null)
@@ -24,29 +22,26 @@
@Metadata(1.5)
@Metadata("Foo")
@Metadata(const ["Foo"])
-@Metadata(const {'foo':"Foo"})
+@Metadata(const {'foo': "Foo"})
@metadata
/** Multiline doc comment. */
/* Multiline comment. */ class Foo {
m(@metadata a) {}
}
+abstract class Bar<E> {}
-abstract class Bar<E> {
-
-}
-
-class Baz<E,F extends Foo> implements Bar<E> {
+class Baz<E, F extends Foo> implements Bar<E> {
Baz();
const Baz.named();
- factory Baz.factory() => new Baz<E,F>();
+ factory Baz.factory() => new Baz<E, F>();
static method1(e) {}
void method2(E e, [F f = null]) {}
- Baz<E,F> method3(E func1(F f), Func<E,F> func2) => null;
+ Baz<E, F> method3(E func1(F f), Func<E, F> func2) => null;
- bool operator==(Object other) => false;
- int operator-() => 0;
+ bool operator ==(Object other) => false;
+ int operator -() => 0;
operator$foo() {}
}
@@ -75,4 +70,4 @@
class Metadata {
final data;
const Metadata(this.data);
-}
\ No newline at end of file
+}
diff --git a/tests/compiler/dart2js/dead_code_test.dart b/tests/compiler/dart2js/dead_code_test.dart
index e4096c0..eace363 100644
--- a/tests/compiler/dart2js/dead_code_test.dart
+++ b/tests/compiler/dart2js/dead_code_test.dart
@@ -18,6 +18,7 @@
main() {
asyncTest(() => compileAll(TEST).then((generated) {
- Expect.isFalse(generated.contains('return 42'), 'dead code not eliminated');
- }));
+ Expect.isFalse(
+ generated.contains('return 42'), 'dead code not eliminated');
+ }));
}
diff --git a/tests/compiler/dart2js/dead_phi_eliminator_test.dart b/tests/compiler/dart2js/dead_phi_eliminator_test.dart
index a7088d5..6b0b67b 100644
--- a/tests/compiler/dart2js/dead_phi_eliminator_test.dart
+++ b/tests/compiler/dart2js/dead_phi_eliminator_test.dart
@@ -19,7 +19,7 @@
main() {
asyncTest(() => compile(TEST_ONE, entry: 'foo', check: (String generated) {
- RegExp regexp = new RegExp("toBeRemoved");
- Expect.isTrue(!regexp.hasMatch(generated));
- }));
+ RegExp regexp = new RegExp("toBeRemoved");
+ Expect.isTrue(!regexp.hasMatch(generated));
+ }));
}
diff --git a/tests/compiler/dart2js/declare_once_test.dart b/tests/compiler/dart2js/declare_once_test.dart
index 729a5ab..63535eb 100644
--- a/tests/compiler/dart2js/declare_once_test.dart
+++ b/tests/compiler/dart2js/declare_once_test.dart
@@ -12,16 +12,17 @@
// compactness. Test that we don't also declare it at the start of the
// method.
asyncTest(() => compile(
- 'final List a = const ["bar", "baz"];'
- 'int foo() {'
- ' for (int i = 0; i < a.length; i++) {'
- ' print(a[i]);'
- ' }'
- '}',
- entry: 'foo', minify: false).then((String generated) {
- RegExp re = new RegExp(r"var ");
- Expect.isTrue(re.hasMatch(generated));
- print(generated);
- Expect.equals(1, re.allMatches(generated).length);
- }));
+ 'final List a = const ["bar", "baz"];'
+ 'int foo() {'
+ ' for (int i = 0; i < a.length; i++) {'
+ ' print(a[i]);'
+ ' }'
+ '}',
+ entry: 'foo',
+ minify: false).then((String generated) {
+ RegExp re = new RegExp(r"var ");
+ Expect.isTrue(re.hasMatch(generated));
+ print(generated);
+ Expect.equals(1, re.allMatches(generated).length);
+ }));
}
diff --git a/tests/compiler/dart2js/deferred_custom_element_test.dart b/tests/compiler/dart2js/deferred_custom_element_test.dart
index 07851d8..c89ec9a 100644
--- a/tests/compiler/dart2js/deferred_custom_element_test.dart
+++ b/tests/compiler/dart2js/deferred_custom_element_test.dart
@@ -31,7 +31,8 @@
// The main library imports a file defining a custom element.
// Registering this class implicitly causes the constructors to be
// live. Check that this is handled.
-const Map MEMORY_SOURCE_FILES = const {"main.dart": """
+const Map MEMORY_SOURCE_FILES = const {
+ "main.dart": """
import "lib.dart" deferred as a;
import 'dart:html';
@@ -39,7 +40,8 @@
document.registerElement("foo-tag", a.a);
a.foo();
}
-""", "lib.dart": """
+""",
+ "lib.dart": """
import 'dart:html';
var a = CustomType;
@@ -49,4 +51,5 @@
}
foo() {}
-""",};
+""",
+};
diff --git a/tests/compiler/dart2js/deferred_dont_inline_deferred_constants_test.dart b/tests/compiler/dart2js/deferred_dont_inline_deferred_constants_test.dart
index ae6fd61..6fd44b1 100644
--- a/tests/compiler/dart2js/deferred_dont_inline_deferred_constants_test.dart
+++ b/tests/compiler/dart2js/deferred_dont_inline_deferred_constants_test.dart
@@ -15,8 +15,7 @@
asyncTest(() async {
OutputCollector collector = new OutputCollector();
CompilationResult result = await runCompiler(
- memorySourceFiles: MEMORY_SOURCE_FILES,
- outputProvider: collector);
+ memorySourceFiles: MEMORY_SOURCE_FILES, outputProvider: collector);
Compiler compiler = result.compiler;
lookupLibrary(name) {
@@ -40,7 +39,7 @@
var fooMain = compiler.mainApp.find("foo");
var ou_lib1_lib2 = outputUnitForElement(fooMain);
- String mainOutput = collector.getOutput("","js");
+ String mainOutput = collector.getOutput("", "js");
String lib1Output = collector.getOutput("out_${ou_lib1.name}", "part.js");
String lib2Output = collector.getOutput("out_${ou_lib2.name}", "part.js");
String lib12Output =
@@ -84,7 +83,8 @@
}
// Make sure that deferred constants are not inlined into the main hunk.
-const Map MEMORY_SOURCE_FILES = const {"main.dart": """
+const Map MEMORY_SOURCE_FILES = const {
+ "main.dart": """
import "dart:async";
import 'lib1.dart' deferred as lib1;
@@ -119,7 +119,8 @@
});
});
}
-""", "lib1.dart": """
+""",
+ "lib1.dart": """
import "main.dart" as main;
const C1 = "string1";
const C2 = 1010;
@@ -133,7 +134,8 @@
print("lib1");
main.foo();
}
-""", "lib2.dart": """
+""",
+ "lib2.dart": """
import "main.dart" as main;
const C4 = "string4";
const C5 = const main.C(1);
@@ -142,4 +144,5 @@
print("lib2");
main.foo();
}
-"""};
+"""
+};
diff --git a/tests/compiler/dart2js/deferred_dont_inline_deferred_globals_test.dart b/tests/compiler/dart2js/deferred_dont_inline_deferred_globals_test.dart
index 46674f0..4bf5bb6 100644
--- a/tests/compiler/dart2js/deferred_dont_inline_deferred_globals_test.dart
+++ b/tests/compiler/dart2js/deferred_dont_inline_deferred_globals_test.dart
@@ -15,8 +15,7 @@
OutputCollector collector = new OutputCollector();
asyncTest(() async {
CompilationResult result = await runCompiler(
- memorySourceFiles: MEMORY_SOURCE_FILES,
- outputProvider: collector);
+ memorySourceFiles: MEMORY_SOURCE_FILES, outputProvider: collector);
Compiler compiler = result.compiler;
lookupLibrary(name) {
return compiler.libraryLoader.lookupLibrary(Uri.parse(name));
@@ -45,7 +44,8 @@
}
// Make sure that deferred constants are not inlined into the main hunk.
-const Map MEMORY_SOURCE_FILES = const {"main.dart": """
+const Map MEMORY_SOURCE_FILES = const {
+ "main.dart": """
import "dart:async";
import 'lib1.dart' deferred as lib1;
@@ -58,8 +58,10 @@
print(lib1.globalVar);
});
}
-""", "lib1.dart": """
+""",
+ "lib1.dart": """
import "main.dart" as main;
final finalVar = "string1";
var globalVar = "string2";
-"""};
+"""
+};
diff --git a/tests/compiler/dart2js/deferred_emit_type_checks_test.dart b/tests/compiler/dart2js/deferred_emit_type_checks_test.dart
index f6df078..97772aa 100644
--- a/tests/compiler/dart2js/deferred_emit_type_checks_test.dart
+++ b/tests/compiler/dart2js/deferred_emit_type_checks_test.dart
@@ -7,8 +7,7 @@
import 'package:async_helper/async_helper.dart';
import 'package:compiler/src/compiler.dart';
-import 'package:compiler/src/js_backend/js_backend.dart'
- show JavaScriptBackend;
+import 'package:compiler/src/js_backend/js_backend.dart' show JavaScriptBackend;
import 'package:expect/expect.dart';
import 'memory_compiler.dart';
import 'output_collector.dart';
@@ -17,14 +16,14 @@
asyncTest(() async {
OutputCollector collector = new OutputCollector();
CompilationResult result = await runCompiler(
- memorySourceFiles: MEMORY_SOURCE_FILES,
- outputProvider: collector);
+ memorySourceFiles: MEMORY_SOURCE_FILES, outputProvider: collector);
Compiler compiler = result.compiler;
String mainOutput = collector.getOutput('', 'js');
- String deferredOutput = collector.getOutput('out_1', 'part.js');
+ String deferredOutput = collector.getOutput('out_1', 'part.js');
JavaScriptBackend backend = compiler.backend;
String isPrefix = backend.namer.operatorIsPrefix;
- Expect.isTrue(deferredOutput.contains('${isPrefix}A: 1'),
+ Expect.isTrue(
+ deferredOutput.contains('${isPrefix}A: 1'),
"Deferred output doesn't contain '${isPrefix}A: 1':\n"
"$deferredOutput");
Expect.isFalse(mainOutput.contains('${isPrefix}A: 1'));
@@ -34,7 +33,8 @@
// We force additional runtime type support to be output for A by instantiating
// it with a type argument, and testing for the type. The extra support should
// go to the deferred hunk.
-const Map MEMORY_SOURCE_FILES = const {"main.dart": """
+const Map MEMORY_SOURCE_FILES = const {
+ "main.dart": """
import 'lib.dart' deferred as lib show f, A, instance;
void main() {
@@ -42,7 +42,8 @@
print(lib.f(lib.instance));
});
}
-""", "lib.dart": """
+""",
+ "lib.dart": """
class A<T> {}
class B<T> implements A<T> {}
@@ -52,4 +53,5 @@
bool f (Object o) {
return o is A<A>;
}
-""",};
+""",
+};
diff --git a/tests/compiler/dart2js/deferred_follow_constant_dependencies_test.dart b/tests/compiler/dart2js/deferred_follow_constant_dependencies_test.dart
index 0f10523..4fd0b58 100644
--- a/tests/compiler/dart2js/deferred_follow_constant_dependencies_test.dart
+++ b/tests/compiler/dart2js/deferred_follow_constant_dependencies_test.dart
@@ -32,14 +32,16 @@
backend.constants.compiledConstants.forEach(addConstantWithDependendencies);
for (String stringValue in ["cA", "cB", "cC"]) {
ConstantValue constant = allConstants.firstWhere((constant) {
- return constant.isString
- && constant.primitiveValue.slowToString() == stringValue;
+ return constant.isString &&
+ constant.primitiveValue.slowToString() == stringValue;
});
Expect.notEquals(null, outputUnitForConstant(constant),
"Constant value ${constant.toStructuredText()} has no output unit.");
- Expect.notEquals(mainOutputUnit, outputUnitForConstant(constant),
+ Expect.notEquals(
+ mainOutputUnit,
+ outputUnitForConstant(constant),
"Constant value ${constant.toStructuredText()} "
- "is in the main output unit.");
+ "is in the main output unit.");
}
});
}
@@ -54,17 +56,20 @@
// lib1 and lib2 also import lib4 deferred, but lib1 uses lib4.bar1 and lib2
// uses lib4.bar2. So two output units should be created for lib4, one for each
// import.
-const Map MEMORY_SOURCE_FILES = const {"main.dart": """
+const Map MEMORY_SOURCE_FILES = const {
+ "main.dart": """
import 'lib.dart' deferred as lib;
void main() {
print(lib.L);
}
-""", "lib.dart": """
+""",
+ "lib.dart": """
class C {
final a;
const C(this.a);
}
const L = const {"cA": const C(const {"cB": "cC"})};
-""",};
\ No newline at end of file
+""",
+};
diff --git a/tests/compiler/dart2js/deferred_follow_implicit_super_regression_test.dart b/tests/compiler/dart2js/deferred_follow_implicit_super_regression_test.dart
index b083958..7ec3318 100644
--- a/tests/compiler/dart2js/deferred_follow_implicit_super_regression_test.dart
+++ b/tests/compiler/dart2js/deferred_follow_implicit_super_regression_test.dart
@@ -6,12 +6,11 @@
import 'package:async_helper/async_helper.dart';
import 'memory_compiler.dart';
-import 'package:compiler/src/compiler.dart'
- as dart2js;
+import 'package:compiler/src/compiler.dart' as dart2js;
void main() {
asyncTest(() async {
- CompilationResult result =
+ CompilationResult result =
await runCompiler(memorySourceFiles: MEMORY_SOURCE_FILES);
dart2js.Compiler compiler = result.compiler;
@@ -39,7 +38,7 @@
// Make sure that the implicit references to supers are found by the deferred
// loading dependency mechanism.
const Map MEMORY_SOURCE_FILES = const {
- "main.dart":"""
+ "main.dart": """
import "lib.dart" deferred as lib;
void main() {
@@ -51,7 +50,7 @@
});
}
""",
- "lib.dart":"""
+ "lib.dart": """
a() => print("123");
b() => print("123");
diff --git a/tests/compiler/dart2js/deferred_inline_restrictions_test.dart b/tests/compiler/dart2js/deferred_inline_restrictions_test.dart
index 14d0a7b..6014f36 100644
--- a/tests/compiler/dart2js/deferred_inline_restrictions_test.dart
+++ b/tests/compiler/dart2js/deferred_inline_restrictions_test.dart
@@ -14,8 +14,7 @@
asyncTest(() async {
OutputCollector collector = new OutputCollector();
CompilationResult result = await runCompiler(
- memorySourceFiles: MEMORY_SOURCE_FILES,
- outputProvider: collector);
+ memorySourceFiles: MEMORY_SOURCE_FILES, outputProvider: collector);
Compiler compiler = result.compiler;
lookupLibrary(name) {
@@ -63,7 +62,8 @@
// Make sure that empty functions are inlined and that functions from
// main also are inlined (assuming normal heuristics).
-const Map MEMORY_SOURCE_FILES = const {"main.dart": """
+const Map MEMORY_SOURCE_FILES = const {
+ "main.dart": """
import "dart:async";
import 'lib1.dart' deferred as lib1;
@@ -81,7 +81,8 @@
});
});
}
-""", "lib1.dart": """
+""",
+ "lib1.dart": """
import "main.dart" as main;
import "lib3.dart" as lib3;
@@ -93,12 +94,15 @@
print(main.inlineFromMain("should be inlined"));
print(lib3.sameContextInline("should be inlined"));
}
-""", "lib2.dart": """
+""",
+ "lib2.dart": """
import "lib3.dart" as lib3;
test() {
print(lib3.sameContextInline("should be inlined"));
}
-""", "lib3.dart": """
+""",
+ "lib3.dart": """
sameContextInline(x) => "inline same context" + x;
-"""};
+"""
+};
diff --git a/tests/compiler/dart2js/deferred_load_graph_segmentation2_test.dart b/tests/compiler/dart2js/deferred_load_graph_segmentation2_test.dart
index 52ad4d4..1320fe2 100644
--- a/tests/compiler/dart2js/deferred_load_graph_segmentation2_test.dart
+++ b/tests/compiler/dart2js/deferred_load_graph_segmentation2_test.dart
@@ -37,7 +37,8 @@
// lib1 and lib2 also import lib4 deferred, but lib1 uses lib4.bar1 and lib2
// uses lib4.bar2. So two output units should be created for lib4, one for each
// import.
-const Map MEMORY_SOURCE_FILES = const {"main.dart": """
+const Map MEMORY_SOURCE_FILES = const {
+ "main.dart": """
import "dart:async";
import 'lib.dart' deferred as lib show f1;
@@ -49,7 +50,8 @@
print(lib.f1());
});
}
-""", "lib.dart": """
+""",
+ "lib.dart": """
int f1 () {
return 1;
}
@@ -57,4 +59,5 @@
int f2 () {
return 2;
}
-""",};
+""",
+};
diff --git a/tests/compiler/dart2js/deferred_load_graph_segmentation_test.dart b/tests/compiler/dart2js/deferred_load_graph_segmentation_test.dart
index 9c91d69..5e67cc3 100644
--- a/tests/compiler/dart2js/deferred_load_graph_segmentation_test.dart
+++ b/tests/compiler/dart2js/deferred_load_graph_segmentation_test.dart
@@ -84,7 +84,7 @@
// uses lib4.bar2. So two output units should be created for lib4, one for each
// import.
const Map MEMORY_SOURCE_FILES = const {
- "main.dart":"""
+ "main.dart": """
import "dart:async";
import 'lib1.dart' deferred as lib1;
import 'lib2.dart' deferred as lib2;
@@ -99,7 +99,7 @@
});
}
""",
- "lib1.dart":"""
+ "lib1.dart": """
library lib1;
import "dart:async";
import "dart:html";
@@ -117,7 +117,7 @@
return () {return 1 + l3.foo3();} ();
}
""",
- "lib2.dart":"""
+ "lib2.dart": """
library lib2;
import "dart:async";
import "lib3.dart" as l3;
@@ -130,14 +130,14 @@
return () {return 2+l3.foo3();} ();
}
""",
- "lib3.dart":"""
+ "lib3.dart": """
library lib3;
foo3() {
return () {return 3;} ();
}
""",
- "lib4.dart":"""
+ "lib4.dart": """
library lib4;
bar1() {
diff --git a/tests/compiler/dart2js/deferred_load_mapping_test.dart b/tests/compiler/dart2js/deferred_load_mapping_test.dart
index 34ba2e8..18be4f0 100644
--- a/tests/compiler/dart2js/deferred_load_mapping_test.dart
+++ b/tests/compiler/dart2js/deferred_load_mapping_test.dart
@@ -16,8 +16,7 @@
outputProvider: collector);
CompilerImpl compiler = result.compiler;
// Ensure a mapping file is output.
- Expect.isNotNull(
- collector.getOutput("deferred_map.json", "deferred_map"));
+ Expect.isNotNull(collector.getOutput("deferred_map.json", "deferred_map"));
Map mapping = compiler.deferredLoadTask.computeDeferredMap();
// Test structure of mapping.
@@ -32,7 +31,7 @@
}
const Map MEMORY_SOURCE_FILES = const {
- "main.dart":"""
+ "main.dart": """
import 'dart:convert' deferred as convert;
import 'lib1.dart' deferred as lib1;
import 'lib2.dart' deferred as lib2;
@@ -50,7 +49,7 @@
});
}
""",
- "lib1.dart":"""
+ "lib1.dart": """
library lib1;
import "dart:async";
import "dart:html";
@@ -68,7 +67,7 @@
return () {return 1 + l3.foo3();} ();
}
""",
- "lib2.dart":"""
+ "lib2.dart": """
library lib2;
import "dart:async";
import "lib3.dart" as l3;
@@ -81,14 +80,14 @@
return () {return 2+l3.foo3();} ();
}
""",
- "lib3.dart":"""
+ "lib3.dart": """
library lib3;
foo3() {
return () {return 3;} ();
}
""",
- "lib4.dart":"""
+ "lib4.dart": """
library lib4;
bar1() {
diff --git a/tests/compiler/dart2js/deferred_mirrors_test.dart b/tests/compiler/dart2js/deferred_mirrors_test.dart
index d48550c..6879d56 100644
--- a/tests/compiler/dart2js/deferred_mirrors_test.dart
+++ b/tests/compiler/dart2js/deferred_mirrors_test.dart
@@ -10,8 +10,7 @@
import 'package:expect/expect.dart';
import 'package:async_helper/async_helper.dart';
import 'memory_compiler.dart';
-import 'package:compiler/src/compiler.dart'
- as dart2js;
+import 'package:compiler/src/compiler.dart' as dart2js;
Future runTest(String mainScript, test) async {
CompilationResult result = await runCompiler(
@@ -103,7 +102,7 @@
});
}
""",
- "lib1.dart":"""
+ "lib1.dart": """
library lib1;
import "dart:mirrors";
@@ -114,7 +113,7 @@
mirror.invoke(null, null);
}
""",
- "lib2.dart":"""
+ "lib2.dart": """
library lib2;
@MirrorsUsed(targets: "field2") import "dart:mirrors";
@@ -127,7 +126,7 @@
""",
// The elements C and f are named as targets, but there is no actual use of
// mirrors.
-"main2.dart": """
+ "main2.dart": """
import "lib.dart" deferred as lib;
@MirrorsUsed(targets: const ["C", "f"])
@@ -141,10 +140,10 @@
}
""",
-"lib.dart": """ """,
+ "lib.dart": """ """,
// Lib3 has a MirrorsUsed annotation with a library.
// Check that that is handled correctly.
-"main3.dart": """
+ "main3.dart": """
library main3;
import "lib3.dart" deferred as lib;
@@ -161,7 +160,7 @@
});
}
""",
-"lib3.dart": """
+ "lib3.dart": """
@MirrorsUsed(targets: const ["main3.C"])
import "dart:mirrors";
@@ -170,7 +169,7 @@
}
""",
// Check that exports and imports are handled correctly with mirrors.
-"main4.dart": """
+ "main4.dart": """
library main3;
@MirrorsUsed(targets: const ["lib5.foo","lib6.foo"])
@@ -184,17 +183,17 @@
});
}
""",
-"lib4.dart": """
+ "lib4.dart": """
import "lib5.dart";
export "lib6.dart";
""",
-"lib5.dart": """
+ "lib5.dart": """
library lib5;
foo() {}
""",
-"lib6.dart": """
+ "lib6.dart": """
library lib6;
foo() {}
diff --git a/tests/compiler/dart2js/deferred_not_in_main_test.dart b/tests/compiler/dart2js/deferred_not_in_main_test.dart
index 2955879..9e45223 100644
--- a/tests/compiler/dart2js/deferred_not_in_main_test.dart
+++ b/tests/compiler/dart2js/deferred_not_in_main_test.dart
@@ -18,8 +18,7 @@
void deferredTest1() {
asyncTest(() async {
- CompilationResult result =
- await runCompiler(memorySourceFiles: TEST1);
+ CompilationResult result = await runCompiler(memorySourceFiles: TEST1);
Compiler compiler = result.compiler;
lookupLibrary(name) {
@@ -63,7 +62,7 @@
// lib1 imports lib2 deferred. But mainlib never uses DeferredLibrary.
// Test that this case works.
const Map TEST1 = const {
- "main.dart":"""
+ "main.dart": """
library mainlib;
import 'lib1.dart' as lib1;
@@ -72,7 +71,7 @@
lib1.foo1();
}
""",
- "lib1.dart":"""
+ "lib1.dart": """
library lib1;
import 'lib2.dart' deferred as lib2;
@@ -83,7 +82,7 @@
lib1.loadLibrary().then((_) => lib2.foo2());
}
""",
- "lib2.dart":"""
+ "lib2.dart": """
library lib2;
void foo2() {}
@@ -93,7 +92,7 @@
// main indirectly uses class A from shared. A should still be included in the
// main fragment.
const Map TEST2 = const {
- "main.dart":"""
+ "main.dart": """
import 'def.dart' deferred as def;
import 'shared.dart';
@@ -106,12 +105,12 @@
});
}
""",
- "def.dart":"""
+ "def.dart": """
import 'shared.dart';
toto() { print(new A()); }
""",
- "shared.dart":"""
+ "shared.dart": """
class A {}
class B extends A {}
foo(B b) => null;
diff --git a/tests/compiler/dart2js/diagnose_ambiguous_test.dart b/tests/compiler/dart2js/diagnose_ambiguous_test.dart
index 12e574c..8867a36 100644
--- a/tests/compiler/dart2js/diagnose_ambiguous_test.dart
+++ b/tests/compiler/dart2js/diagnose_ambiguous_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:async_helper/async_helper.dart';
import 'package:compiler/compiler_new.dart' show Diagnostic;
import 'package:expect/expect.dart';
@@ -12,9 +11,9 @@
DiagnosticCollector collector = new DiagnosticCollector();
asyncTest(() async {
CompilationResult result = await runCompiler(
- memorySourceFiles: MEMORY_SOURCE_FILES,
- diagnosticHandler: collector,
- options: ['--analyze-all']);
+ memorySourceFiles: MEMORY_SOURCE_FILES,
+ diagnosticHandler: collector,
+ options: ['--analyze-all']);
List<String> diagnostics = <String>[];
collector.messages.forEach((CollectedMessage message) {
@@ -23,16 +22,16 @@
});
diagnostics.sort();
var expected = [
- "MessageKind.AMBIGUOUS_LOCATION:"
- "memory:exporter.dart:43:47:'hest' is defined here.:info",
- "MessageKind.AMBIGUOUS_LOCATION:"
- "memory:library.dart:41:45:'hest' is defined here.:info",
- "MessageKind.DUPLICATE_IMPORT:"
- "memory:main.dart:86:92:Duplicate import of 'hest'.:warning",
- "MessageKind.IMPORTED_HERE:"
- "memory:main.dart:0:22:'hest' is imported here.:info",
- "MessageKind.IMPORTED_HERE:"
- "memory:main.dart:23:46:'hest' is imported here.:info",
+ "MessageKind.AMBIGUOUS_LOCATION:"
+ "memory:exporter.dart:43:47:'hest' is defined here.:info",
+ "MessageKind.AMBIGUOUS_LOCATION:"
+ "memory:library.dart:41:45:'hest' is defined here.:info",
+ "MessageKind.DUPLICATE_IMPORT:"
+ "memory:main.dart:86:92:Duplicate import of 'hest'.:warning",
+ "MessageKind.IMPORTED_HERE:"
+ "memory:main.dart:0:22:'hest' is imported here.:info",
+ "MessageKind.IMPORTED_HERE:"
+ "memory:main.dart:23:46:'hest' is imported here.:info",
];
Expect.listEquals(expected, diagnostics);
Expect.isTrue(result.isSuccess);
diff --git a/tests/compiler/dart2js/diagnostic_helper.dart b/tests/compiler/dart2js/diagnostic_helper.dart
index d87579f..7d82a3d 100644
--- a/tests/compiler/dart2js/diagnostic_helper.dart
+++ b/tests/compiler/dart2js/diagnostic_helper.dart
@@ -6,12 +6,10 @@
import 'dart:collection';
-import 'package:compiler/compiler_new.dart' show
- CompilerDiagnostics,
- Diagnostic;
-import 'package:compiler/src/diagnostics/messages.dart' show
- Message,
- MessageKind;
+import 'package:compiler/compiler_new.dart'
+ show CompilerDiagnostics, Diagnostic;
+import 'package:compiler/src/diagnostics/messages.dart'
+ show Message, MessageKind;
import 'package:expect/expect.dart';
class CollectedMessage {
@@ -29,7 +27,7 @@
String toString() {
return '${message != null ? message.kind : ''}'
- ':$uri:$begin:$end:$text:$kind';
+ ':$uri:$begin:$end:$text:$kind';
}
}
@@ -37,14 +35,14 @@
List<CollectedMessage> messages = <CollectedMessage>[];
@override
- void report(Message message,
- Uri uri, int begin, int end, String text, Diagnostic kind) {
+ void report(Message message, Uri uri, int begin, int end, String text,
+ Diagnostic kind) {
messages.add(new CollectedMessage(message, uri, begin, end, text, kind));
}
Iterable<CollectedMessage> filterMessagesByKinds(List<Diagnostic> kinds) {
- return messages.where(
- (CollectedMessage message) => kinds.contains(message.kind));
+ return messages
+ .where((CollectedMessage message) => kinds.contains(message.kind));
}
Iterable<CollectedMessage> get errors {
@@ -78,16 +76,16 @@
void checkMessages(List<Expected> expectedMessages) {
int index = 0;
- Iterable<CollectedMessage> messages =
- filterMessagesByKinds(
- [Diagnostic.ERROR,
- Diagnostic.WARNING,
- Diagnostic.HINT,
- Diagnostic.INFO]);
+ Iterable<CollectedMessage> messages = filterMessagesByKinds([
+ Diagnostic.ERROR,
+ Diagnostic.WARNING,
+ Diagnostic.HINT,
+ Diagnostic.INFO
+ ]);
for (CollectedMessage message in messages) {
if (index >= expectedMessages.length) {
Expect.fail("Unexpected messages:\n "
- "${messages.skip(index).join('\n ')}");
+ "${messages.skip(index).join('\n ')}");
} else {
Expected expected = expectedMessages[index];
Expect.equals(expected.messageKind, message.messageKind,
@@ -119,18 +117,14 @@
: this(messageKind, Diagnostic.INFO);
}
-
-void compareWarningKinds(String text,
- List expectedWarnings,
- Iterable<CollectedMessage> foundWarnings) {
+void compareWarningKinds(String text, List expectedWarnings,
+ Iterable<CollectedMessage> foundWarnings) {
compareMessageKinds(text, expectedWarnings, foundWarnings, 'warning');
}
/// [expectedMessages] must be a list of either [MessageKind] or [CheckMessage].
-void compareMessageKinds(String text,
- List expectedMessages,
- Iterable<CollectedMessage> foundMessages,
- String kind) {
+void compareMessageKinds(String text, List expectedMessages,
+ Iterable<CollectedMessage> foundMessages, String kind) {
var fail = (message) => Expect.fail('$text: $message');
HasNextIterator expectedIterator =
new HasNextIterator(expectedMessages.iterator);
@@ -181,7 +175,7 @@
String foundValue = '${message.arguments[key]}';
if (expectedValue != foundValue) {
return 'Expected argument $key with value $expectedValue, '
- 'found $foundValue.';
+ 'found $foundValue.';
}
}
return null;
diff --git a/tests/compiler/dart2js/diagnostic_reporter_helper.dart b/tests/compiler/dart2js/diagnostic_reporter_helper.dart
index 16ff636..679ef8c 100644
--- a/tests/compiler/dart2js/diagnostic_reporter_helper.dart
+++ b/tests/compiler/dart2js/diagnostic_reporter_helper.dart
@@ -15,9 +15,7 @@
DiagnosticReporter get reporter;
@override
- DiagnosticMessage createMessage(
- Spannable spannable,
- MessageKind messageKind,
+ DiagnosticMessage createMessage(Spannable spannable, MessageKind messageKind,
[Map arguments = const {}]) {
return reporter.createMessage(spannable, messageKind, arguments);
}
@@ -36,31 +34,26 @@
DiagnosticOptions get options => reporter.options;
@override
- void reportError(
- DiagnosticMessage message,
- [List<DiagnosticMessage> infos = const <DiagnosticMessage> []]) {
+ void reportError(DiagnosticMessage message,
+ [List<DiagnosticMessage> infos = const <DiagnosticMessage>[]]) {
reporter.reportError(message, infos);
}
@override
- void reportHint(
- DiagnosticMessage message,
- [List<DiagnosticMessage> infos = const <DiagnosticMessage> []]) {
+ void reportHint(DiagnosticMessage message,
+ [List<DiagnosticMessage> infos = const <DiagnosticMessage>[]]) {
reporter.reportHint(message, infos);
}
@override
- void reportInfo(
- Spannable node,
- MessageKind errorCode,
+ void reportInfo(Spannable node, MessageKind errorCode,
[Map arguments = const {}]) {
reporter.reportInfo(node, errorCode, arguments);
}
@override
- void reportWarning(
- DiagnosticMessage message,
- [List<DiagnosticMessage> infos = const <DiagnosticMessage> []]) {
+ void reportWarning(DiagnosticMessage message,
+ [List<DiagnosticMessage> infos = const <DiagnosticMessage>[]]) {
reporter.reportWarning(message, infos);
}
diff --git a/tests/compiler/dart2js/dictionary_types_test.dart b/tests/compiler/dart2js/dictionary_types_test.dart
index afe9db5..2f52323 100644
--- a/tests/compiler/dart2js/dictionary_types_test.dart
+++ b/tests/compiler/dart2js/dictionary_types_test.dart
@@ -8,7 +8,7 @@
import 'compiler_helper.dart' show findElement;
var SOURCES = const {
-'AddAll.dart': """
+ 'AddAll.dart': """
var dictionaryA = {'string': "aString", 'int': 42, 'double': 21.5,
'list': []};
var dictionaryB = {'string': "aString", 'int': 42, 'double': 21.5,
@@ -28,7 +28,7 @@
nullOrInt = dictionaryB['intTwo'];
}
""",
-'Union.dart': """
+ 'Union.dart': """
var dictionaryA = {'string': "aString", 'int': 42, 'double': 21.5,
'list': []};
var dictionaryB = {'string': "aString", 'intTwo': 42, 'list': []};
@@ -44,7 +44,7 @@
doubleOrNull = union['double'];
}
""",
-'ValueType.dart': """
+ 'ValueType.dart': """
var dictionary = {'string': "aString", 'int': 42, 'double': 21.5, 'list': []};
var keyD = 'double';
var keyI = 'int';
@@ -58,7 +58,7 @@
var x = [intOrNull, justNull];
}
""",
-'Propagation.dart': """
+ 'Propagation.dart': """
class A {
A();
foo(value) {
@@ -84,7 +84,7 @@
print(it.foo(dictionary) + 2);
}
""",
-'Bailout.dart': """
+ 'Bailout.dart': """
var dict = makeMap([1,2]);
var notInt = 0;
var alsoNotInt = 0;
@@ -100,7 +100,8 @@
alsoNotInt = dict['goo'];
print("\$notInt and \$alsoNotInt.");
}
-"""};
+"""
+};
void main() {
asyncTest(() async {
@@ -133,9 +134,11 @@
compileAndTest(source, checker, {createCode: false}) async {
CompilationResult result = await runCompiler(
- entryPoint: Uri.parse('memory:'+source),
+ entryPoint: Uri.parse('memory:' + source),
memorySourceFiles: SOURCES,
- beforeRun: (compiler) { compiler.stopAfterTypeInference = !createCode; });
+ beforeRun: (compiler) {
+ compiler.stopAfterTypeInference = !createCode;
+ });
var compiler = result.compiler;
var commonMasks = compiler.commonMasks;
var typesInferrer = compiler.globalInference.typesInferrer;
@@ -143,6 +146,7 @@
var element = findElement(compiler, name);
return typesInferrer.getTypeOfElement(element);
}
+
if (!createCode) {
checker(commonMasks, getType, compiler);
} else {
diff --git a/tests/compiler/dart2js/dump_info_test.dart b/tests/compiler/dart2js/dump_info_test.dart
index 575d6d6..4d55317 100644
--- a/tests/compiler/dart2js/dump_info_test.dart
+++ b/tests/compiler/dart2js/dump_info_test.dart
@@ -8,7 +8,7 @@
import 'package:async_helper/async_helper.dart';
import 'memory_compiler.dart';
-const String TEST_BASIC= r"""
+const String TEST_BASIC = r"""
library main;
int a = 2;
@@ -141,15 +141,14 @@
}));
});
- await jsonTest(TEST_STATICS, (map) {
+ await jsonTest(TEST_STATICS, (map) {
var functions = map['elements']['function'].values;
var classes = map['elements']['class'].values;
Expect.isTrue(functions.any((fn) {
return fn['name'] == 'does_something';
}));
Expect.isTrue(classes.any((cls) {
- return cls['name'] == 'ContainsStatics' &&
- cls['children'].length >= 1;
+ return cls['name'] == 'ContainsStatics' && cls['children'].length >= 1;
}));
});
@@ -157,12 +156,10 @@
var functions = map['elements']['function'].values;
var classes = map['elements']['class'].values;
Expect.isTrue(functions.any((fn) {
- return fn['name'] == 'double' &&
- fn['inlinedCount'] == 1;
+ return fn['name'] == 'double' && fn['inlinedCount'] == 1;
}));
Expect.isTrue(classes.any((cls) {
- return cls['name'] == 'Doubler' &&
- cls['children'].length >= 1;
+ return cls['name'] == 'Doubler' && cls['children'].length >= 1;
}));
});
diff --git a/tests/compiler/dart2js/duplicate_library_test.dart b/tests/compiler/dart2js/duplicate_library_test.dart
index 5a2a708..57800dc 100644
--- a/tests/compiler/dart2js/duplicate_library_test.dart
+++ b/tests/compiler/dart2js/duplicate_library_test.dart
@@ -12,9 +12,8 @@
import 'package:compiler/src/diagnostics/messages.dart' show MessageKind;
import 'memory_compiler.dart';
-void check(String kind,
- Iterable<CollectedMessage> messages,
- List<MessageKind> expectedMessageKinds) {
+void check(String kind, Iterable<CollectedMessage> messages,
+ List<MessageKind> expectedMessageKinds) {
Expect.equals(messages.length, expectedMessageKinds.length,
"Unexpected $kind count: $messages");
int i = 0;
@@ -24,8 +23,8 @@
}
Future test(Map<String, String> source,
- {List<MessageKind> warnings: const <MessageKind>[],
- List<MessageKind> hints: const <MessageKind>[]}) async {
+ {List<MessageKind> warnings: const <MessageKind>[],
+ List<MessageKind> hints: const <MessageKind>[]}) async {
DiagnosticCollector collector = new DiagnosticCollector();
await runCompiler(
memorySourceFiles: source,
@@ -54,8 +53,10 @@
""",
'pkg/lib/foo.dart': """
library lib.foo;
-"""},
- warnings: [MessageKind.DUPLICATED_LIBRARY_RESOURCE]);
+"""
+ }, warnings: [
+ MessageKind.DUPLICATED_LIBRARY_RESOURCE
+ ]);
await test({
'main.dart': """
@@ -71,8 +72,10 @@
""",
'pkg/lib/bar.dart': """
library lib.bar;
-"""},
- warnings: [MessageKind.DUPLICATED_LIBRARY_RESOURCE]);
+"""
+ }, warnings: [
+ MessageKind.DUPLICATED_LIBRARY_RESOURCE
+ ]);
await test({
'main.dart': """
@@ -88,8 +91,10 @@
""",
'pkg/lib/baz.dart': """
library lib.baz;
-"""},
- warnings: [MessageKind.DUPLICATED_LIBRARY_RESOURCE]);
+"""
+ }, warnings: [
+ MessageKind.DUPLICATED_LIBRARY_RESOURCE
+ ]);
await test({
'main.dart': """
@@ -110,8 +115,10 @@
""",
'pkg/lib/boz.dart': """
library lib.boz;
-"""},
- warnings: [MessageKind.DUPLICATED_LIBRARY_RESOURCE]);
+"""
+ }, warnings: [
+ MessageKind.DUPLICATED_LIBRARY_RESOURCE
+ ]);
await test({
'main.dart': """
@@ -122,8 +129,10 @@
""",
'pkg/lib/qux.dart': """
// No library tag.
-"""},
- hints: [MessageKind.DUPLICATED_RESOURCE]);
+"""
+ }, hints: [
+ MessageKind.DUPLICATED_RESOURCE
+ ]);
await test({
'main.dart': """
@@ -137,8 +146,9 @@
""",
'bar.dart': """
library lib;
-"""},
- warnings: [MessageKind.DUPLICATED_LIBRARY_NAME,
- MessageKind.DUPLICATED_LIBRARY_NAME]);
+"""
+ }, warnings: [
+ MessageKind.DUPLICATED_LIBRARY_NAME,
+ MessageKind.DUPLICATED_LIBRARY_NAME
+ ]);
}
-
diff --git a/tests/compiler/dart2js/elide_callthrough_stub_test.dart b/tests/compiler/dart2js/elide_callthrough_stub_test.dart
index bdb9667..6f925b3 100644
--- a/tests/compiler/dart2js/elide_callthrough_stub_test.dart
+++ b/tests/compiler/dart2js/elide_callthrough_stub_test.dart
@@ -39,22 +39,22 @@
main() {
asyncTest(() => compileAll(TEST1).then((generated) {
- // Direct call through field.
- Expect.isTrue(generated.contains(r'this._fun.call$1(zzz)'));
- // No stub.
- Expect.isFalse(generated.contains(r'_fun$1:'));
- // No call to stub.
- Expect.isFalse(generated.contains(r'_fun$1('));
- }));
+ // Direct call through field.
+ Expect.isTrue(generated.contains(r'this._fun.call$1(zzz)'));
+ // No stub.
+ Expect.isFalse(generated.contains(r'_fun$1:'));
+ // No call to stub.
+ Expect.isFalse(generated.contains(r'_fun$1('));
+ }));
asyncTest(() => compileAll(TEST2).then((generated) {
- // No call through field.
- Expect.isFalse(generated.contains(r'this._fun.call$1(zzz)'));
- // Call through stub.
- Expect.isTrue(generated.contains(r'this._fun$1(zzz)'));
- // Stub is generated.
- Expect.isTrue(generated.contains(r'_fun$1:'));
- // Call through getter (inside stub).
- Expect.isTrue(generated.contains(r'get$_fun().call$1'));
- }));
+ // No call through field.
+ Expect.isFalse(generated.contains(r'this._fun.call$1(zzz)'));
+ // Call through stub.
+ Expect.isTrue(generated.contains(r'this._fun$1(zzz)'));
+ // Stub is generated.
+ Expect.isTrue(generated.contains(r'_fun$1:'));
+ // Call through getter (inside stub).
+ Expect.isTrue(generated.contains(r'get$_fun().call$1'));
+ }));
}
diff --git a/tests/compiler/dart2js/embedded_category_api_boundary_test.dart b/tests/compiler/dart2js/embedded_category_api_boundary_test.dart
index 76db27b..042bc37 100644
--- a/tests/compiler/dart2js/embedded_category_api_boundary_test.dart
+++ b/tests/compiler/dart2js/embedded_category_api_boundary_test.dart
@@ -23,9 +23,7 @@
}
});
asyncTest(() async {
- analyze(uriList, {},
- checkResults: checkResults,
- mode: AnalysisMode.MAIN);
+ analyze(uriList, {}, checkResults: checkResults, mode: AnalysisMode.MAIN);
});
}
diff --git a/tests/compiler/dart2js/emit_const_fields_test.dart b/tests/compiler/dart2js/emit_const_fields_test.dart
index 14385d7..3076df7 100644
--- a/tests/compiler/dart2js/emit_const_fields_test.dart
+++ b/tests/compiler/dart2js/emit_const_fields_test.dart
@@ -20,8 +20,7 @@
main() {
asyncTest(() => compileAll(TEST_GUIDE).then((generated) {
- Expect.isTrue(generated.contains("42"));
- Expect.isFalse(generated.contains("TITLE"));
- }));
+ Expect.isTrue(generated.contains("42"));
+ Expect.isFalse(generated.contains("TITLE"));
+ }));
}
-
diff --git a/tests/compiler/dart2js/enumset_test.dart b/tests/compiler/dart2js/enumset_test.dart
index 66fad2e..92ab39c 100644
--- a/tests/compiler/dart2js/enumset_test.dart
+++ b/tests/compiler/dart2js/enumset_test.dart
@@ -7,18 +7,22 @@
import 'package:compiler/src/util/enumset.dart';
import 'package:expect/expect.dart';
-enum Enum { A, B, C, D, E, F, }
+enum Enum {
+ A,
+ B,
+ C,
+ D,
+ E,
+ F,
+}
main() {
testAddRemoveContains();
testConstructorsIntersects();
}
-
-void checkEnumSet(EnumSet<Enum> enumSet,
- int expectedValue,
- List<Enum> expectedValues,
- String expectedToString) {
+void checkEnumSet(EnumSet<Enum> enumSet, int expectedValue,
+ List<Enum> expectedValues, String expectedToString) {
Expect.equals(expectedValue, enumSet.value,
"Unexpected EnumSet.value for ${enumSet.iterable(Enum.values)}");
Expect.listEquals(expectedValues, enumSet.iterable(Enum.values).toList(),
@@ -28,7 +32,9 @@
Expect.equals(expectedToString, enumSet.toString(),
"Unexpected EnumSet.toString for ${enumSet.iterable(Enum.values)}");
for (Enum value in Enum.values) {
- Expect.equals(expectedValues.contains(value), enumSet.contains(value),
+ Expect.equals(
+ expectedValues.contains(value),
+ enumSet.contains(value),
"Unexpected EnumSet.contains for $value in "
"${enumSet.iterable(Enum.values)}");
}
@@ -37,9 +43,8 @@
void testAddRemoveContains() {
EnumSet<Enum> enumSet = new EnumSet<Enum>();
- void check(int expectedValue,
- List<Enum> expectedValues,
- String expectedToString) {
+ void check(
+ int expectedValue, List<Enum> expectedValues, String expectedToString) {
checkEnumSet(enumSet, expectedValue, expectedValues, expectedToString);
}
@@ -84,21 +89,17 @@
EnumSet<Enum> emptyC = const EnumSet<Enum>.fixed(0);
EnumSet<Enum> emptyD = new EnumSet<Enum>.fixed(0);
-
void checkIntersects(EnumSet<Enum> a, EnumSet<Enum> b, bool expectedValue) {
- Expect.equals(expectedValue, a.intersects(b),
- "Unexpected intersects of $a and $b");
+ Expect.equals(
+ expectedValue, a.intersects(b), "Unexpected intersects of $a and $b");
Expect.equals(a.intersects(b), b.intersects(a),
"Unsymmetric intersects of $a and $b");
}
void check(EnumSet<Enum> a, EnumSet<Enum> b) {
- Expect.equals(a.value, b.value,
- "Unexpected values of $a and $b");
- Expect.equals(a.hashCode, b.hashCode,
- "Unexpected hash codes of $a and $b");
- Expect.equals(a, b,
- "Unexpected equality of $a and $b");
+ Expect.equals(a.value, b.value, "Unexpected values of $a and $b");
+ Expect.equals(a.hashCode, b.hashCode, "Unexpected hash codes of $a and $b");
+ Expect.equals(a, b, "Unexpected equality of $a and $b");
checkIntersects(a, b, !a.isEmpty);
}
@@ -122,7 +123,9 @@
check(singleA, singleF);
EnumSet<Enum> multiA = new EnumSet<Enum>()
- ..add(Enum.A)..add(Enum.D)..add(Enum.F);
+ ..add(Enum.A)
+ ..add(Enum.D)
+ ..add(Enum.F);
EnumSet<Enum> multiB = new EnumSet<Enum>.fromValue(41);
EnumSet<Enum> multiC = const EnumSet<Enum>.fixed(41);
EnumSet<Enum> multiD = new EnumSet<Enum>.fixed(41);
@@ -147,4 +150,4 @@
checkIntersects(singleA, multi2, true);
checkIntersects(multiA, multi2, true);
-}
\ No newline at end of file
+}
diff --git a/tests/compiler/dart2js/erroneous_element_test.dart b/tests/compiler/dart2js/erroneous_element_test.dart
index 737f721..0fee336 100644
--- a/tests/compiler/dart2js/erroneous_element_test.dart
+++ b/tests/compiler/dart2js/erroneous_element_test.dart
@@ -4,15 +4,12 @@
import 'package:expect/expect.dart';
-import 'package:compiler/src/diagnostics/messages.dart'
- show MessageKind;
+import 'package:compiler/src/diagnostics/messages.dart' show MessageKind;
import 'package:compiler/src/elements/elements.dart';
-import 'package:compiler/src/elements/modelx.dart'
- show ErroneousElementX;
+import 'package:compiler/src/elements/modelx.dart' show ErroneousElementX;
void main() {
- ErroneousElement e = new ErroneousElementX(MessageKind.GENERIC,
- {'text': 'error'},
- 'foo', null);
+ ErroneousElement e = new ErroneousElementX(
+ MessageKind.GENERIC, {'text': 'error'}, 'foo', null);
Expect.stringEquals('<foo: error>', '$e');
}
diff --git a/tests/compiler/dart2js/error_token_test.dart b/tests/compiler/dart2js/error_token_test.dart
index 2000f1a..6c99b6d 100644
--- a/tests/compiler/dart2js/error_token_test.dart
+++ b/tests/compiler/dart2js/error_token_test.dart
@@ -32,21 +32,25 @@
void main() {
asyncTest(() async {
- await runTest('''
+ await runTest(
+ '''
main() {}
class Foo {
static void bar() {
baz());
}
}
-''', error: MessageKind.UNMATCHED_TOKEN);
+''',
+ error: MessageKind.UNMATCHED_TOKEN);
- await runTest('''
+ await runTest(
+ '''
main() {}
class C {
C(v) {
throw '');
}
-}''', error: MessageKind.UNMATCHED_TOKEN);
+}''',
+ error: MessageKind.UNMATCHED_TOKEN);
});
}
diff --git a/tests/compiler/dart2js/exit_code_test.dart b/tests/compiler/dart2js/exit_code_test.dart
index 27f1948..e60072e 100644
--- a/tests/compiler/dart2js/exit_code_test.dart
+++ b/tests/compiler/dart2js/exit_code_test.dart
@@ -4,7 +4,6 @@
// Test the exit code of dart2js in case of exceptions, errors, warnings, etc.
-
import 'dart:async';
import 'dart:io' show Platform;
@@ -37,13 +36,14 @@
final Function onTest;
TestDiagnosticReporter reporter;
- TestCompiler(api.CompilerInput inputProvider,
- api.CompilerOutput outputProvider,
- api.CompilerDiagnostics handler,
- CompilerOptions options,
- String this.testMarker,
- String this.testType,
- Function this.onTest)
+ TestCompiler(
+ api.CompilerInput inputProvider,
+ api.CompilerOutput outputProvider,
+ api.CompilerDiagnostics handler,
+ CompilerOptions options,
+ String this.testMarker,
+ String this.testType,
+ Function this.onTest)
: reporter = new TestDiagnosticReporter(),
super(inputProvider, outputProvider, handler, options) {
reporter.compiler = this;
@@ -87,37 +87,35 @@
test(String marker) {
if (marker == testMarker) {
switch (testType) {
- case 'assert':
- onTest(testMarker, testType);
- assert(false);
- break;
- case 'invariant':
- onTest(testMarker, testType);
- invariant(NO_LOCATION_SPANNABLE, false, message: marker);
- break;
- case 'warning':
- onTest(testMarker, testType);
- reporter.reportWarningMessage(
- NO_LOCATION_SPANNABLE,
- MessageKind.GENERIC, {'text': marker});
- break;
- case 'error':
- onTest(testMarker, testType);
- reporter.reportErrorMessage(
- NO_LOCATION_SPANNABLE,
- MessageKind.GENERIC, {'text': marker});
- break;
- case 'internalError':
- onTest(testMarker, testType);
- reporter.internalError(NO_LOCATION_SPANNABLE, marker);
- break;
- case 'NoSuchMethodError':
- onTest(testMarker, testType);
- null.foo;
- break;
- case '':
- onTest(testMarker, testType);
- break;
+ case 'assert':
+ onTest(testMarker, testType);
+ assert(false);
+ break;
+ case 'invariant':
+ onTest(testMarker, testType);
+ invariant(NO_LOCATION_SPANNABLE, false, message: marker);
+ break;
+ case 'warning':
+ onTest(testMarker, testType);
+ reporter.reportWarningMessage(
+ NO_LOCATION_SPANNABLE, MessageKind.GENERIC, {'text': marker});
+ break;
+ case 'error':
+ onTest(testMarker, testType);
+ reporter.reportErrorMessage(
+ NO_LOCATION_SPANNABLE, MessageKind.GENERIC, {'text': marker});
+ break;
+ case 'internalError':
+ onTest(testMarker, testType);
+ reporter.internalError(NO_LOCATION_SPANNABLE, marker);
+ break;
+ case 'NoSuchMethodError':
+ onTest(testMarker, testType);
+ null.foo;
+ break;
+ case '':
+ onTest(testMarker, testType);
+ break;
}
}
}
@@ -154,10 +152,7 @@
TestResolver(TestCompiler compiler, ConstantCompiler constantCompiler)
: this.compiler = compiler,
- super(
- compiler.resolution,
- constantCompiler,
- compiler.world,
+ super(compiler.resolution, constantCompiler, compiler.world,
compiler.measurer);
void computeClassMembers(ClassElement element) {
@@ -177,6 +172,7 @@
testOccurred = true;
}
}
+
return new Future(() {
Future<api.CompilationResult> compile(
CompilerOptions compilerOptions,
@@ -186,14 +182,8 @@
compilerOutput = const NullCompilerOutput();
// Use this to silence the test when debugging:
// handler = (uri, begin, end, message, kind) {};
- Compiler compiler = new TestCompiler(
- compilerInput,
- compilerOutput,
- compilerDiagnostics,
- compilerOptions,
- marker,
- type,
- onTest);
+ Compiler compiler = new TestCompiler(compilerInput, compilerOutput,
+ compilerDiagnostics, compilerOptions, marker, type, onTest);
return compiler.run(compilerOptions.entryPoint).then((bool success) {
return new api.CompilationResult(compiler, isSuccess: success);
});
@@ -205,8 +195,10 @@
Expect.isTrue(testOccurred, 'testExitCode($marker, $type) did not occur');
if (foundExitCode == null) foundExitCode = 0;
print('testExitCode($marker, $type) '
- 'exitCode=$foundExitCode expected=$expectedExitCode');
- Expect.equals(expectedExitCode, foundExitCode,
+ 'exitCode=$foundExitCode expected=$expectedExitCode');
+ Expect.equals(
+ expectedExitCode,
+ foundExitCode,
'testExitCode($marker, $type) '
'exitCode=$foundExitCode expected=${expectedExitCode}');
checkedResults++;
@@ -216,14 +208,16 @@
if (foundExitCode == null) {
foundExitCode = exitCode;
}
- };
+ }
+
+ ;
entry.exitFunc = exit;
entry.compileFunc = compile;
List<String> args = new List<String>.from(options)
- ..add("--library-root=${Platform.script.resolve('../../../sdk/')}")
- ..add("tests/compiler/dart2js/data/exit_code_helper.dart");
+ ..add("--library-root=${Platform.script.resolve('../../../sdk/')}")
+ ..add("tests/compiler/dart2js/data/exit_code_helper.dart");
Future result = entry.internalMain(args);
return result.catchError((e, s) {
// Capture crashes.
@@ -232,7 +226,7 @@
}
Future testExitCodes(
- String marker, Map<String,int> expectedExitCodes, List<String> options) {
+ String marker, Map<String, int> expectedExitCodes, List<String> options) {
return Future.forEach(expectedExitCodes.keys, (String type) {
return testExitCode(marker, type, expectedExitCodes[type], options);
});
@@ -285,8 +279,8 @@
totalExpectedErrors += expected.length;
await testExitCodes(marker, expected, []);
- expected = _expectedExitCode(
- beforeRun: tests[marker], fatalWarnings: true);
+ expected =
+ _expectedExitCode(beforeRun: tests[marker], fatalWarnings: true);
totalExpectedErrors += expected.length;
await testExitCodes(marker, expected, ['--fatal-warnings']);
}
diff --git a/tests/compiler/dart2js/expect_annotations2_test.dart b/tests/compiler/dart2js/expect_annotations2_test.dart
index f0572c5..1608975 100644
--- a/tests/compiler/dart2js/expect_annotations2_test.dart
+++ b/tests/compiler/dart2js/expect_annotations2_test.dart
@@ -7,7 +7,7 @@
import 'memory_compiler.dart';
const MEMORY_SOURCE_FILES = const {
- 'main.dart': '''
+ 'main.dart': '''
import 'package:expect/expect.dart';
@NoInline()
@@ -31,14 +31,14 @@
print(A.bar(87654));
print(new A().gee(1337, 919182));
print(new A().field + 1);
- }'''};
+ }'''
+};
void main() {
asyncTest(() async {
OutputCollector collector = new OutputCollector();
CompilationResult result = await runCompiler(
- memorySourceFiles: MEMORY_SOURCE_FILES,
- outputProvider: collector);
+ memorySourceFiles: MEMORY_SOURCE_FILES, outputProvider: collector);
// Simply check that the constants of the small functions are still in the
// output, and that we don't see the result of constant folding.
String jsOutput = collector.getOutput('', 'js');
diff --git a/tests/compiler/dart2js/expect_annotations_test.dart b/tests/compiler/dart2js/expect_annotations_test.dart
index 8e2abcd..1d1a235 100644
--- a/tests/compiler/dart2js/expect_annotations_test.dart
+++ b/tests/compiler/dart2js/expect_annotations_test.dart
@@ -61,69 +61,64 @@
'AssumeDynamicClass is unresolved.');
void testTypeMatch(FunctionElement function, TypeMask expectedParameterType,
- TypeMask expectedReturnType, TypesInferrer inferrer) {
+ TypeMask expectedReturnType, TypesInferrer inferrer) {
for (ParameterElement parameter in function.parameters) {
TypeMask type = inferrer.getTypeOfElement(parameter);
- Expect.equals(expectedParameterType, simplify(type, compiler),
- "$parameter");
+ Expect.equals(
+ expectedParameterType, simplify(type, compiler), "$parameter");
}
if (expectedReturnType != null) {
TypeMask type = inferrer.getReturnTypeOfElement(function);
- Expect.equals(expectedReturnType, simplify(type, compiler),
- "$function");
+ Expect.equals(
+ expectedReturnType, simplify(type, compiler), "$function");
}
}
void test(String name,
- {bool expectNoInline: false,
- bool expectTrustTypeAnnotations: false,
- TypeMask expectedParameterType: null,
- TypeMask expectedReturnType: null,
- bool expectAssumeDynamic: false}) {
- Element method = compiler.mainApp.find(name);
- Expect.isNotNull(method);
- Expect.equals(
- expectNoInline,
- backend.annotations.noInline(method),
- "Unexpected annotation of @NoInline on '$method'.");
- Expect.equals(
- expectTrustTypeAnnotations,
- backend.annotations.trustTypeAnnotations(method),
- "Unexpected annotation of @TrustTypeAnnotations on '$method'.");
- Expect.equals(
- expectAssumeDynamic,
- backend.annotations.assumeDynamic(method),
- "Unexpected annotation of @AssumeDynamic on '$method'.");
- TypesInferrer inferrer = compiler.globalInference.typesInferrer;
- if (expectTrustTypeAnnotations && expectedParameterType != null) {
- testTypeMatch(method, expectedParameterType, expectedReturnType,
- inferrer);
- } else if (expectAssumeDynamic) {
- testTypeMatch(method,
- compiler.commonMasks.dynamicType, null, inferrer);
- }
+ {bool expectNoInline: false,
+ bool expectTrustTypeAnnotations: false,
+ TypeMask expectedParameterType: null,
+ TypeMask expectedReturnType: null,
+ bool expectAssumeDynamic: false}) {
+ Element method = compiler.mainApp.find(name);
+ Expect.isNotNull(method);
+ Expect.equals(expectNoInline, backend.annotations.noInline(method),
+ "Unexpected annotation of @NoInline on '$method'.");
+ Expect.equals(
+ expectTrustTypeAnnotations,
+ backend.annotations.trustTypeAnnotations(method),
+ "Unexpected annotation of @TrustTypeAnnotations on '$method'.");
+ Expect.equals(
+ expectAssumeDynamic,
+ backend.annotations.assumeDynamic(method),
+ "Unexpected annotation of @AssumeDynamic on '$method'.");
+ TypesInferrer inferrer = compiler.globalInference.typesInferrer;
+ if (expectTrustTypeAnnotations && expectedParameterType != null) {
+ testTypeMatch(
+ method, expectedParameterType, expectedReturnType, inferrer);
+ } else if (expectAssumeDynamic) {
+ testTypeMatch(method, compiler.commonMasks.dynamicType, null, inferrer);
+ }
}
TypeMask jsStringType = compiler.commonMasks.stringType;
TypeMask jsIntType = compiler.commonMasks.intType;
- TypeMask coreStringType = new TypeMask.subtype(
- compiler.coreClasses.stringClass, compiler.world);
+ TypeMask coreStringType =
+ new TypeMask.subtype(compiler.coreClasses.stringClass, compiler.world);
test('method');
test('methodAssumeDynamic', expectAssumeDynamic: true);
test('methodTrustTypeAnnotations',
- expectTrustTypeAnnotations: true,
- expectedParameterType: jsStringType);
+ expectTrustTypeAnnotations: true, expectedParameterType: jsStringType);
test('methodNoInline', expectNoInline: true);
test('methodNoInlineTrustTypeAnnotations',
- expectNoInline: true,
- expectTrustTypeAnnotations: true,
- expectedParameterType: jsStringType,
- expectedReturnType: jsIntType);
+ expectNoInline: true,
+ expectTrustTypeAnnotations: true,
+ expectedParameterType: jsStringType,
+ expectedReturnType: jsIntType);
test('methodAssumeDynamicTrustTypeAnnotations',
- expectAssumeDynamic: true,
- expectTrustTypeAnnotations: true,
- expectedParameterType: coreStringType);
-
+ expectAssumeDynamic: true,
+ expectTrustTypeAnnotations: true,
+ expectedParameterType: coreStringType);
});
}
diff --git a/tests/compiler/dart2js/field_codegen_test.dart b/tests/compiler/dart2js/field_codegen_test.dart
index c7036a4..893bc1f 100644
--- a/tests/compiler/dart2js/field_codegen_test.dart
+++ b/tests/compiler/dart2js/field_codegen_test.dart
@@ -21,10 +21,10 @@
main() {
asyncTest(() => compileAll(TEST_NULL0).then((generated) {
- Expect.isTrue(generated.contains("null"));
- }));
+ Expect.isTrue(generated.contains("null"));
+ }));
asyncTest(() => compileAll(TEST_NULL1).then((generated) {
- Expect.isTrue(generated.contains("null"));
- }));
+ Expect.isTrue(generated.contains("null"));
+ }));
}
diff --git a/tests/compiler/dart2js/field_type_simple_inferer_test.dart b/tests/compiler/dart2js/field_type_simple_inferer_test.dart
index ad28778..59ae877 100644
--- a/tests/compiler/dart2js/field_type_simple_inferer_test.dart
+++ b/tests/compiler/dart2js/field_type_simple_inferer_test.dart
@@ -4,25 +4,20 @@
import 'package:expect/expect.dart';
import 'package:async_helper/async_helper.dart';
-import 'package:compiler/src/types/types.dart'
- show TypeMask;
+import 'package:compiler/src/types/types.dart' show TypeMask;
import 'compiler_helper.dart';
import 'type_mask_test_helper.dart';
-void compileAndFind(String code,
- String className,
- String memberName,
- bool disableInlining,
- check(compiler, element)) {
+void compileAndFind(String code, String className, String memberName,
+ bool disableInlining, check(compiler, element)) {
Uri uri = new Uri(scheme: 'source');
- var compiler = compilerFor(code, uri,
- disableInlining: disableInlining);
+ var compiler = compilerFor(code, uri, disableInlining: disableInlining);
asyncTest(() => compiler.run(uri).then((_) {
- var cls = findElement(compiler, className);
- var member = cls.lookupMember(memberName);
- check(compiler, member);
- }));
+ var cls = findElement(compiler, className);
+ var member = cls.lookupMember(memberName);
+ check(compiler, member);
+ }));
}
const String TEST_1 = r"""
@@ -179,7 +174,6 @@
}
""";
-
const String TEST_11 = r"""
class S {
int fs = 1;
@@ -477,17 +471,12 @@
void doTest(String test, bool disableInlining, Map<String, Function> fields) {
fields.forEach((String name, Function f) {
- compileAndFind(
- test,
- 'A',
- name,
- disableInlining,
- (compiler, field) {
- TypeMask type = f(compiler.commonMasks);
- var inferrer = compiler.globalInference.typesInferrer;
- TypeMask inferredType =
- simplify(inferrer.getTypeOfElement(field), inferrer.compiler);
- Expect.equals(type, inferredType, test);
+ compileAndFind(test, 'A', name, disableInlining, (compiler, field) {
+ TypeMask type = f(compiler.commonMasks);
+ var inferrer = compiler.globalInference.typesInferrer;
+ TypeMask inferredType =
+ simplify(inferrer.getTypeOfElement(field), inferrer.compiler);
+ Expect.equals(type, inferredType, test);
});
});
}
@@ -502,21 +491,22 @@
findTypeMask(types.compiler, 'Interceptor', 'nonNullSubclass');
runTest(TEST_1, {'f': (types) => types.nullType});
- runTest(TEST_2, {'f1': (types) => types.nullType,
- 'f2': (types) => types.uint31Type});
- runTest(TEST_3, {'f1': (types) => types.uint31Type,
- 'f2': (types) => types.uint31Type.nullable()});
- runTest(TEST_4, {'f1': subclassOfInterceptor,
- 'f2': (types) => types.stringType.nullable()});
+ runTest(TEST_2,
+ {'f1': (types) => types.nullType, 'f2': (types) => types.uint31Type});
+ runTest(TEST_3, {
+ 'f1': (types) => types.uint31Type,
+ 'f2': (types) => types.uint31Type.nullable()
+ });
+ runTest(TEST_4, {
+ 'f1': subclassOfInterceptor,
+ 'f2': (types) => types.stringType.nullable()
+ });
// TODO(ngeoffray): We should try to infer that the initialization
// code at the declaration site of the fields does not matter.
- runTest(TEST_5, {'f1': subclassOfInterceptor,
- 'f2': subclassOfInterceptor});
- runTest(TEST_6, {'f1': subclassOfInterceptor,
- 'f2': subclassOfInterceptor});
- runTest(TEST_7, {'f1': subclassOfInterceptor,
- 'f2': subclassOfInterceptor});
+ runTest(TEST_5, {'f1': subclassOfInterceptor, 'f2': subclassOfInterceptor});
+ runTest(TEST_6, {'f1': subclassOfInterceptor, 'f2': subclassOfInterceptor});
+ runTest(TEST_7, {'f1': subclassOfInterceptor, 'f2': subclassOfInterceptor});
runTest(TEST_8, {'f': (types) => types.stringType.nullable()});
runTest(TEST_9, {'f': (types) => types.stringType.nullable()});
@@ -529,43 +519,55 @@
runTest(TEST_13, {'fs': (types) => types.uint31Type});
runTest(TEST_14, {'f': (types) => types.uint31Type});
- runTest(TEST_15, {'f': (types) {
- ClassElement cls =
- types.compiler.backend.helpers.jsIndexableClass;
- return new TypeMask.nonNullSubtype(cls,
- types.compiler.world);
- }});
+ runTest(TEST_15, {
+ 'f': (types) {
+ ClassElement cls = types.compiler.backend.helpers.jsIndexableClass;
+ return new TypeMask.nonNullSubtype(cls, types.compiler.world);
+ }
+ });
runTest(TEST_16, {'f': subclassOfInterceptor});
runTest(TEST_17, {'f': (types) => types.uint31Type.nullable()});
- runTest(TEST_18, {'f1': (types) => types.uint31Type,
- 'f2': (types) => types.stringType,
- 'f3': (types) => types.dynamicType});
- runTest(TEST_19, {'f1': (types) => types.uint31Type,
- 'f2': (types) => types.stringType,
- 'f3': (types) => types.dynamicType});
+ runTest(TEST_18, {
+ 'f1': (types) => types.uint31Type,
+ 'f2': (types) => types.stringType,
+ 'f3': (types) => types.dynamicType
+ });
+ runTest(TEST_19, {
+ 'f1': (types) => types.uint31Type,
+ 'f2': (types) => types.stringType,
+ 'f3': (types) => types.dynamicType
+ });
runTest(TEST_20, {'f': (types) => types.uint31Type.nullable()});
runTest(TEST_21, {'f': (types) => types.uint31Type.nullable()});
- runTest(TEST_22, {'f1': (types) => types.uint31Type,
- 'f2': (types) => types.uint31Type,
- 'f3': (types) => types.stringType.nullable()});
+ runTest(TEST_22, {
+ 'f1': (types) => types.uint31Type,
+ 'f2': (types) => types.uint31Type,
+ 'f3': (types) => types.stringType.nullable()
+ });
- runTest(TEST_23, {'f1': (types) => types.uint31Type.nullable(),
- 'f2': (types) => types.uint31Type.nullable(),
- 'f3': (types) => types.uint31Type.nullable(),
- 'f4': (types) => types.uint31Type.nullable()});
+ runTest(TEST_23, {
+ 'f1': (types) => types.uint31Type.nullable(),
+ 'f2': (types) => types.uint31Type.nullable(),
+ 'f3': (types) => types.uint31Type.nullable(),
+ 'f4': (types) => types.uint31Type.nullable()
+ });
- runTest(TEST_24, {'f1': (types) => types.positiveIntType,
- 'f2': (types) => types.positiveIntType,
- 'f3': (types) => types.uint31Type,
- 'f4': (types) => types.uint31Type,
- 'f5': (types) => types.numType.nullable(),
- 'f6': (types) => types.stringType.nullable()});
+ runTest(TEST_24, {
+ 'f1': (types) => types.positiveIntType,
+ 'f2': (types) => types.positiveIntType,
+ 'f3': (types) => types.uint31Type,
+ 'f4': (types) => types.uint31Type,
+ 'f5': (types) => types.numType.nullable(),
+ 'f6': (types) => types.stringType.nullable()
+ });
- runTest(TEST_25, {'f1': (types) => types.uint31Type });
- runTest(TEST_26, {'f1': (types) => types.positiveIntType });
- runTest(TEST_27, {'f1': (types) => types.uint31Type,
- 'f2': (types) => types.uint31Type.nullable()});
+ runTest(TEST_25, {'f1': (types) => types.uint31Type});
+ runTest(TEST_26, {'f1': (types) => types.positiveIntType});
+ runTest(TEST_27, {
+ 'f1': (types) => types.uint31Type,
+ 'f2': (types) => types.uint31Type.nullable()
+ });
}
void main() {
diff --git a/tests/compiler/dart2js/field_update_test.dart b/tests/compiler/dart2js/field_update_test.dart
index f5a93ba..c81422a 100644
--- a/tests/compiler/dart2js/field_update_test.dart
+++ b/tests/compiler/dart2js/field_update_test.dart
@@ -80,12 +80,11 @@
}
""";
-
main() {
test(String code, Function f) {
asyncTest(() => compileAll(code, disableInlining: true).then((generated) {
- Expect.isTrue(f(generated));
- }));
+ Expect.isTrue(f(generated));
+ }));
}
test(TEST_1, (generated) => generated.contains(r'return this.a++;'));
diff --git a/tests/compiler/dart2js/find_my_name_test.dart b/tests/compiler/dart2js/find_my_name_test.dart
index 3c5c22b..b2a2970 100644
--- a/tests/compiler/dart2js/find_my_name_test.dart
+++ b/tests/compiler/dart2js/find_my_name_test.dart
@@ -28,9 +28,9 @@
main() {
asyncTest(() => MockCompiler.create((MockCompiler compiler) {
- testClass(TEST_0, compiler);
- testClass(TEST_1, compiler);
- }));
+ testClass(TEST_0, compiler);
+ testClass(TEST_1, compiler);
+ }));
}
testClass(String code, MockCompiler compiler) {
diff --git a/tests/compiler/dart2js/flatten_test.dart b/tests/compiler/dart2js/flatten_test.dart
index 0275ee7..4b60d02 100644
--- a/tests/compiler/dart2js/flatten_test.dart
+++ b/tests/compiler/dart2js/flatten_test.dart
@@ -8,8 +8,7 @@
import "package:async_helper/async_helper.dart";
import 'type_test_helper.dart';
import 'package:compiler/src/dart_types.dart';
-import "package:compiler/src/elements/elements.dart"
- show Element, ClassElement;
+import "package:compiler/src/elements/elements.dart" show Element, ClassElement;
void main() {
asyncTest(() => TypeEnvironment.create(r"""
@@ -17,66 +16,67 @@
abstract class G<T> implements Future<G<T>> {}
abstract class H<T> implements Future<H<H<T>>> {}
""").then((env) {
+ void check(DartType T, DartType expectedFlattenedType) {
+ DartType flattenedType = env.flatten(T);
+ Expect.equals(
+ expectedFlattenedType,
+ flattenedType,
+ "Unexpected flattening of '$T' = '$flattenedType',"
+ "expected '$expectedFlattenedType'.");
+ }
- void check(DartType T, DartType expectedFlattenedType) {
- DartType flattenedType = env.flatten(T);
- Expect.equals(expectedFlattenedType, flattenedType,
- "Unexpected flattening of '$T' = '$flattenedType',"
- "expected '$expectedFlattenedType'.");
- }
+ ClassElement Future_ = env.getElement('Future');
+ ClassElement F = env.getElement('F');
+ ClassElement G = env.getElement('G');
+ ClassElement H = env.getElement('H');
+ DartType int_ = env['int'];
+ DartType dynamic_ = env['dynamic'];
+ DartType Future_int = instantiate(Future_, [int_]);
+ DartType F_int = instantiate(F, [int_]);
+ DartType G_int = instantiate(G, [int_]);
+ DartType H_int = instantiate(H, [int_]);
+ DartType H_H_int = instantiate(H, [H_int]);
- ClassElement Future_ = env.getElement('Future');
- ClassElement F = env.getElement('F');
- ClassElement G = env.getElement('G');
- ClassElement H = env.getElement('H');
- DartType int_ = env['int'];
- DartType dynamic_ = env['dynamic'];
- DartType Future_int = instantiate(Future_, [int_]);
- DartType F_int = instantiate(F, [int_]);
- DartType G_int = instantiate(G, [int_]);
- DartType H_int = instantiate(H, [int_]);
- DartType H_H_int = instantiate(H, [H_int]);
+ // flatten(int) = int
+ check(int_, int_);
- // flatten(int) = int
- check(int_, int_);
+ // flatten(Future) = dynamic
+ check(Future_.rawType, dynamic_);
- // flatten(Future) = dynamic
- check(Future_.rawType, dynamic_);
+ // flatten(Future<int>) = int
+ check(Future_int, int_);
- // flatten(Future<int>) = int
- check(Future_int, int_);
+ // flatten(Future<Future<int>>) = int
+ check(instantiate(Future_, [Future_int]), int_);
- // flatten(Future<Future<int>>) = int
- check(instantiate(Future_, [Future_int]), int_);
+ // flatten(F) = dynamic
+ check(F.rawType, dynamic_);
- // flatten(F) = dynamic
- check(F.rawType, dynamic_);
+ // flatten(F<int>) = int
+ check(F_int, int_);
- // flatten(F<int>) = int
- check(F_int, int_);
+ // flatten(F<Future<int>>) = Future<int>
+ check(instantiate(F, [Future_int]), Future_int);
- // flatten(F<Future<int>>) = Future<int>
- check(instantiate(F, [Future_int]), Future_int);
+ // flatten(G) = G
+ check(G.rawType, G.rawType);
- // flatten(G) = G
- check(G.rawType, G.rawType);
+ // flatten(G<int>) = G<int>
+ check(G_int, G_int);
- // flatten(G<int>) = G<int>
- check(G_int, G_int);
+ // flatten(H) = H<H>
+ check(H.rawType, instantiate(H, [H.rawType]));
- // flatten(H) = H<H>
- check(H.rawType, instantiate(H, [H.rawType]));
+ // flatten(H<int>) = H<H<int>>
+ check(H_int, H_H_int);
- // flatten(H<int>) = H<H<int>>
- check(H_int, H_H_int);
+ // flatten(Future<F<int>>) = int
+ check(instantiate(Future_, [F_int]), int_);
- // flatten(Future<F<int>>) = int
- check(instantiate(Future_, [F_int]), int_);
+ // flatten(Future<G<int>>) = int
+ check(instantiate(Future_, [G_int]), G_int);
- // flatten(Future<G<int>>) = int
- check(instantiate(Future_, [G_int]), G_int);
-
- // flatten(Future<H<int>>) = int
- check(instantiate(Future_, [H_int]), H_H_int);
- }));
+ // flatten(Future<H<int>>) = int
+ check(instantiate(Future_, [H_int]), H_H_int);
+ }));
}
diff --git a/tests/compiler/dart2js/for_in_test.dart b/tests/compiler/dart2js/for_in_test.dart
index 23db24a..3f02023 100644
--- a/tests/compiler/dart2js/for_in_test.dart
+++ b/tests/compiler/dart2js/for_in_test.dart
@@ -30,11 +30,11 @@
main() {
asyncTest(() => Future.wait([
- compile(TEST_ONE, entry: 'foo', check: (String generated) {
- Expect.isTrue(!generated.contains(r'break'));
- }),
- compile(TEST_TWO, entry: 'foo', check: (String generated) {
- Expect.isTrue(generated.contains(r'continue'));
- }),
- ]));
+ compile(TEST_ONE, entry: 'foo', check: (String generated) {
+ Expect.isTrue(!generated.contains(r'break'));
+ }),
+ compile(TEST_TWO, entry: 'foo', check: (String generated) {
+ Expect.isTrue(generated.contains(r'continue'));
+ }),
+ ]));
}
diff --git a/tests/compiler/dart2js/forloop_box_test.dart b/tests/compiler/dart2js/forloop_box_test.dart
index 25873c0..e44bf61 100644
--- a/tests/compiler/dart2js/forloop_box_test.dart
+++ b/tests/compiler/dart2js/forloop_box_test.dart
@@ -29,11 +29,11 @@
main() {
asyncTest(() => compileAll(TEST).then((generated) {
- Expect.isTrue(generated.contains('main_closure(i)'),
- 'for-loop variable was boxed');
- }));
+ Expect.isTrue(generated.contains('main_closure(i)'),
+ 'for-loop variable was boxed');
+ }));
asyncTest(() => compileAll(NEGATIVE_TEST).then((generated) {
- Expect.isFalse(generated.contains('main_closure(i)'),
- 'for-loop variable was not boxed');
- }));
+ Expect.isFalse(generated.contains('main_closure(i)'),
+ 'for-loop variable was not boxed');
+ }));
}
diff --git a/tests/compiler/dart2js/frontend_checker.dart b/tests/compiler/dart2js/frontend_checker.dart
index 8624cfe..dc264a2 100644
--- a/tests/compiler/dart2js/frontend_checker.dart
+++ b/tests/compiler/dart2js/frontend_checker.dart
@@ -10,15 +10,12 @@
import 'package:async_helper/async_helper.dart';
import 'package:compiler/src/commandline_options.dart';
-import 'package:compiler/src/util/uri_extras.dart'
- show relativize;
+import 'package:compiler/src/util/uri_extras.dart' show relativize;
import 'memory_compiler.dart';
import '../../../tools/testing/dart/multitest.dart'
show ExtractTestsFromMultitest;
-import '../../../tools/testing/dart/path.dart'
- show Path;
-
+import '../../../tools/testing/dart/path.dart' show Path;
/// Check the analysis of the multitests in [testFiles] to result in the
/// expected static warnings and compile-time errors.
@@ -31,72 +28,72 @@
/// the multitests in 'language/async_await_syntax_test.dart' are checked but
/// the subtests 'a03b' and 'a04c' are expected to fail.
void check(Map<String, List<String>> testFiles,
- {List<String> arguments: const <String>[],
- List<String> options: const <String>[]}) {
+ {List<String> arguments: const <String>[],
+ List<String> options: const <String>[]}) {
bool outcomeMismatch = false;
bool verbose = arguments.contains('-v');
var cachedCompiler;
asyncTest(() => Future.forEach(testFiles.keys, (String testFile) {
- Map<String, String> testSources = {};
- Map<String, Set<String>> testOutcomes = {};
- String fileName = 'tests/$testFile';
- ExtractTestsFromMultitest(new Path(fileName), testSources, testOutcomes);
- return Future.forEach(testSources.keys, (String testName) async {
- String testFileName = '$fileName/$testName';
- Set<String> expectedOutcome = testOutcomes[testName];
- bool expectFailure = testFiles[testFile].contains(testName);
- DiagnosticCollector collector = new DiagnosticCollector();
- CompilationResult result = await runCompiler(
- entryPoint: Uri.parse('memory:$testFileName'),
- memorySourceFiles: {testFileName: testSources[testName]},
- diagnosticHandler: collector,
- options: [Flags.analyzeOnly]..addAll(options),
- showDiagnostics: verbose,
- cachedCompiler: cachedCompiler);
- var compiler = result.compiler;
- bool unexpectedResult = false;
- if (expectedOutcome.contains('compile-time error')) {
- if (collector.errors.isEmpty) {
- print('$testFileName: Missing compile-time error.');
- unexpectedResult = true;
- }
- } else if (expectedOutcome.contains('static type warning')) {
- if (collector.warnings.isEmpty) {
- print('$testFileName: Missing static type warning.');
- unexpectedResult = true;
- }
- } else {
- // Expect ok.
- if (!collector.errors.isEmpty ||
- !collector.warnings.isEmpty) {
- collector.errors.forEach((message) {
- print('$testFileName: Unexpected error: ${message.message}');
- });
- collector.warnings.forEach((message) {
- print('$testFileName: Unexpected warning: ${message.message}');
- });
- unexpectedResult = true;
- }
- }
- if (expectFailure) {
- if (unexpectedResult) {
- unexpectedResult = false;
- } else {
- print('$testFileName: The test is white-listed '
- 'and therefore expected to fail.');
- unexpectedResult = true;
- }
- }
- if (unexpectedResult) {
- outcomeMismatch = true;
- }
- cachedCompiler = compiler;
- });
- }).then((_) {
- if (outcomeMismatch) {
- String testFileName =
- relativize(Uri.base, Platform.script, Platform.isWindows);
- print('''
+ Map<String, String> testSources = {};
+ Map<String, Set<String>> testOutcomes = {};
+ String fileName = 'tests/$testFile';
+ ExtractTestsFromMultitest(
+ new Path(fileName), testSources, testOutcomes);
+ return Future.forEach(testSources.keys, (String testName) async {
+ String testFileName = '$fileName/$testName';
+ Set<String> expectedOutcome = testOutcomes[testName];
+ bool expectFailure = testFiles[testFile].contains(testName);
+ DiagnosticCollector collector = new DiagnosticCollector();
+ CompilationResult result = await runCompiler(
+ entryPoint: Uri.parse('memory:$testFileName'),
+ memorySourceFiles: {testFileName: testSources[testName]},
+ diagnosticHandler: collector,
+ options: [Flags.analyzeOnly]..addAll(options),
+ showDiagnostics: verbose,
+ cachedCompiler: cachedCompiler);
+ var compiler = result.compiler;
+ bool unexpectedResult = false;
+ if (expectedOutcome.contains('compile-time error')) {
+ if (collector.errors.isEmpty) {
+ print('$testFileName: Missing compile-time error.');
+ unexpectedResult = true;
+ }
+ } else if (expectedOutcome.contains('static type warning')) {
+ if (collector.warnings.isEmpty) {
+ print('$testFileName: Missing static type warning.');
+ unexpectedResult = true;
+ }
+ } else {
+ // Expect ok.
+ if (!collector.errors.isEmpty || !collector.warnings.isEmpty) {
+ collector.errors.forEach((message) {
+ print('$testFileName: Unexpected error: ${message.message}');
+ });
+ collector.warnings.forEach((message) {
+ print('$testFileName: Unexpected warning: ${message.message}');
+ });
+ unexpectedResult = true;
+ }
+ }
+ if (expectFailure) {
+ if (unexpectedResult) {
+ unexpectedResult = false;
+ } else {
+ print('$testFileName: The test is white-listed '
+ 'and therefore expected to fail.');
+ unexpectedResult = true;
+ }
+ }
+ if (unexpectedResult) {
+ outcomeMismatch = true;
+ }
+ cachedCompiler = compiler;
+ });
+ }).then((_) {
+ if (outcomeMismatch) {
+ String testFileName =
+ relativize(Uri.base, Platform.script, Platform.isWindows);
+ print('''
===
=== ERROR: Unexpected result of analysis.
@@ -105,7 +102,7 @@
===
''');
- exit(1);
- }
- }));
+ exit(1);
+ }
+ }));
}
diff --git a/tests/compiler/dart2js/generate_at_use_site_test.dart b/tests/compiler/dart2js/generate_at_use_site_test.dart
index 4e9e100..c951836 100644
--- a/tests/compiler/dart2js/generate_at_use_site_test.dart
+++ b/tests/compiler/dart2js/generate_at_use_site_test.dart
@@ -52,16 +52,16 @@
main() {
asyncTest(() => Future.wait([
- // Make sure we don't introduce a new variable.
- compileAndDoNotMatch(FIB, 'fib', new RegExp("var $anyIdentifier =")),
+ // Make sure we don't introduce a new variable.
+ compileAndDoNotMatch(FIB, 'fib', new RegExp("var $anyIdentifier =")),
- compileAndDoNotMatch(BAR, 'bar', new RegExp("isLeaf")),
+ compileAndDoNotMatch(BAR, 'bar', new RegExp("isLeaf")),
- compile(TEST, entry: 'foo', check: (String generated) {
- Expect.isFalse(generated.contains('else'));
- // Regression check to ensure that there is no floating variable
- // expression.
- Expect.isFalse(new RegExp('^[ ]*a;').hasMatch(generated));
- }),
- ]));
+ compile(TEST, entry: 'foo', check: (String generated) {
+ Expect.isFalse(generated.contains('else'));
+ // Regression check to ensure that there is no floating variable
+ // expression.
+ Expect.isFalse(new RegExp('^[ ]*a;').hasMatch(generated));
+ }),
+ ]));
}
diff --git a/tests/compiler/dart2js/generate_code_with_compile_time_errors_test.dart b/tests/compiler/dart2js/generate_code_with_compile_time_errors_test.dart
index a1814d7..8654db5 100644
--- a/tests/compiler/dart2js/generate_code_with_compile_time_errors_test.dart
+++ b/tests/compiler/dart2js/generate_code_with_compile_time_errors_test.dart
@@ -27,9 +27,9 @@
};
test(List<String> options,
- {bool expectedOutput,
- bool expectedCodeGenerated,
- bool expectHint: false}) async {
+ {bool expectedOutput,
+ bool expectedCodeGenerated,
+ bool expectHint: false}) async {
DiagnosticCollector collector = new DiagnosticCollector();
OutputCollector outputCollector = new OutputCollector();
CompilationResult result = await runCompiler(
@@ -38,18 +38,11 @@
outputProvider: outputCollector,
options: options);
Compiler compiler = result.compiler;
- Expect.isFalse(
- result.isSuccess,
- "Expected compilation failure.");
+ Expect.isFalse(result.isSuccess, "Expected compilation failure.");
Expect.isTrue(
- collector.warnings.isEmpty,
- "Unexpected warnings: ${collector.warnings}");
- Expect.isFalse(
- collector.errors.isEmpty,
- "Expected compile-time errors.");
- Expect.equals(
- expectHint,
- collector.hints.isNotEmpty,
+ collector.warnings.isEmpty, "Unexpected warnings: ${collector.warnings}");
+ Expect.isFalse(collector.errors.isEmpty, "Expected compile-time errors.");
+ Expect.equals(expectHint, collector.hints.isNotEmpty,
"Unexpected hints: ${collector.warnings}");
JavaScriptBackend backend = compiler.backend;
@@ -70,21 +63,12 @@
void main() {
asyncTest(() async {
- await test(
- [],
- expectedCodeGenerated: false,
- expectedOutput: false);
- await test(
- ['--test-mode'],
- expectedCodeGenerated: false,
- expectedOutput: false);
- await test(
- ['--generate-code-with-compile-time-errors'],
- expectedCodeGenerated: true,
- expectedOutput: true);
- await test(
- ['--generate-code-with-compile-time-errors', '--test-mode'],
- expectedCodeGenerated: true,
- expectedOutput: false);
+ await test([], expectedCodeGenerated: false, expectedOutput: false);
+ await test(['--test-mode'],
+ expectedCodeGenerated: false, expectedOutput: false);
+ await test(['--generate-code-with-compile-time-errors'],
+ expectedCodeGenerated: true, expectedOutput: true);
+ await test(['--generate-code-with-compile-time-errors', '--test-mode'],
+ expectedCodeGenerated: true, expectedOutput: false);
});
}
diff --git a/tests/compiler/dart2js/generic_method_type_usage_test.dart b/tests/compiler/dart2js/generic_method_type_usage_test.dart
index 9ec4fbe..b1f0f22 100644
--- a/tests/compiler/dart2js/generic_method_type_usage_test.dart
+++ b/tests/compiler/dart2js/generic_method_type_usage_test.dart
@@ -53,7 +53,6 @@
print(aFunction<Set>(null));
}
''',
-
'cannot_new_method_type_variable.dart': '''
class C {
X aMethod<X>() => new X();
@@ -63,7 +62,6 @@
new C().aMethod<Set>();
}
''',
-
'cannot_new_function_type_variable.dart': '''
X aFunction<X>() => new X(42);
@@ -73,7 +71,6 @@
''',
};
-
Future runTest(Uri main, {MessageKind warning, MessageKind info}) async {
print("----\nentry-point: $main\n");
@@ -101,15 +98,12 @@
void main() {
asyncTest(() async {
- await runTest(
- Uri.parse('memory:type_variable_is_dynamic.dart'));
+ await runTest(Uri.parse('memory:type_variable_is_dynamic.dart'));
- await runTest(
- Uri.parse('memory:cannot_new_method_type_variable.dart'),
+ await runTest(Uri.parse('memory:cannot_new_method_type_variable.dart'),
warning: MessageKind.CANNOT_INSTANTIATE_TYPE_VARIABLE);
- await runTest(
- Uri.parse('memory:cannot_new_function_type_variable.dart'),
+ await runTest(Uri.parse('memory:cannot_new_function_type_variable.dart'),
warning: MessageKind.CANNOT_INSTANTIATE_TYPE_VARIABLE);
});
}
diff --git a/tests/compiler/dart2js/gvn_dynamic_field_get_test.dart b/tests/compiler/dart2js/gvn_dynamic_field_get_test.dart
index cb9e4c8..cf9deec 100644
--- a/tests/compiler/dart2js/gvn_dynamic_field_get_test.dart
+++ b/tests/compiler/dart2js/gvn_dynamic_field_get_test.dart
@@ -26,16 +26,16 @@
Uri uri = new Uri(scheme: 'source');
var compiler = compilerFor(TEST, uri);
asyncTest(() => compiler.run(uri).then((_) {
- String generated = compiler.assembledCode;
- RegExp regexp = new RegExp(r"get\$foo");
- Iterator matches = regexp.allMatches(generated).iterator;
- checkNumberOfMatches(matches, 1);
- var cls = findElement(compiler, 'A');
- Expect.isNotNull(cls);
- String name = 'foo';
- var element = cls.lookupLocalMember(name);
- Expect.isNotNull(element);
- Selector selector = new Selector.getter(new PublicName(name));
- Expect.isFalse(compiler.world.hasAnyUserDefinedGetter(selector, null));
- }));
+ String generated = compiler.assembledCode;
+ RegExp regexp = new RegExp(r"get\$foo");
+ Iterator matches = regexp.allMatches(generated).iterator;
+ checkNumberOfMatches(matches, 1);
+ var cls = findElement(compiler, 'A');
+ Expect.isNotNull(cls);
+ String name = 'foo';
+ var element = cls.lookupLocalMember(name);
+ Expect.isNotNull(element);
+ Selector selector = new Selector.getter(new PublicName(name));
+ Expect.isFalse(compiler.world.hasAnyUserDefinedGetter(selector, null));
+ }));
}
diff --git a/tests/compiler/dart2js/gvn_test.dart b/tests/compiler/dart2js/gvn_test.dart
index 4050222..2497dc9 100644
--- a/tests/compiler/dart2js/gvn_test.dart
+++ b/tests/compiler/dart2js/gvn_test.dart
@@ -108,40 +108,34 @@
main() {
asyncTest(() => Future.wait([
- compile(TEST_ONE, entry: 'foo', check: (String generated) {
- RegExp regexp = new RegExp(r"1 \+ [a-z]+");
- checkNumberOfMatches(regexp.allMatches(generated).iterator, 1);
- }),
-
- compile(TEST_TWO, entry: 'foo', check: (String generated) {
- checkNumberOfMatches(
- new RegExp("length").allMatches(generated).iterator, 1);
- }),
-
- compile(TEST_THREE, entry: 'foo', check: (String generated) {
- checkNumberOfMatches(
- new RegExp("number").allMatches(generated).iterator, 1);
- }),
-
- compile(TEST_FOUR, entry: 'foo', check: (String generated) {
- checkNumberOfMatches(new RegExp("shr").allMatches(generated).iterator, 1);
- }),
-
- compileAll(TEST_FIVE).then((generated) {
- checkNumberOfMatches(
- new RegExp("get\\\$foo").allMatches(generated).iterator, 1);
- }),
-
- compileAll(TEST_SIX).then((generated) {
- Expect.isTrue(generated.contains('for (t1 = a.field === 54; t1;)'));
- }),
-
- compileAll(TEST_SEVEN).then((generated) {
- Expect.isTrue(generated.contains('for (t1 = a.field === 54; t1;)'));
- }),
-
- compileAll(TEST_EIGHT).then((generated) {
- Expect.isTrue(generated.contains('for (; i < t1; ++i)'));
- }),
- ]));
+ compile(TEST_ONE, entry: 'foo', check: (String generated) {
+ RegExp regexp = new RegExp(r"1 \+ [a-z]+");
+ checkNumberOfMatches(regexp.allMatches(generated).iterator, 1);
+ }),
+ compile(TEST_TWO, entry: 'foo', check: (String generated) {
+ checkNumberOfMatches(
+ new RegExp("length").allMatches(generated).iterator, 1);
+ }),
+ compile(TEST_THREE, entry: 'foo', check: (String generated) {
+ checkNumberOfMatches(
+ new RegExp("number").allMatches(generated).iterator, 1);
+ }),
+ compile(TEST_FOUR, entry: 'foo', check: (String generated) {
+ checkNumberOfMatches(
+ new RegExp("shr").allMatches(generated).iterator, 1);
+ }),
+ compileAll(TEST_FIVE).then((generated) {
+ checkNumberOfMatches(
+ new RegExp("get\\\$foo").allMatches(generated).iterator, 1);
+ }),
+ compileAll(TEST_SIX).then((generated) {
+ Expect.isTrue(generated.contains('for (t1 = a.field === 54; t1;)'));
+ }),
+ compileAll(TEST_SEVEN).then((generated) {
+ Expect.isTrue(generated.contains('for (t1 = a.field === 54; t1;)'));
+ }),
+ compileAll(TEST_EIGHT).then((generated) {
+ Expect.isTrue(generated.contains('for (; i < t1; ++i)'));
+ }),
+ ]));
}
diff --git a/tests/compiler/dart2js/identity_test.dart b/tests/compiler/dart2js/identity_test.dart
index 6e25ea4..f534e29 100644
--- a/tests/compiler/dart2js/identity_test.dart
+++ b/tests/compiler/dart2js/identity_test.dart
@@ -17,15 +17,14 @@
main() {
asyncTest(() => compile(TEST_ONE, entry: 'foo', check: (String generated) {
+ // Check that no boolify code is generated.
+ RegExp regexp = new RegExp("=== true");
+ Iterator matches = regexp.allMatches(generated).iterator;
+ Expect.isFalse(matches.moveNext());
- // Check that no boolify code is generated.
- RegExp regexp = new RegExp("=== true");
- Iterator matches = regexp.allMatches(generated).iterator;
- Expect.isFalse(matches.moveNext());
-
- regexp = new RegExp("===");
- matches = regexp.allMatches(generated).iterator;
- Expect.isTrue(matches.moveNext());
- Expect.isFalse(matches.moveNext());
- }));
+ regexp = new RegExp("===");
+ matches = regexp.allMatches(generated).iterator;
+ Expect.isTrue(matches.moveNext());
+ Expect.isFalse(matches.moveNext());
+ }));
}
diff --git a/tests/compiler/dart2js/if_do_while_test.dart b/tests/compiler/dart2js/if_do_while_test.dart
index 406e981..929e76b 100644
--- a/tests/compiler/dart2js/if_do_while_test.dart
+++ b/tests/compiler/dart2js/if_do_while_test.dart
@@ -21,9 +21,9 @@
main() {
print("foo");
asyncTest(() => compile(TEST, entry: 'foo', check: (String generated) {
- // Check that the do-while in the 'then' is enclosed in braces.
- // Otherwise Android 4.0 stock browser has a syntax error. See issue 10923.
- Expect.isTrue(
- new RegExp(r'if[ ]*\([^)]+\)[ ]*\{[\n ]*do').hasMatch(generated));
- }));
+ // Check that the do-while in the 'then' is enclosed in braces.
+ // Otherwise Android 4.0 stock browser has a syntax error. See issue 10923.
+ Expect.isTrue(
+ new RegExp(r'if[ ]*\([^)]+\)[ ]*\{[\n ]*do').hasMatch(generated));
+ }));
}
diff --git a/tests/compiler/dart2js/import_mirrors_test.dart b/tests/compiler/dart2js/import_mirrors_test.dart
index 9c42114..e6d5fac 100644
--- a/tests/compiler/dart2js/import_mirrors_test.dart
+++ b/tests/compiler/dart2js/import_mirrors_test.dart
@@ -10,9 +10,8 @@
import 'dart:async';
import 'package:expect/expect.dart';
import 'package:async_helper/async_helper.dart';
-import 'package:compiler/src/diagnostics/messages.dart' show
- MessageKind,
- MessageTemplate;
+import 'package:compiler/src/diagnostics/messages.dart'
+ show MessageKind, MessageTemplate;
import 'memory_compiler.dart';
const DIRECT_IMPORT = const {
@@ -21,9 +20,7 @@
main() {}
''',
-
- 'paths':
- "main.dart => dart:mirrors",
+ 'paths': "main.dart => dart:mirrors",
};
const INDIRECT_IMPORT1 = const {
@@ -35,11 +32,8 @@
'/first.dart': '''
import 'dart:mirrors';
''',
-
- 'paths':
- "first.dart => dart:mirrors",
- 'verbosePaths':
- "main.dart => first.dart => dart:mirrors",
+ 'paths': "first.dart => dart:mirrors",
+ 'verbosePaths': "main.dart => first.dart => dart:mirrors",
};
const INDIRECT_IMPORT2 = const {
@@ -54,11 +48,8 @@
'/second.dart': '''
import 'dart:mirrors';
''',
-
- 'paths':
- "second.dart => dart:mirrors",
- 'verbosePaths':
- "main.dart => first.dart => second.dart => dart:mirrors",
+ 'paths': "second.dart => dart:mirrors",
+ 'verbosePaths': "main.dart => first.dart => second.dart => dart:mirrors",
};
const INDIRECT_PACKAGE_IMPORT1 = const {
@@ -73,9 +64,7 @@
'/pkg/second/second.dart': '''
import 'dart:mirrors';
''',
-
- 'paths':
- "first.dart => package:second => dart:mirrors",
+ 'paths': "first.dart => package:second => dart:mirrors",
'verbosePaths':
"main.dart => first.dart => package:second/second.dart => dart:mirrors",
};
@@ -92,11 +81,8 @@
'/pkg/packagename/second.dart': '''
import 'dart:mirrors';
''',
-
- 'paths':
- "first.dart => package:packagename => dart:mirrors",
- 'verbosePaths':
- "main.dart => first.dart => package:packagename/second.dart "
+ 'paths': "first.dart => package:packagename => dart:mirrors",
+ 'verbosePaths': "main.dart => first.dart => package:packagename/second.dart "
"=> dart:mirrors",
};
@@ -115,11 +101,8 @@
'/pkg/package2/third.dart': '''
import 'dart:mirrors';
''',
-
- 'paths':
- "first.dart => package:package1 => package:package2 => dart:mirrors",
- 'verbosePaths':
- "main.dart => first.dart => package:package1/second.dart "
+ 'paths': "first.dart => package:package1 => package:package2 => dart:mirrors",
+ 'verbosePaths': "main.dart => first.dart => package:package1/second.dart "
"=> package:package2/third.dart => dart:mirrors",
};
@@ -144,11 +127,8 @@
'/pkg/package2/lib/src/fifth.dart': '''
import 'dart:mirrors';
''',
-
- 'paths':
- "first.dart => package:package1 => package:package2 => dart:mirrors",
- 'verbosePaths':
- "main.dart => first.dart => package:package1/second.dart "
+ 'paths': "first.dart => package:package1 => package:package2 => dart:mirrors",
+ 'verbosePaths': "main.dart => first.dart => package:package1/second.dart "
"=> package:package1/sub/third.dart => package:package2/fourth.dart "
"=> package:package2/lib/src/fifth.dart => dart:mirrors",
};
@@ -160,9 +140,7 @@
main() {}
''',
-
- 'paths':
- "main.dart => dart:mirrors",
+ 'paths': "main.dart => dart:mirrors",
};
const DUAL_INDIRECT_IMPORT1 = const {
@@ -175,13 +153,11 @@
'/first.dart': '''
import 'dart:mirrors';
''',
-
- 'paths': const
- ["main.dart => dart:mirrors",
- "first.dart => dart:mirrors"],
- 'verbosePaths': const
- ["main.dart => dart:mirrors",
- "main.dart => first.dart => dart:mirrors"],
+ 'paths': const ["main.dart => dart:mirrors", "first.dart => dart:mirrors"],
+ 'verbosePaths': const [
+ "main.dart => dart:mirrors",
+ "main.dart => first.dart => dart:mirrors"
+ ],
};
const DUAL_INDIRECT_IMPORT2 = const {
@@ -197,13 +173,11 @@
'/second.dart': '''
import 'dart:mirrors';
''',
-
- 'paths': const
- ["first.dart => dart:mirrors",
- "second.dart => dart:mirrors"],
- 'verbosePaths': const
- ["main.dart => first.dart => dart:mirrors",
- "main.dart => second.dart => dart:mirrors"],
+ 'paths': const ["first.dart => dart:mirrors", "second.dart => dart:mirrors"],
+ 'verbosePaths': const [
+ "main.dart => first.dart => dart:mirrors",
+ "main.dart => second.dart => dart:mirrors"
+ ],
};
const DUAL_INDIRECT_IMPORT3 = const {
@@ -222,12 +196,11 @@
'/third.dart': '''
import 'dart:mirrors';
''',
-
- 'paths':
- "third.dart => dart:mirrors",
- 'verbosePaths': const
- ["main.dart => first.dart => third.dart => dart:mirrors",
- "main.dart => second.dart => third.dart => dart:mirrors"],
+ 'paths': "third.dart => dart:mirrors",
+ 'verbosePaths': const [
+ "main.dart => first.dart => third.dart => dart:mirrors",
+ "main.dart => second.dart => third.dart => dart:mirrors"
+ ],
};
const DUAL_INDIRECT_PACKAGE_IMPORT1 = const {
@@ -246,13 +219,14 @@
'/pkg/package2/third.dart': '''
import 'dart:mirrors';
''',
-
- 'paths': const
- ["main.dart => package:package1 => dart:mirrors",
- "first.dart => package:package2 => dart:mirrors"],
- 'verbosePaths': const
- ["main.dart => package:package1/second.dart => dart:mirrors",
- "main.dart => first.dart => package:package2/third.dart => dart:mirrors"]
+ 'paths': const [
+ "main.dart => package:package1 => dart:mirrors",
+ "first.dart => package:package2 => dart:mirrors"
+ ],
+ 'verbosePaths': const [
+ "main.dart => package:package1/second.dart => dart:mirrors",
+ "main.dart => first.dart => package:package2/third.dart => dart:mirrors"
+ ]
};
const DIRECT_EXPORT = const {
@@ -261,9 +235,7 @@
main() {}
''',
-
- 'paths':
- "main.dart => dart:mirrors",
+ 'paths': "main.dart => dart:mirrors",
};
const INDIRECT_EXPORT1 = const {
@@ -275,11 +247,8 @@
'/first.dart': '''
export 'dart:mirrors';
''',
-
- 'paths':
- "first.dart => dart:mirrors",
- 'verbosePaths':
- "main.dart => first.dart => dart:mirrors",
+ 'paths': "first.dart => dart:mirrors",
+ 'verbosePaths': "main.dart => first.dart => dart:mirrors",
};
const INDIRECT_EXPORT2 = const {
@@ -294,11 +263,8 @@
'/second.dart': '''
export 'dart:mirrors';
''',
-
- 'paths':
- "second.dart => dart:mirrors",
- 'verbosePaths':
- "main.dart => first.dart => second.dart => dart:mirrors",
+ 'paths': "second.dart => dart:mirrors",
+ 'verbosePaths': "main.dart => first.dart => second.dart => dart:mirrors",
};
const INDIRECT_PACKAGE_EXPORT1 = const {
@@ -313,11 +279,8 @@
'/pkg/packagename/second.dart': '''
export 'dart:mirrors';
''',
-
- 'paths':
- "first.dart => package:packagename => dart:mirrors",
- 'verbosePaths':
- "main.dart => first.dart => package:packagename/second.dart "
+ 'paths': "first.dart => package:packagename => dart:mirrors",
+ 'verbosePaths': "main.dart => first.dart => package:packagename/second.dart "
"=> dart:mirrors",
};
@@ -333,18 +296,15 @@
'/pkg/packagename/second.dart': '''
import 'dart:mirrors';
''',
-
- 'paths':
- "first.dart => package:packagename => dart:mirrors",
- 'verbosePaths':
- "main.dart => first.dart => package:packagename/second.dart "
+ 'paths': "first.dart => package:packagename => dart:mirrors",
+ 'verbosePaths': "main.dart => first.dart => package:packagename/second.dart "
"=> dart:mirrors",
};
Future test(Map sourceFiles,
- {expectedPaths,
- bool verbose: false,
- bool enableExperimentalMirrors: false}) async {
+ {expectedPaths,
+ bool verbose: false,
+ bool enableExperimentalMirrors: false}) async {
if (expectedPaths is! List) {
expectedPaths = [expectedPaths];
}
@@ -364,13 +324,12 @@
options: options);
Expect.equals(0, collector.errors.length, 'Errors: ${collector.errors}');
if (enableExperimentalMirrors) {
- Expect.equals(0, collector.warnings.length,
- 'Warnings: ${collector.errors}');
- } else {
- Expect.equals(1, collector.warnings.length,
- 'Warnings: ${collector.errors}');
Expect.equals(
- MessageKind.IMPORT_EXPERIMENTAL_MIRRORS,
+ 0, collector.warnings.length, 'Warnings: ${collector.errors}');
+ } else {
+ Expect.equals(
+ 1, collector.warnings.length, 'Warnings: ${collector.errors}');
+ Expect.equals(MessageKind.IMPORT_EXPERIMENTAL_MIRRORS,
collector.warnings.first.message.kind);
Expect.equals(
expectedPaths.join(MessageTemplate.IMPORT_EXPERIMENTAL_MIRRORS_PADDING),
@@ -386,8 +345,8 @@
expectedVerbosePaths = expectedPaths;
}
return test(sourceFiles, expectedPaths: expectedPaths).then((_) {
- return test(
- sourceFiles, expectedPaths: expectedVerbosePaths, verbose: true);
+ return test(sourceFiles,
+ expectedPaths: expectedVerbosePaths, verbose: true);
}).then((_) {
return test(sourceFiles, enableExperimentalMirrors: true);
});
@@ -395,23 +354,22 @@
void main() {
asyncTest(() => Future.forEach([
- DIRECT_IMPORT,
- INDIRECT_IMPORT1,
- INDIRECT_IMPORT2,
- INDIRECT_PACKAGE_IMPORT1,
- INDIRECT_PACKAGE_IMPORT2,
- INDIRECT_PACKAGE_IMPORT3,
- INDIRECT_PACKAGE_IMPORT4,
- DUAL_DIRECT_IMPORT,
- DUAL_INDIRECT_IMPORT1,
- DUAL_INDIRECT_IMPORT2,
- DUAL_INDIRECT_IMPORT3,
- DUAL_INDIRECT_PACKAGE_IMPORT1,
- DIRECT_EXPORT,
- INDIRECT_EXPORT1,
- INDIRECT_EXPORT2,
- INDIRECT_PACKAGE_EXPORT1,
- INDIRECT_PACKAGE_EXPORT2],
- (map) => checkPaths(map)
- ));
+ DIRECT_IMPORT,
+ INDIRECT_IMPORT1,
+ INDIRECT_IMPORT2,
+ INDIRECT_PACKAGE_IMPORT1,
+ INDIRECT_PACKAGE_IMPORT2,
+ INDIRECT_PACKAGE_IMPORT3,
+ INDIRECT_PACKAGE_IMPORT4,
+ DUAL_DIRECT_IMPORT,
+ DUAL_INDIRECT_IMPORT1,
+ DUAL_INDIRECT_IMPORT2,
+ DUAL_INDIRECT_IMPORT3,
+ DUAL_INDIRECT_PACKAGE_IMPORT1,
+ DIRECT_EXPORT,
+ INDIRECT_EXPORT1,
+ INDIRECT_EXPORT2,
+ INDIRECT_PACKAGE_EXPORT1,
+ INDIRECT_PACKAGE_EXPORT2
+ ], (map) => checkPaths(map)));
}
diff --git a/tests/compiler/dart2js/import_test.dart b/tests/compiler/dart2js/import_test.dart
index 0fbe10e..dccafe7 100644
--- a/tests/compiler/dart2js/import_test.dart
+++ b/tests/compiler/dart2js/import_test.dart
@@ -28,12 +28,12 @@
int i = "";
}
''',
- 'part.dart': '''
+ 'part.dart': '''
part of lib;
main() {}
''',
- 'lib.dart': '''
+ 'lib.dart': '''
library lib;
import 'part.dart';
@@ -49,8 +49,7 @@
memorySourceFiles: MEMORY_SOURCE_FILES,
diagnosticHandler: collector);
- collector.checkMessages([
- const Expected.error(MessageKind.MAIN_HAS_PART_OF)]);
+ collector.checkMessages([const Expected.error(MessageKind.MAIN_HAS_PART_OF)]);
}
testImportPart() async {
@@ -61,22 +60,23 @@
diagnosticHandler: collector);
collector.checkMessages([
- const Expected.error(MessageKind.IMPORT_PART_OF),
- const Expected.info(MessageKind.IMPORT_PART_OF_HERE)]);
+ const Expected.error(MessageKind.IMPORT_PART_OF),
+ const Expected.info(MessageKind.IMPORT_PART_OF_HERE)
+ ]);
}
testMissingImports() async {
var collector = new DiagnosticCollector();
await runCompiler(
- memorySourceFiles: MEMORY_SOURCE_FILES,
- diagnosticHandler: collector);
+ memorySourceFiles: MEMORY_SOURCE_FILES, diagnosticHandler: collector);
collector.checkMessages([
- const Expected.error(MessageKind.READ_SCRIPT_ERROR),
- const Expected.error(MessageKind.LIBRARY_NOT_FOUND),
- const Expected.error(MessageKind.READ_SCRIPT_ERROR),
- const Expected.error(MessageKind.READ_SCRIPT_ERROR),
- const Expected.warning(MessageKind.NOT_ASSIGNABLE)]);
+ const Expected.error(MessageKind.READ_SCRIPT_ERROR),
+ const Expected.error(MessageKind.LIBRARY_NOT_FOUND),
+ const Expected.error(MessageKind.LIBRARY_NOT_FOUND),
+ const Expected.error(MessageKind.READ_SCRIPT_ERROR),
+ const Expected.warning(MessageKind.NOT_ASSIGNABLE)
+ ]);
}
testMissingMain() async {
@@ -84,8 +84,7 @@
await runCompiler(
entryPoint: Uri.parse('memory:missing.dart'),
diagnosticHandler: collector);
- collector.checkMessages([
- const Expected.error(MessageKind.READ_SELF_ERROR)]);
+ collector.checkMessages([const Expected.error(MessageKind.READ_SELF_ERROR)]);
}
void main() {
diff --git a/tests/compiler/dart2js/in_user_code_test.dart b/tests/compiler/dart2js/in_user_code_test.dart
index 0a6e13f..486d3ec 100644
--- a/tests/compiler/dart2js/in_user_code_test.dart
+++ b/tests/compiler/dart2js/in_user_code_test.dart
@@ -23,22 +23,18 @@
main() {}
""",
-
'foo.dart': """
library foo;
""",
-
'pkg/sub/bar.dart': """
library sub.bar;
import 'package:sup/boz.dart';
import 'baz.dart';
""",
-
'pkg/sub/baz.dart': """
library sub.baz;
""",
-
'pkg/sup/boz.dart': """
library sup.boz;
""",
@@ -46,17 +42,20 @@
Future test(List<Uri> entryPoints, Map<String, bool> expectedResults) async {
CompilationResult result = await runCompiler(
- entryPoints: entryPoints,
- memorySourceFiles: SOURCE,
- options: [Flags.analyzeOnly, Flags.analyzeAll],
- packageRoot: Uri.parse('memory:pkg/'));
+ entryPoints: entryPoints,
+ memorySourceFiles: SOURCE,
+ options: [Flags.analyzeOnly, Flags.analyzeAll],
+ packageRoot: Uri.parse('memory:pkg/'));
Compiler compiler = result.compiler;
expectedResults.forEach((String uri, bool expectedResult) {
var element = compiler.libraryLoader.lookupLibrary(Uri.parse(uri));
Expect.isNotNull(element, "Unknown library '$uri'.");
- Expect.equals(expectedResult, compiler.inUserCode(element),
- expectedResult ? "Library '$uri' expected to be in user code"
- : "Library '$uri' not expected to be in user code");
+ Expect.equals(
+ expectedResult,
+ compiler.inUserCode(element),
+ expectedResult
+ ? "Library '$uri' expected to be in user code"
+ : "Library '$uri' not expected to be in user code");
});
}
@@ -65,39 +64,46 @@
}
Future runTests() async {
+ await test([
+ Uri.parse('memory:main.dart')
+ ], {
+ 'memory:main.dart': true,
+ 'memory:foo.dart': true,
+ 'memory:pkg/sub/bar.dart': true,
+ 'memory:pkg/sub/baz.dart': true,
+ 'package:sub/bar.dart': false,
+ 'package:sub/baz.dart': false,
+ 'package:sup/boz.dart': false,
+ 'dart:core': false,
+ 'dart:async': false
+ });
await test(
- [Uri.parse('memory:main.dart')],
- {'memory:main.dart': true,
- 'memory:foo.dart': true,
- 'memory:pkg/sub/bar.dart': true,
- 'memory:pkg/sub/baz.dart': true,
- 'package:sub/bar.dart': false,
- 'package:sub/baz.dart': false,
- 'package:sup/boz.dart': false,
- 'dart:core': false,
- 'dart:async': false});
- await test(
- [Uri.parse('dart:async')],
- {'dart:core': true,
- 'dart:async': true});
- await test(
- [Uri.parse('package:sub/bar.dart')],
- {'package:sub/bar.dart': true,
- 'package:sub/baz.dart': true,
- 'package:sup/boz.dart': false,
- 'dart:core': false});
- await test(
- [Uri.parse('package:sub/bar.dart'), Uri.parse('package:sup/boz.dart')],
- {'package:sub/bar.dart': true,
- 'package:sub/baz.dart': true,
- 'package:sup/boz.dart': true,
- 'dart:core': false});
- await test(
- [Uri.parse('dart:async'), Uri.parse('package:sub/bar.dart')],
- {'package:sub/bar.dart': true,
- 'package:sub/baz.dart': true,
- 'package:sup/boz.dart': false,
- 'dart:core': true,
- 'dart:async': true});
+ [Uri.parse('dart:async')], {'dart:core': true, 'dart:async': true});
+ await test([
+ Uri.parse('package:sub/bar.dart')
+ ], {
+ 'package:sub/bar.dart': true,
+ 'package:sub/baz.dart': true,
+ 'package:sup/boz.dart': false,
+ 'dart:core': false
+ });
+ await test([
+ Uri.parse('package:sub/bar.dart'),
+ Uri.parse('package:sup/boz.dart')
+ ], {
+ 'package:sub/bar.dart': true,
+ 'package:sub/baz.dart': true,
+ 'package:sup/boz.dart': true,
+ 'dart:core': false
+ });
+ await test([
+ Uri.parse('dart:async'),
+ Uri.parse('package:sub/bar.dart')
+ ], {
+ 'package:sub/bar.dart': true,
+ 'package:sub/baz.dart': true,
+ 'package:sup/boz.dart': false,
+ 'dart:core': true,
+ 'dart:async': true
+ });
}
-
diff --git a/tests/compiler/dart2js/incremental/compile_all.dart b/tests/compiler/dart2js/incremental/compile_all.dart
index fb22d15..ca1321a 100644
--- a/tests/compiler/dart2js/incremental/compile_all.dart
+++ b/tests/compiler/dart2js/incremental/compile_all.dart
@@ -9,19 +9,16 @@
import 'dart:io';
-import 'dart:developer' show
- UserTag;
+import 'dart:developer' show UserTag;
-import 'package:dart2js_incremental/dart2js_incremental.dart' show
- IncrementalCompiler;
-import 'package:compiler/src/source_file_provider.dart' show
- FormattingDiagnosticHandler;
+import 'package:dart2js_incremental/dart2js_incremental.dart'
+ show IncrementalCompiler;
+import 'package:compiler/src/source_file_provider.dart'
+ show FormattingDiagnosticHandler;
-import '../memory_source_file_helper.dart' show
- CompilerImpl;
+import '../memory_source_file_helper.dart' show CompilerImpl;
-import '../memory_compiler.dart' show
- compilerFor;
+import '../memory_compiler.dart' show compilerFor;
const bool verbose = false;
@@ -71,12 +68,16 @@
UserTag.defaultTag.makeCurrent();
sw.stop();
print('Compiled $path in ${sw.elapsedMilliseconds}');
- sw..reset()..start();
+ sw
+ ..reset()
+ ..start();
}).catchError((error, trace) {
sw.stop();
print('$error\n$trace');
print('Crash when compiling $path after ${sw.elapsedMilliseconds}');
- sw..reset()..start();
+ sw
+ ..reset()
+ ..start();
crashes.add(path);
});
}).then((_) {
@@ -97,82 +98,82 @@
}
Set<String> brokenTests = new Set<String>.from([
- // TODO(ahe): Fix the outputProvider to not throw an error.
- "/dart2js_extra/deferred/deferred_class_library.dart",
- "/dart2js_extra/deferred/deferred_class_library2.dart",
- "/dart2js_extra/deferred/deferred_class_test.dart",
- "/dart2js_extra/deferred/deferred_constant2_test.dart",
- "/dart2js_extra/deferred/deferred_constant3_test.dart",
- "/dart2js_extra/deferred/deferred_constant4_test.dart",
- "/dart2js_extra/deferred/deferred_constant_test.dart",
- "/dart2js_extra/deferred/deferred_function_library.dart",
- "/dart2js_extra/deferred/deferred_function_test.dart",
- "/dart2js_extra/deferred/deferred_overlapping_lib1.dart",
- "/dart2js_extra/deferred/deferred_overlapping_lib2.dart",
- "/dart2js_extra/deferred/deferred_overlapping_lib3.dart",
- "/dart2js_extra/deferred/deferred_overlapping_test.dart",
- "/dart2js_extra/deferred/deferred_unused_classes_test.dart",
- "/language/deferred_closurize_load_library_lib.dart",
- "/language/deferred_closurize_load_library_test.dart",
- "/language/deferred_constraints_constants_lib.dart",
- "/language/deferred_constraints_constants_old_syntax_lib.dart",
- "/language/deferred_constraints_constants_old_syntax_test.dart",
- "/language/deferred_constraints_constants_test.dart",
- "/language/deferred_constraints_lib.dart",
- "/language/deferred_constraints_lib2.dart",
- "/language/deferred_constraints_old_syntax_lib.dart",
- "/language/deferred_constraints_type_annotation_old_syntax_test.dart",
- "/language/deferred_constraints_type_annotation_test.dart",
- "/language/deferred_duplicate_prefix1_test.dart",
- "/language/deferred_duplicate_prefix2_test.dart",
- "/language/deferred_duplicate_prefix3_test.dart",
- "/language/deferred_load_inval_code_lib.dart",
- "/language/deferred_load_inval_code_test.dart",
- "/language/deferred_load_library_wrong_args_lib.dart",
- "/language/deferred_load_library_wrong_args_test.dart",
- "/language/deferred_no_prefix_test.dart",
- "/language/deferred_no_such_method_lib.dart",
- "/language/deferred_no_such_method_test.dart",
- "/language/deferred_not_loaded_check_lib.dart",
- "/language/deferred_not_loaded_check_test.dart",
- "/language/deferred_prefix_constraints_lib.dart",
- "/language/deferred_prefix_constraints_lib2.dart",
- "/language/deferred_shadow_load_library_lib.dart",
- "/language/deferred_shadow_load_library_test.dart",
+ // TODO(ahe): Fix the outputProvider to not throw an error.
+ "/dart2js_extra/deferred/deferred_class_library.dart",
+ "/dart2js_extra/deferred/deferred_class_library2.dart",
+ "/dart2js_extra/deferred/deferred_class_test.dart",
+ "/dart2js_extra/deferred/deferred_constant2_test.dart",
+ "/dart2js_extra/deferred/deferred_constant3_test.dart",
+ "/dart2js_extra/deferred/deferred_constant4_test.dart",
+ "/dart2js_extra/deferred/deferred_constant_test.dart",
+ "/dart2js_extra/deferred/deferred_function_library.dart",
+ "/dart2js_extra/deferred/deferred_function_test.dart",
+ "/dart2js_extra/deferred/deferred_overlapping_lib1.dart",
+ "/dart2js_extra/deferred/deferred_overlapping_lib2.dart",
+ "/dart2js_extra/deferred/deferred_overlapping_lib3.dart",
+ "/dart2js_extra/deferred/deferred_overlapping_test.dart",
+ "/dart2js_extra/deferred/deferred_unused_classes_test.dart",
+ "/language/deferred_closurize_load_library_lib.dart",
+ "/language/deferred_closurize_load_library_test.dart",
+ "/language/deferred_constraints_constants_lib.dart",
+ "/language/deferred_constraints_constants_old_syntax_lib.dart",
+ "/language/deferred_constraints_constants_old_syntax_test.dart",
+ "/language/deferred_constraints_constants_test.dart",
+ "/language/deferred_constraints_lib.dart",
+ "/language/deferred_constraints_lib2.dart",
+ "/language/deferred_constraints_old_syntax_lib.dart",
+ "/language/deferred_constraints_type_annotation_old_syntax_test.dart",
+ "/language/deferred_constraints_type_annotation_test.dart",
+ "/language/deferred_duplicate_prefix1_test.dart",
+ "/language/deferred_duplicate_prefix2_test.dart",
+ "/language/deferred_duplicate_prefix3_test.dart",
+ "/language/deferred_load_inval_code_lib.dart",
+ "/language/deferred_load_inval_code_test.dart",
+ "/language/deferred_load_library_wrong_args_lib.dart",
+ "/language/deferred_load_library_wrong_args_test.dart",
+ "/language/deferred_no_prefix_test.dart",
+ "/language/deferred_no_such_method_lib.dart",
+ "/language/deferred_no_such_method_test.dart",
+ "/language/deferred_not_loaded_check_lib.dart",
+ "/language/deferred_not_loaded_check_test.dart",
+ "/language/deferred_prefix_constraints_lib.dart",
+ "/language/deferred_prefix_constraints_lib2.dart",
+ "/language/deferred_shadow_load_library_lib.dart",
+ "/language/deferred_shadow_load_library_test.dart",
- "/language/bad_constructor_test.dart",
- "/language/black_listed_test.dart",
- "/language/built_in_identifier_illegal_test.dart",
- "/language/built_in_identifier_prefix_test.dart",
- "/language/built_in_identifier_test.dart",
- "/language/class_cycle2_test.dart",
- "/language/class_syntax_test.dart",
- "/language/cyclic_typedef_test.dart",
- "/language/external_test.dart",
- "/language/factory3_negative_test.dart",
- "/language/generic_field_mixin4_test.dart",
- "/language/generic_field_mixin5_test.dart",
- "/language/interface_cycle_test.dart",
- "/language/interface_injection1_negative_test.dart",
- "/language/interface_injection2_negative_test.dart",
- "/language/internal_library_test.dart",
- "/language/malformed_inheritance_test.dart",
- "/language/metadata_test.dart",
- "/language/method_override2_test.dart",
- "/language/mixin_illegal_syntax_test.dart",
- "/language/mixin_invalid_inheritance1_test.dart",
- "/language/null_test.dart",
- "/language/override_inheritance_generic_test.dart",
- "/language/prefix18_negative_test.dart",
- "/language/prefix3_negative_test.dart",
- "/language/script2_negative_test.dart",
- "/language/setter_declaration2_negative_test.dart",
- "/language/source_self_negative_test.dart",
- "/language/syntax_test.dart",
- "/language/type_variable_bounds2_test.dart",
- "/language/type_variable_conflict2_test.dart",
- "/language/type_variable_field_initializer_test.dart",
- "/language/type_variable_nested_test.dart",
- "/language/vm/reflect_core_vm_test.dart",
- "/language/vm/regress_14903_test.dart",
+ "/language/bad_constructor_test.dart",
+ "/language/black_listed_test.dart",
+ "/language/built_in_identifier_illegal_test.dart",
+ "/language/built_in_identifier_prefix_test.dart",
+ "/language/built_in_identifier_test.dart",
+ "/language/class_cycle2_test.dart",
+ "/language/class_syntax_test.dart",
+ "/language/cyclic_typedef_test.dart",
+ "/language/external_test.dart",
+ "/language/factory3_negative_test.dart",
+ "/language/generic_field_mixin4_test.dart",
+ "/language/generic_field_mixin5_test.dart",
+ "/language/interface_cycle_test.dart",
+ "/language/interface_injection1_negative_test.dart",
+ "/language/interface_injection2_negative_test.dart",
+ "/language/internal_library_test.dart",
+ "/language/malformed_inheritance_test.dart",
+ "/language/metadata_test.dart",
+ "/language/method_override2_test.dart",
+ "/language/mixin_illegal_syntax_test.dart",
+ "/language/mixin_invalid_inheritance1_test.dart",
+ "/language/null_test.dart",
+ "/language/override_inheritance_generic_test.dart",
+ "/language/prefix18_negative_test.dart",
+ "/language/prefix3_negative_test.dart",
+ "/language/script2_negative_test.dart",
+ "/language/setter_declaration2_negative_test.dart",
+ "/language/source_self_negative_test.dart",
+ "/language/syntax_test.dart",
+ "/language/type_variable_bounds2_test.dart",
+ "/language/type_variable_conflict2_test.dart",
+ "/language/type_variable_field_initializer_test.dart",
+ "/language/type_variable_nested_test.dart",
+ "/language/vm/reflect_core_vm_test.dart",
+ "/language/vm/regress_14903_test.dart",
]);
diff --git a/tests/compiler/dart2js/incremental/hello_test.dart b/tests/compiler/dart2js/incremental/hello_test.dart
index e47ef9d..c034e05 100644
--- a/tests/compiler/dart2js/incremental/hello_test.dart
+++ b/tests/compiler/dart2js/incremental/hello_test.dart
@@ -5,68 +5,56 @@
// Test a sequence of modifications to hello-world which used to cause problems
// on Try Dart.
-import 'dart:io' show
- Platform;
+import 'dart:io' show Platform;
-import 'dart:async' show
- Future;
+import 'dart:async' show Future;
-import 'package:dart2js_incremental/dart2js_incremental.dart' show
- IncrementalCompiler;
+import 'package:dart2js_incremental/dart2js_incremental.dart'
+ show IncrementalCompiler;
-import 'package:compiler/compiler.dart' show
- Diagnostic;
+import 'package:compiler/compiler.dart' show Diagnostic;
-import 'package:compiler/src/null_compiler_output.dart' show
- NullCompilerOutput;
+import 'package:compiler/src/null_compiler_output.dart' show NullCompilerOutput;
-import 'package:compiler/src/old_to_new_api.dart' show
- LegacyCompilerDiagnostics;
+import 'package:compiler/src/old_to_new_api.dart'
+ show LegacyCompilerDiagnostics;
-import 'package:async_helper/async_helper.dart' show
- asyncTest;
+import 'package:async_helper/async_helper.dart' show asyncTest;
-import 'package:expect/expect.dart' show
- Expect;
+import 'package:expect/expect.dart' show Expect;
-import '../memory_source_file_helper.dart' show
- MemorySourceFileProvider;
+import '../memory_source_file_helper.dart' show MemorySourceFileProvider;
var tests = {
-'/test1.dart':
-'''
+ '/test1.dart': '''
var greeting = "Hello, World!";
void main() {
print(greeting);
}
''',
-'/test2.dart':
-'''
+ '/test2.dart': '''
va greeting = "Hello, World!";
void main() {
print(greeting);
}
''',
-'/test3.dart':
-'''
+ '/test3.dart': '''
greeting = "Hello, World!";
void main() {
print(greeting);
}
''',
-'/test4.dart':
-'''
+ '/test4.dart': '''
in greeting = "Hello, World!";
void main() {
print(greeting);
}
''',
-'/test5.dart':
-'''
+ '/test5.dart': '''
int greeting = "Hello, World!";
void main() {
@@ -85,39 +73,31 @@
main() {
Uri libraryRoot = Uri.base.resolve('sdk/');
- Uri packageRoot = Uri.base.resolve(Platform.packageRoot);
- MemorySourceFileProvider provider =
- new MemorySourceFileProvider(tests);
- asyncTest(() => runTests(libraryRoot, packageRoot, provider));
+ Uri packageConfig = Uri.base.resolve('.packages');
+ MemorySourceFileProvider provider = new MemorySourceFileProvider(tests);
+ asyncTest(() => runTests(libraryRoot, packageConfig, provider));
}
Future runTests(
- Uri libraryRoot,
- Uri packageRoot,
- MemorySourceFileProvider provider) {
+ Uri libraryRoot, Uri packageConfig, MemorySourceFileProvider provider) {
IncrementalCompiler compiler = new IncrementalCompiler(
diagnosticHandler: new LegacyCompilerDiagnostics(handler),
inputProvider: provider,
outputProvider: const NullCompilerOutput(),
options: ['--analyze-main'],
libraryRoot: libraryRoot,
- packageRoot: packageRoot);
+ packageConfig: packageConfig);
return Future.forEach(tests.keys, (String testName) {
Uri testUri = Uri.parse('memory:$testName');
return compiler.compile(testUri).then((bool success) {
- Expect.equals(
- testResults[testName], success,
+ Expect.equals(testResults[testName], success,
'Compilation unexpectedly ${success ? "succeed" : "failed"}.');
});
});
}
-void handler(Uri uri,
- int begin,
- int end,
- String message,
- Diagnostic kind) {
+void handler(Uri uri, int begin, int end, String message, Diagnostic kind) {
if (kind != Diagnostic.VERBOSE_INFO) {
print('$uri:$begin:$end:$message:$kind');
}
diff --git a/tests/compiler/dart2js/indentation_test.dart b/tests/compiler/dart2js/indentation_test.dart
index e70190c..1730fd1 100644
--- a/tests/compiler/dart2js/indentation_test.dart
+++ b/tests/compiler/dart2js/indentation_test.dart
@@ -31,4 +31,4 @@
ind.indentMore();
Expect.stringEquals("x", ind.indentation);
-}
\ No newline at end of file
+}
diff --git a/tests/compiler/dart2js/inferrer_factory_test.dart b/tests/compiler/dart2js/inferrer_factory_test.dart
index a8b225c..2639517 100644
--- a/tests/compiler/dart2js/inferrer_factory_test.dart
+++ b/tests/compiler/dart2js/inferrer_factory_test.dart
@@ -24,9 +24,8 @@
main() {
asyncTest(() => compileAll(TEST1).then((generated) {
- // Check that we're using the index operator on the object returned
- // by the A factory.
- Expect.isTrue(generated.contains('[0] = 42'));
- }));
+ // Check that we're using the index operator on the object returned
+ // by the A factory.
+ Expect.isTrue(generated.contains('[0] = 42'));
+ }));
}
-
diff --git a/tests/compiler/dart2js/instantiated_classes_test.dart b/tests/compiler/dart2js/instantiated_classes_test.dart
index ea90156..adeca4c 100644
--- a/tests/compiler/dart2js/instantiated_classes_test.dart
+++ b/tests/compiler/dart2js/instantiated_classes_test.dart
@@ -7,79 +7,94 @@
import 'dart:async';
import 'package:expect/expect.dart';
import 'package:async_helper/async_helper.dart';
-import 'package:compiler/src/elements/elements.dart'
- show ClassElement;
+import 'package:compiler/src/elements/elements.dart' show ClassElement;
import 'type_test_helper.dart';
void main() {
asyncTest(() => Future.forEach([
- () => test("class Class {}", ["Class"]),
- () => test("""abstract class A {}
+ () => test("class Class {}", ["Class"]),
+ () => test(
+ """abstract class A {}
class Class extends A {}""",
- ["Class"]),
- () => test("""class A {}
+ ["Class"]),
+ () => test(
+ """class A {}
class Class extends A {}""",
- ["Class"]),
- () => test("""class A {}
+ ["Class"]),
+ () => test(
+ """class A {}
class B {}
class Class extends A {}""",
- ["Class"]),
- () => test("""class A {}
+ ["Class"]),
+ () => test(
+ """class A {}
class Class implements A {}""",
- ["Class"]),
- () => test("""class A {}
+ ["Class"]),
+ () => test(
+ """class A {}
class Class extends Object with A {}""",
- ["Class"]),
- () => test("""class A {}
+ ["Class"]),
+ () => test(
+ """class A {}
class B {}
class Class extends Object with B implements A {}""",
- ["Class"]),
+ ["Class"]),
- () => test("""class A {}
+ () => test(
+ """class A {}
class Class {}""",
- ["Class", "A"], ["Class", "A"]),
- () => test("""class A {}
+ ["Class", "A"],
+ ["Class", "A"]),
+ () => test(
+ """class A {}
class Class extends A {}""",
- ["Class", "A"], ["Class", "A"]),
- () => test("""class A {}
+ ["Class", "A"],
+ ["Class", "A"]),
+ () => test(
+ """class A {}
class Class implements A {}""",
- ["Class", "A"], ["Class", "A"]),
- () => test("""class A {}
+ ["Class", "A"],
+ ["Class", "A"]),
+ () => test(
+ """class A {}
class B extends A {}
class Class extends B {}""",
- ["Class", "A"], ["Class", "A"]),
- () => test("""class A {}
+ ["Class", "A"],
+ ["Class", "A"]),
+ () => test(
+ """class A {}
class B {}
class Class extends B with A {}""",
- ["Class", "A"], ["Class", "A"]),
+ ["Class", "A"],
+ ["Class", "A"]),
- // TODO(johnniwinther): Avoid registration of `Class` as instantiated.
- () => test("""class A {}
+ // TODO(johnniwinther): Avoid registration of `Class` as instantiated.
+ () => test(
+ """class A {}
class Class implements A {
factory Class() = A;
}""",
- ["Class", "A"], ["Class"]),
- ], (f) => f()));
+ ["Class", "A"],
+ ["Class"]),
+ ], (f) => f()));
}
Future test(String source, List<String> directlyInstantiatedClasses,
- [List<String> newClasses = const <String>["Class"]]) {
+ [List<String> newClasses = const <String>["Class"]]) {
StringBuffer mainSource = new StringBuffer();
mainSource.write('main() {\n');
for (String newClass in newClasses) {
mainSource.write(' new $newClass();\n');
}
mainSource.write('}');
- return TypeEnvironment.create(source,
- mainSource: mainSource.toString(),
- useMockCompiler: true).then((env) {
+ return TypeEnvironment
+ .create(source, mainSource: mainSource.toString(), useMockCompiler: true)
+ .then((env) {
Iterable<ClassElement> expectedClasses =
directlyInstantiatedClasses.map(env.getElement);
- Iterable<ClassElement> actualClasses =
- env.compiler.resolverWorld.directlyInstantiatedClasses.where(
- (c) => c.library == env.compiler.mainApp);
+ Iterable<ClassElement> actualClasses = env
+ .compiler.resolverWorld.directlyInstantiatedClasses
+ .where((c) => c.library == env.compiler.mainApp);
Expect.setEquals(expectedClasses, actualClasses);
});
}
-
-
diff --git a/tests/compiler/dart2js/interceptor_almost_constant_test.dart b/tests/compiler/dart2js/interceptor_almost_constant_test.dart
index f32c3f4..72838d76 100644
--- a/tests/compiler/dart2js/interceptor_almost_constant_test.dart
+++ b/tests/compiler/dart2js/interceptor_almost_constant_test.dart
@@ -16,10 +16,10 @@
main() {
asyncTest(() => Future.wait([
- // Check that almost-constant interceptor is used.
- compile(TEST_ONE, entry: 'foo', check: (String generated) {
- String re = r'a && [\w\.]*_methods';
- Expect.isTrue(generated.contains(new RegExp(re)), 'contains /$re/');
- })
- ]));
+ // Check that almost-constant interceptor is used.
+ compile(TEST_ONE, entry: 'foo', check: (String generated) {
+ String re = r'a && [\w\.]*_methods';
+ Expect.isTrue(generated.contains(new RegExp(re)), 'contains /$re/');
+ })
+ ]));
}
diff --git a/tests/compiler/dart2js/interceptor_test.dart b/tests/compiler/dart2js/interceptor_test.dart
index c9bd14c..b7d375d 100644
--- a/tests/compiler/dart2js/interceptor_test.dart
+++ b/tests/compiler/dart2js/interceptor_test.dart
@@ -27,22 +27,22 @@
main() {
asyncTest(() => Future.wait([
- // Check that one-shot interceptors preserve variable names, see
- // https://code.google.com/p/dart/issues/detail?id=8106.
- compile(TEST_ONE, entry: 'foo', check: (String generated) {
- Expect.isTrue(
- generated.contains(new RegExp(r'[$A-Z]+\.toString\$0\$\(a\)')));
- Expect.isTrue(generated.contains('myVariableName'));
- }),
- // Check that an intercepted getter that does not need to be
- // intercepted, is turned into a regular getter call or field
- // access.
- compile(TEST_TWO, entry: 'foo', check: (String generated) {
- Expect.isFalse(generated.contains(r'a.get$length()'));
- Expect.isTrue(
- generated.contains(new RegExp(r'[$A-Z]+\.A\$\(\)\.length')));
- Expect.isTrue(
- generated.contains(new RegExp(r'[$A-Z]+\.get\$length\$as\(a\)')));
- }),
- ]));
+ // Check that one-shot interceptors preserve variable names, see
+ // https://code.google.com/p/dart/issues/detail?id=8106.
+ compile(TEST_ONE, entry: 'foo', check: (String generated) {
+ Expect.isTrue(
+ generated.contains(new RegExp(r'[$A-Z]+\.toString\$0\$\(a\)')));
+ Expect.isTrue(generated.contains('myVariableName'));
+ }),
+ // Check that an intercepted getter that does not need to be
+ // intercepted, is turned into a regular getter call or field
+ // access.
+ compile(TEST_TWO, entry: 'foo', check: (String generated) {
+ Expect.isFalse(generated.contains(r'a.get$length()'));
+ Expect.isTrue(
+ generated.contains(new RegExp(r'[$A-Z]+\.A\$\(\)\.length')));
+ Expect.isTrue(
+ generated.contains(new RegExp(r'[$A-Z]+\.get\$length\$as\(a\)')));
+ }),
+ ]));
}
diff --git a/tests/compiler/dart2js/interop_anonymous_unreachable_test.dart b/tests/compiler/dart2js/interop_anonymous_unreachable_test.dart
index 3f38205..c278eb5 100644
--- a/tests/compiler/dart2js/interop_anonymous_unreachable_test.dart
+++ b/tests/compiler/dart2js/interop_anonymous_unreachable_test.dart
@@ -9,11 +9,11 @@
import 'package:test/test.dart';
import 'compiler_helper.dart';
-
main() {
test("unreachable code doesn't crash the compiler", () async {
// This test is a regression for Issue #24974
- String generated = await compile("""
+ String generated = await compile(
+ """
import 'package:js/js.dart';
@JS() @anonymous
@@ -21,7 +21,8 @@
external factory UniqueLongNameForTesting_A();
}
main() {}
- """, returnAll: true);
+ """,
+ returnAll: true);
// the code should not be included in the output either.
expect(generated, isNot(contains("UniqueLongNameForTesting_A")));
@@ -83,8 +84,7 @@
test('tree-shake when using flag', () async {
String generated = await compile(program,
- trustJSInteropTypeAnnotations: true,
- returnAll: true);
+ trustJSInteropTypeAnnotations: true, returnAll: true);
expect(generated.contains("UniqueLongNameForTesting_A"), isTrue);
expect(generated.contains("UniqueLongNameForTesting_D"), isTrue);
@@ -126,8 +126,7 @@
test('allocation effect of dynamic excludes native types [flag]', () async {
// Trusting types doesn't make a difference.
String generated = await compile(program,
- trustJSInteropTypeAnnotations: true,
- returnAll: true);
+ trustJSInteropTypeAnnotations: true, returnAll: true);
expect(generated.contains("UniqueLongNameForTesting_A"), isTrue);
expect(generated.contains("UniqueLongNameForTesting_B"), isTrue);
expect(generated.contains("HTMLAudioElement"), isFalse);
diff --git a/tests/compiler/dart2js/interpolation_folding_test.dart b/tests/compiler/dart2js/interpolation_folding_test.dart
index 673a85c..ad99195 100644
--- a/tests/compiler/dart2js/interpolation_folding_test.dart
+++ b/tests/compiler/dart2js/interpolation_folding_test.dart
@@ -46,18 +46,18 @@
}
asyncTest(() => Future.wait([
- // Full substitution.
- check(TEST_1, r'"u120vhellow"'),
+ // Full substitution.
+ check(TEST_1, r'"u120vhellow"'),
- // Adjacent string fragments get merged.
- check(TEST_2, r'"xxxxxyyyyy"'),
+ // Adjacent string fragments get merged.
+ check(TEST_2, r'"xxxxxyyyyy"'),
- // 1. No merging of fragments that are multi-use. Prevents exponential code
- // and keeps author's manual CSE.
- // 2. Know string values require no stringification.
- check(TEST_3, r'return b + "x" + b'),
+ // 1. No merging of fragments that are multi-use. Prevents exponential code
+ // and keeps author's manual CSE.
+ // 2. Know string values require no stringification.
+ check(TEST_3, r'return b + "x" + b'),
- // Known int value can be formatted directly.
- check(TEST_4, r'return "" + b.length'),
- ]));
+ // Known int value can be formatted directly.
+ check(TEST_4, r'return "" + b.length'),
+ ]));
}
diff --git a/tests/compiler/dart2js/is_inference2_test.dart b/tests/compiler/dart2js/is_inference2_test.dart
index 3e3e6ea..9177a11 100644
--- a/tests/compiler/dart2js/is_inference2_test.dart
+++ b/tests/compiler/dart2js/is_inference2_test.dart
@@ -15,10 +15,10 @@
main() {
asyncTest(() => compile(TEST_IF_BOOL_FIRST_INSTRUCTION, entry: 'negate',
- check: (String generated) {
- Expect.isTrue(generated.contains("!")); // We want to see !x.
- Expect.isFalse(generated.contains("!=")); // And not !== true.
- Expect.isFalse(generated.contains("true"));
- Expect.isFalse(generated.contains("false"));
- }));
+ check: (String generated) {
+ Expect.isTrue(generated.contains("!")); // We want to see !x.
+ Expect.isFalse(generated.contains("!=")); // And not !== true.
+ Expect.isFalse(generated.contains("true"));
+ Expect.isFalse(generated.contains("false"));
+ }));
}
diff --git a/tests/compiler/dart2js/is_inference_test.dart b/tests/compiler/dart2js/is_inference_test.dart
index 6f0a3b8..a5d7f8b 100644
--- a/tests/compiler/dart2js/is_inference_test.dart
+++ b/tests/compiler/dart2js/is_inference_test.dart
@@ -83,11 +83,11 @@
main() {
asyncTest(() => Future.wait([
- compileAndTest(TEST_IF),
- compileAndTest(TEST_IF_ELSE),
- compileAndTest(TEST_IF_RETURN),
- compileAndTest(TEST_IF_NOT_ELSE),
- compileAndTest(TEST_IF_NOT_RETURN),
- compileAndTest(TEST_IF_NOT_ELSE_RETURN),
- ]));
+ compileAndTest(TEST_IF),
+ compileAndTest(TEST_IF_ELSE),
+ compileAndTest(TEST_IF_RETURN),
+ compileAndTest(TEST_IF_NOT_ELSE),
+ compileAndTest(TEST_IF_NOT_RETURN),
+ compileAndTest(TEST_IF_NOT_ELSE_RETURN),
+ ]));
}
diff --git a/tests/compiler/dart2js/is_test_with_type_parameters_test.dart b/tests/compiler/dart2js/is_test_with_type_parameters_test.dart
index 76847d8..aeb8c3d 100644
--- a/tests/compiler/dart2js/is_test_with_type_parameters_test.dart
+++ b/tests/compiler/dart2js/is_test_with_type_parameters_test.dart
@@ -7,28 +7,21 @@
// Tests that is-tests are also available for superclasses if the class is
// never instantiated and not explicitly tested against.
-class A {
-}
+class A {}
-class B extends A {
-}
+class B extends A {}
-class C<T> implements A {
-}
+class C<T> implements A {}
-class D<T,L> {
-}
+class D<T, L> {}
-class F {
-}
+class F {}
-class E<T,L> extends D<L,T> {
-}
+class E<T, L> extends D<L, T> {}
-class G extends F {
-}
+class G extends F {}
-main () {
+main() {
var l = [new A(), new B(), new C<E<G, G>>()];
Expect.isTrue(l[0] is A);
Expect.isTrue(l[1] is B);
@@ -41,4 +34,3 @@
Expect.equals(e is C<D<F, G>>, i == 2);
}
}
-
diff --git a/tests/compiler/dart2js/issue13354_test.dart b/tests/compiler/dart2js/issue13354_test.dart
index 14d26ca..32826cc 100644
--- a/tests/compiler/dart2js/issue13354_test.dart
+++ b/tests/compiler/dart2js/issue13354_test.dart
@@ -29,28 +29,30 @@
Uri uri = new Uri(scheme: 'source');
var compiler = compilerFor(TEST, uri);
asyncTest(() => compiler.run(uri).then((_) {
- var commonMasks = compiler.commonMasks;
- var typesInferrer = compiler.globalInference.typesInferrer;
+ var commonMasks = compiler.commonMasks;
+ var typesInferrer = compiler.globalInference.typesInferrer;
- checkReturn(String name, type) {
- var element = findElement(compiler, name);
- Expect.equals(
- type,
- simplify(typesInferrer.getReturnTypeOfElement(element), compiler),
- name);
- }
+ checkReturn(String name, type) {
+ var element = findElement(compiler, name);
+ Expect.equals(
+ type,
+ simplify(typesInferrer.getReturnTypeOfElement(element), compiler),
+ name);
+ }
- checkReturnInClass(String className, String methodName, type) {
- var cls = findElement(compiler, className);
- var element = cls.lookupLocalMember(methodName);
- Expect.equals(type,
- simplify(typesInferrer.getReturnTypeOfElement(element), compiler));
- }
+ checkReturnInClass(String className, String methodName, type) {
+ var cls = findElement(compiler, className);
+ var element = cls.lookupLocalMember(methodName);
+ Expect.equals(
+ type,
+ simplify(
+ typesInferrer.getReturnTypeOfElement(element), compiler));
+ }
- checkReturn('bar', commonMasks.uint31Type);
- checkReturn('baz', commonMasks.functionType);
+ checkReturn('bar', commonMasks.uint31Type);
+ checkReturn('baz', commonMasks.functionType);
- checkReturnInClass('A', 'foo', commonMasks.uint31Type);
- checkReturnInClass('B', 'foo', commonMasks.functionType);
- }));
+ checkReturnInClass('A', 'foo', commonMasks.uint31Type);
+ checkReturnInClass('B', 'foo', commonMasks.functionType);
+ }));
}
diff --git a/tests/compiler/dart2js/js_constant_test.dart b/tests/compiler/dart2js/js_constant_test.dart
index 6165cfa..14ab28a 100644
--- a/tests/compiler/dart2js/js_constant_test.dart
+++ b/tests/compiler/dart2js/js_constant_test.dart
@@ -16,7 +16,6 @@
}
""";
-
main() {
RegExp directivePattern = new RegExp(
// \1 \2 \3
@@ -47,6 +46,6 @@
}
asyncTest(() => Future.wait([
- check(TEST_1),
- ]));
+ check(TEST_1),
+ ]));
}
diff --git a/tests/compiler/dart2js/js_parser_statements_test.dart b/tests/compiler/dart2js/js_parser_statements_test.dart
index 6c18de3..9432ffb 100644
--- a/tests/compiler/dart2js/js_parser_statements_test.dart
+++ b/tests/compiler/dart2js/js_parser_statements_test.dart
@@ -9,7 +9,6 @@
import 'package:compiler/src/js/js.dart' as jsAst;
import 'package:compiler/src/js/js.dart' show js;
-
Future testStatement(String statement, arguments, String expect) {
jsAst.Node node = js.statement(statement, arguments);
return MockCompiler.create((MockCompiler compiler) {
@@ -27,9 +26,11 @@
Expect.isTrue(message.contains(expect), '"$message" contains "$expect"');
return true;
}
+
void action() {
jsAst.Node node = js.statement(statement, arguments);
}
+
Expect.throws(action, doCheck);
});
}
@@ -71,9 +72,7 @@
2;
}''';
-
void main() {
-
var eOne = js('1');
var eTwo = js('2');
var eTrue = js('true');
@@ -87,65 +86,58 @@
Expect.isTrue(block12 is jsAst.Block);
asyncTest(() => Future.wait([
- // Interpolated Expressions are upgraded to ExpressionStatements.
- testStatement('{ #; #; }', [eOne, eOne], '{\n 1;\n 1;\n}'),
- testStatement('{ #a; #b; }', {'a': eOne, 'b': eOne}, '{\n 1;\n 1;\n}'),
+ // Interpolated Expressions are upgraded to ExpressionStatements.
+ testStatement('{ #; #; }', [eOne, eOne], '{\n 1;\n 1;\n}'),
+ testStatement(
+ '{ #a; #b; }', {'a': eOne, 'b': eOne}, '{\n 1;\n 1;\n}'),
- // Interpolated sub-blocks are spliced.
- testStatement('{ #; #; }', [block12, block12],
- '{\n 1;\n 2;\n 1;\n 2;\n}\n'),
- testStatement('{ #a; #b; }', {'a': block12, 'b': block12},
- '{\n 1;\n 2;\n 1;\n 2;\n}\n'),
+ // Interpolated sub-blocks are spliced.
+ testStatement(
+ '{ #; #; }', [block12, block12], '{\n 1;\n 2;\n 1;\n 2;\n}\n'),
+ testStatement('{ #a; #b; }', {'a': block12, 'b': block12},
+ '{\n 1;\n 2;\n 1;\n 2;\n}\n'),
- // If-condition. Dart booleans are evaluated, JS Expression booleans are
- // substituted.
- testStatement('if (#) #', [eOne, block12], 'if (1) {\n 1;\n 2;\n}'),
- testStatement('if (#) #;', [eTrue, block12], 'if (true) {\n 1;\n 2;\n}'),
- testStatement('if (#) #;', [eVar, block12], 'if (x) {\n 1;\n 2;\n}'),
- testStatement('if (#) #;', ['a', block12], 'if (a) {\n 1;\n 2;\n}'),
- testStatement('if (#) #;', [true, block12], '{\n 1;\n 2;\n}'),
- testStatement('if (#) #;', [false, block12], ';'),
- testStatement('if (#) 3; else #;', [true, block12], '3;'),
- testStatement('if (#) 3; else #;', [false, block12], '{\n 1;\n 2;\n}'),
- testStatement('if (#a) #b',
- {'a': eOne, 'b': block12},
- 'if (1) {\n 1;\n 2;\n}'),
- testStatement('if (#a) #b;',
- {'a': eTrue, 'b': block12},
- 'if (true) {\n 1;\n 2;\n}'),
- testStatement('if (#a) #b;',
- {'a': eVar, 'b': block12},
- 'if (x) {\n 1;\n 2;\n}'),
- testStatement('if (#a) #b;',
- {'a': 'a', 'b': block12},
- 'if (a) {\n 1;\n 2;\n}'),
- testStatement('if (#a) #b;',
- {'a': true, 'b': block12},
- '{\n 1;\n 2;\n}'),
- testStatement('if (#a) #b;',
- {'a': false, 'b': block12},
- ';'),
- testStatement('if (#a) 3; else #b;',
- {'a': true, 'b': block12},
- '3;'),
- testStatement('if (#a) 3; else #b;',
- {'a': false, 'b': block12},
- '{\n 1;\n 2;\n}'),
+ // If-condition. Dart booleans are evaluated, JS Expression booleans are
+ // substituted.
+ testStatement('if (#) #', [eOne, block12], 'if (1) {\n 1;\n 2;\n}'),
+ testStatement(
+ 'if (#) #;', [eTrue, block12], 'if (true) {\n 1;\n 2;\n}'),
+ testStatement('if (#) #;', [eVar, block12], 'if (x) {\n 1;\n 2;\n}'),
+ testStatement('if (#) #;', ['a', block12], 'if (a) {\n 1;\n 2;\n}'),
+ testStatement('if (#) #;', [true, block12], '{\n 1;\n 2;\n}'),
+ testStatement('if (#) #;', [false, block12], ';'),
+ testStatement('if (#) 3; else #;', [true, block12], '3;'),
+ testStatement(
+ 'if (#) 3; else #;', [false, block12], '{\n 1;\n 2;\n}'),
+ testStatement(
+ 'if (#a) #b', {'a': eOne, 'b': block12}, 'if (1) {\n 1;\n 2;\n}'),
+ testStatement('if (#a) #b;', {'a': eTrue, 'b': block12},
+ 'if (true) {\n 1;\n 2;\n}'),
+ testStatement('if (#a) #b;', {'a': eVar, 'b': block12},
+ 'if (x) {\n 1;\n 2;\n}'),
+ testStatement(
+ 'if (#a) #b;', {'a': 'a', 'b': block12}, 'if (a) {\n 1;\n 2;\n}'),
+ testStatement(
+ 'if (#a) #b;', {'a': true, 'b': block12}, '{\n 1;\n 2;\n}'),
+ testStatement('if (#a) #b;', {'a': false, 'b': block12}, ';'),
+ testStatement('if (#a) 3; else #b;', {'a': true, 'b': block12}, '3;'),
+ testStatement('if (#a) 3; else #b;', {'a': false, 'b': block12},
+ '{\n 1;\n 2;\n}'),
+ testStatement(
+ 'while (#) #', [eOne, block12], 'while (1) {\n 1;\n 2;\n}'),
+ testStatement(
+ 'while (#) #;', [eTrue, block12], 'while (true) {\n 1;\n 2;\n}'),
+ testStatement(
+ 'while (#) #;', [eVar, block12], 'while (x) {\n 1;\n 2;\n}'),
+ testStatement(
+ 'while (#) #;', ['a', block12], 'while (a) {\n 1;\n 2;\n}'),
+ testStatement('while (#) #;', ['a', stm], 'while (a)\n foo();'),
- testStatement('while (#) #', [eOne, block12], 'while (1) {\n 1;\n 2;\n}'),
- testStatement('while (#) #;', [eTrue, block12],
- 'while (true) {\n 1;\n 2;\n}'),
- testStatement('while (#) #;', [eVar, block12],
- 'while (x) {\n 1;\n 2;\n}'),
- testStatement('while (#) #;', ['a', block12],
- 'while (a) {\n 1;\n 2;\n}'),
- testStatement('while (#) #;', ['a', stm],
- 'while (a)\n foo();'),
-
- testStatement(
- 'do { {print(1);} do while(true); while (false) } while ( true )', [],
- '''
+ testStatement(
+ 'do { {print(1);} do while(true); while (false) } while ( true )',
+ [],
+ '''
do {
print(1);
do
@@ -154,30 +146,35 @@
while (false);
} while (true);
'''),
- testStatement('do #; while ( # )', [block12, eOne],
- 'do {\n 1;\n 2;\n} while (1); '),
- testStatement('do #; while ( # )', [block12, eTrue],
- 'do {\n 1;\n 2;\n} while (true); '),
- testStatement('do #; while ( # );', [block12, eVar],
- 'do {\n 1;\n 2;\n} while (x);'),
- testStatement('do { # } while ( # )', [block12, 'a'],
- 'do {\n 1;\n 2;\n} while (a);'),
- testStatement('do #; while ( # )', [stm, 'a'],
- 'do\n foo();\nwhile (a);'),
+ testStatement('do #; while ( # )', [block12, eOne],
+ 'do {\n 1;\n 2;\n} while (1); '),
+ testStatement('do #; while ( # )', [block12, eTrue],
+ 'do {\n 1;\n 2;\n} while (true); '),
+ testStatement('do #; while ( # );', [block12, eVar],
+ 'do {\n 1;\n 2;\n} while (x);'),
+ testStatement('do { # } while ( # )', [block12, 'a'],
+ 'do {\n 1;\n 2;\n} while (a);'),
+ testStatement(
+ 'do #; while ( # )', [stm, 'a'], 'do\n foo();\nwhile (a);'),
- testStatement('switch (#) {}', [eOne], 'switch (1) {\n}'),
- testStatement('''
+ testStatement('switch (#) {}', [eOne], 'switch (1) {\n}'),
+ testStatement(
+ '''
switch (#) {
case #: { # }
- }''', [eTrue, eOne, block12],
- 'switch (true) {\n case 1:\n 1;\n 2;\n}'),
- testStatement('''
+ }''',
+ [eTrue, eOne, block12],
+ 'switch (true) {\n case 1:\n 1;\n 2;\n}'),
+ testStatement(
+ '''
switch (#) {
case #: { # }
break;
case #: { # }
default: { # }
- }''', [eTrue, eOne, block12, eTwo, block12, stm], '''
+ }''',
+ [eTrue, eOne, block12, eTwo, block12, stm],
+ '''
switch (true) {
case 1:
1;
@@ -190,199 +187,321 @@
foo();
}'''),
- testStatement(NAMED_FUNCTION_1, [eOne], NAMED_FUNCTION_1_ONE),
- testStatement(NAMED_FUNCTION_1_NAMED_HOLE,
- {'hole': eOne},
- NAMED_FUNCTION_1_ONE),
+ testStatement(NAMED_FUNCTION_1, [eOne], NAMED_FUNCTION_1_ONE),
+ testStatement(
+ NAMED_FUNCTION_1_NAMED_HOLE, {'hole': eOne}, NAMED_FUNCTION_1_ONE),
- testStatement(MISC_1, [block12], MISC_1_1),
- testStatement(MISC_1_NAMED_HOLE, {'hole': block12}, MISC_1_1),
+ testStatement(MISC_1, [block12], MISC_1_1),
+ testStatement(MISC_1_NAMED_HOLE, {'hole': block12}, MISC_1_1),
- // Argument list splicing.
- testStatement('foo(#)', [[]], 'foo();'),
- testStatement('foo(#)', [[eOne]], 'foo(1);'),
- testStatement('foo(#)', [eOne], 'foo(1);'),
- testStatement('foo(#)', [[eTrue,eOne]], 'foo(true, 1);'),
- testStatement('foo(#a)', {'a': []}, 'foo();'),
- testStatement('foo(#a)', {'a': [eOne]}, 'foo(1);'),
- testStatement('foo(#a)', {'a': eOne}, 'foo(1);'),
- testStatement('foo(#a)', {'a': [eTrue,eOne]}, 'foo(true, 1);'),
+ // Argument list splicing.
+ testStatement('foo(#)', [[]], 'foo();'),
+ testStatement(
+ 'foo(#)',
+ [
+ [eOne]
+ ],
+ 'foo(1);'),
+ testStatement('foo(#)', [eOne], 'foo(1);'),
+ testStatement(
+ 'foo(#)',
+ [
+ [eTrue, eOne]
+ ],
+ 'foo(true, 1);'),
+ testStatement('foo(#a)', {'a': []}, 'foo();'),
+ testStatement(
+ 'foo(#a)',
+ {
+ 'a': [eOne]
+ },
+ 'foo(1);'),
+ testStatement('foo(#a)', {'a': eOne}, 'foo(1);'),
+ testStatement(
+ 'foo(#a)',
+ {
+ 'a': [eTrue, eOne]
+ },
+ 'foo(true, 1);'),
- testStatement('foo(2,#)', [[]], 'foo(2);'),
- testStatement('foo(2,#)', [[eOne]], 'foo(2, 1);'),
- testStatement('foo(2,#)', [eOne], 'foo(2, 1);'),
- testStatement('foo(2,#)', [[eTrue,eOne]], 'foo(2, true, 1);'),
- testStatement('foo(2,#a)', {'a': []}, 'foo(2);'),
- testStatement('foo(2,#a)', {'a': [eOne]}, 'foo(2, 1);'),
- testStatement('foo(2,#a)', {'a': eOne}, 'foo(2, 1);'),
- testStatement('foo(2,#a)', {'a': [eTrue,eOne]}, 'foo(2, true, 1);'),
+ testStatement('foo(2,#)', [[]], 'foo(2);'),
+ testStatement(
+ 'foo(2,#)',
+ [
+ [eOne]
+ ],
+ 'foo(2, 1);'),
+ testStatement('foo(2,#)', [eOne], 'foo(2, 1);'),
+ testStatement(
+ 'foo(2,#)',
+ [
+ [eTrue, eOne]
+ ],
+ 'foo(2, true, 1);'),
+ testStatement('foo(2,#a)', {'a': []}, 'foo(2);'),
+ testStatement(
+ 'foo(2,#a)',
+ {
+ 'a': [eOne]
+ },
+ 'foo(2, 1);'),
+ testStatement('foo(2,#a)', {'a': eOne}, 'foo(2, 1);'),
+ testStatement(
+ 'foo(2,#a)',
+ {
+ 'a': [eTrue, eOne]
+ },
+ 'foo(2, true, 1);'),
- testStatement('foo(#,3)', [[]], 'foo(3);'),
- testStatement('foo(#,3)', [[eOne]], 'foo(1, 3);'),
- testStatement('foo(#,3)', [eOne], 'foo(1, 3);'),
- testStatement('foo(#,3)', [[eTrue,eOne]], 'foo(true, 1, 3);'),
- testStatement('foo(#a,3)', {'a': []}, 'foo(3);'),
- testStatement('foo(#a,3)', {'a': [eOne]}, 'foo(1, 3);'),
- testStatement('foo(#a,3)', {'a': eOne}, 'foo(1, 3);'),
- testStatement('foo(#a,3)', {'a': [eTrue,eOne]}, 'foo(true, 1, 3);'),
+ testStatement('foo(#,3)', [[]], 'foo(3);'),
+ testStatement(
+ 'foo(#,3)',
+ [
+ [eOne]
+ ],
+ 'foo(1, 3);'),
+ testStatement('foo(#,3)', [eOne], 'foo(1, 3);'),
+ testStatement(
+ 'foo(#,3)',
+ [
+ [eTrue, eOne]
+ ],
+ 'foo(true, 1, 3);'),
+ testStatement('foo(#a,3)', {'a': []}, 'foo(3);'),
+ testStatement(
+ 'foo(#a,3)',
+ {
+ 'a': [eOne]
+ },
+ 'foo(1, 3);'),
+ testStatement('foo(#a,3)', {'a': eOne}, 'foo(1, 3);'),
+ testStatement(
+ 'foo(#a,3)',
+ {
+ 'a': [eTrue, eOne]
+ },
+ 'foo(true, 1, 3);'),
- testStatement('foo(2,#,3)', [[]], 'foo(2, 3);'),
- testStatement('foo(2,#,3)', [[eOne]], 'foo(2, 1, 3);'),
- testStatement('foo(2,#,3)', [eOne], 'foo(2, 1, 3);'),
- testStatement('foo(2,#,3)', [[eTrue,eOne]], 'foo(2, true, 1, 3);'),
- testStatement('foo(2,#a,3)', {'a': []}, 'foo(2, 3);'),
- testStatement('foo(2,#a,3)', {'a': [eOne]}, 'foo(2, 1, 3);'),
- testStatement('foo(2,#a,3)', {'a': eOne}, 'foo(2, 1, 3);'),
- testStatement('foo(2,#a,3)', {'a': [eTrue,eOne]}, 'foo(2, true, 1, 3);'),
+ testStatement('foo(2,#,3)', [[]], 'foo(2, 3);'),
+ testStatement(
+ 'foo(2,#,3)',
+ [
+ [eOne]
+ ],
+ 'foo(2, 1, 3);'),
+ testStatement('foo(2,#,3)', [eOne], 'foo(2, 1, 3);'),
+ testStatement(
+ 'foo(2,#,3)',
+ [
+ [eTrue, eOne]
+ ],
+ 'foo(2, true, 1, 3);'),
+ testStatement('foo(2,#a,3)', {'a': []}, 'foo(2, 3);'),
+ testStatement(
+ 'foo(2,#a,3)',
+ {
+ 'a': [eOne]
+ },
+ 'foo(2, 1, 3);'),
+ testStatement('foo(2,#a,3)', {'a': eOne}, 'foo(2, 1, 3);'),
+ testStatement(
+ 'foo(2,#a,3)',
+ {
+ 'a': [eTrue, eOne]
+ },
+ 'foo(2, true, 1, 3);'),
- // Interpolated Literals
- testStatement('a = {#: 1}', [eOne], 'a = {1: 1};'),
- testStatement('a = {#a: 1}', {'a': eOne}, 'a = {1: 1};'),
- // Maybe we should make this work?
- testError('a = {#: 1}', [1], 'is not a Literal: 1'),
- testError('a = {#a: 1}', {'a': 1}, 'is not a Literal: 1'),
+ // Interpolated Literals
+ testStatement('a = {#: 1}', [eOne], 'a = {1: 1};'),
+ testStatement('a = {#a: 1}', {'a': eOne}, 'a = {1: 1};'),
+ // Maybe we should make this work?
+ testError('a = {#: 1}', [1], 'is not a Literal: 1'),
+ testError('a = {#a: 1}', {'a': 1}, 'is not a Literal: 1'),
- // Interpolated parameter splicing.
- testStatement('function foo(#){}', [new jsAst.Parameter('x')],
- 'function foo(x) {\n}'),
- testStatement('function foo(#){}', ['x'], 'function foo(x) {\n}'),
- testStatement('function foo(#){}', [[]], 'function foo() {\n}'),
- testStatement('function foo(#){}', [['x']], 'function foo(x) {\n}'),
- testStatement('function foo(#){}', [['x', 'y']], 'function foo(x, y) {\n}'),
- testStatement('function foo(#a){}', {'a': new jsAst.Parameter('x')},
- 'function foo(x) {\n}'),
- testStatement('function foo(#a){}', {'a': 'x'}, 'function foo(x) {\n}'),
- testStatement('function foo(#a){}', {'a': []}, 'function foo() {\n}'),
- testStatement('function foo(#a){}', {'a': ['x']}, 'function foo(x) {\n}'),
- testStatement('function foo(#a){}',
- {'a': ['x', 'y']},
- 'function foo(x, y) {\n}'),
+ // Interpolated parameter splicing.
+ testStatement('function foo(#){}', [new jsAst.Parameter('x')],
+ 'function foo(x) {\n}'),
+ testStatement('function foo(#){}', ['x'], 'function foo(x) {\n}'),
+ testStatement('function foo(#){}', [[]], 'function foo() {\n}'),
+ testStatement(
+ 'function foo(#){}',
+ [
+ ['x']
+ ],
+ 'function foo(x) {\n}'),
+ testStatement(
+ 'function foo(#){}',
+ [
+ ['x', 'y']
+ ],
+ 'function foo(x, y) {\n}'),
+ testStatement('function foo(#a){}', {'a': new jsAst.Parameter('x')},
+ 'function foo(x) {\n}'),
+ testStatement('function foo(#a){}', {'a': 'x'}, 'function foo(x) {\n}'),
+ testStatement('function foo(#a){}', {'a': []}, 'function foo() {\n}'),
+ testStatement(
+ 'function foo(#a){}',
+ {
+ 'a': ['x']
+ },
+ 'function foo(x) {\n}'),
+ testStatement(
+ 'function foo(#a){}',
+ {
+ 'a': ['x', 'y']
+ },
+ 'function foo(x, y) {\n}'),
- testStatement('function foo() async {}', [], 'function foo() async {\n}'),
- testStatement('function foo() sync* {}', [], 'function foo() sync* {\n}'),
- testStatement('function foo() async* {}', [], 'function foo() async* {\n}'),
+ testStatement(
+ 'function foo() async {}', [], 'function foo() async {\n}'),
+ testStatement(
+ 'function foo() sync* {}', [], 'function foo() sync* {\n}'),
+ testStatement(
+ 'function foo() async* {}', [], 'function foo() async* {\n}'),
- testStatement('a = #.#', [eVar,eOne], 'a = x[1];'),
- testStatement('a = #.#', [eVar,'foo'], 'a = x.foo;'),
- testStatement('a = #a.#b', {'a': eVar, 'b': eOne}, 'a = x[1];'),
- testStatement('a = #a.#b', {'a': eVar, 'b': 'foo'}, 'a = x.foo;'),
+ testStatement('a = #.#', [eVar, eOne], 'a = x[1];'),
+ testStatement('a = #.#', [eVar, 'foo'], 'a = x.foo;'),
+ testStatement('a = #a.#b', {'a': eVar, 'b': eOne}, 'a = x[1];'),
+ testStatement('a = #a.#b', {'a': eVar, 'b': 'foo'}, 'a = x.foo;'),
- testStatement('function f(#) { return #.#; }', ['x', eVar,'foo'],
- 'function f(x) {\n return x.foo;\n}'),
- testStatement('function f(#a) { return #b.#c; }',
- {'a': 'x', 'b': eVar, 'c': 'foo'},
- 'function f(x) {\n return x.foo;\n}'),
+ testStatement('function f(#) { return #.#; }', ['x', eVar, 'foo'],
+ 'function f(x) {\n return x.foo;\n}'),
+ testStatement(
+ 'function f(#a) { return #b.#c; }',
+ {'a': 'x', 'b': eVar, 'c': 'foo'},
+ 'function f(x) {\n return x.foo;\n}'),
- testStatement('#.prototype.# = function(#) { return #.# };',
- ['className', 'getterName', ['r', 'y'], 'r', 'fieldName'],
- 'className.prototype.getterName = function(r, y) {\n'
- ' return r.fieldName;\n'
- '};'),
- testStatement('#a.prototype.#b = function(#c) { return #d.#e };',
- {'a': 'className',
- 'b': 'getterName',
- 'c': ['r', 'y'],
- 'd': 'r',
- 'e': 'fieldName'},
- 'className.prototype.getterName = function(r, y) {\n'
- ' return r.fieldName;\n'
- '};'),
+ testStatement(
+ '#.prototype.# = function(#) { return #.# };',
+ [
+ 'className',
+ 'getterName',
+ ['r', 'y'],
+ 'r',
+ 'fieldName'
+ ],
+ 'className.prototype.getterName = function(r, y) {\n'
+ ' return r.fieldName;\n'
+ '};'),
+ testStatement(
+ '#a.prototype.#b = function(#c) { return #d.#e };',
+ {
+ 'a': 'className',
+ 'b': 'getterName',
+ 'c': ['r', 'y'],
+ 'd': 'r',
+ 'e': 'fieldName'
+ },
+ 'className.prototype.getterName = function(r, y) {\n'
+ ' return r.fieldName;\n'
+ '};'),
- testStatement('function foo(r, #) { return #[r](#) }',
- [['a', 'b'], 'g', ['b', 'a']],
- 'function foo(r, a, b) {\n return g[r](b, a);\n}'),
- testStatement('function foo(r, #a) { return #b[r](#c) }',
- {'a': ['a', 'b'], 'b': 'g', 'c': ['b', 'a']},
- 'function foo(r, a, b) {\n return g[r](b, a);\n}'),
+ testStatement(
+ 'function foo(r, #) { return #[r](#) }',
+ [
+ ['a', 'b'],
+ 'g',
+ ['b', 'a']
+ ],
+ 'function foo(r, a, b) {\n return g[r](b, a);\n}'),
+ testStatement(
+ 'function foo(r, #a) { return #b[r](#c) }',
+ {
+ 'a': ['a', 'b'],
+ 'b': 'g',
+ 'c': ['b', 'a']
+ },
+ 'function foo(r, a, b) {\n return g[r](b, a);\n}'),
- // Sequence is printed flattened
- testStatement('x = #', [seq1], 'x = (1, 2, 3);'),
- testStatement('x = (#, #)', [seq1, seq1], 'x = (1, 2, 3, 1, 2, 3);'),
- testStatement('x = #, #', [seq1, seq1], 'x = (1, 2, 3), 1, 2, 3;'),
- testStatement(
- 'for (i = 0, j = #, k = 0; ; ++i, ++j, ++k){}', [seq1],
- 'for (i = 0, j = (1, 2, 3), k = 0;; ++i, ++j, ++k) {\n}'),
- testStatement('x = #a', {'a': seq1}, 'x = (1, 2, 3);'),
- testStatement('x = (#a, #b)',
- {'a': seq1, 'b': seq1},
- 'x = (1, 2, 3, 1, 2, 3);'),
- testStatement('x = #a, #b',
- {'a': seq1, 'b': seq1},
- 'x = (1, 2, 3), 1, 2, 3;'),
- testStatement(
- 'for (i = 0, j = #a, k = 0; ; ++i, ++j, ++k){}', {'a': seq1},
- 'for (i = 0, j = (1, 2, 3), k = 0;; ++i, ++j, ++k) {\n}'),
+ // Sequence is printed flattened
+ testStatement('x = #', [seq1], 'x = (1, 2, 3);'),
+ testStatement('x = (#, #)', [seq1, seq1], 'x = (1, 2, 3, 1, 2, 3);'),
+ testStatement('x = #, #', [seq1, seq1], 'x = (1, 2, 3), 1, 2, 3;'),
+ testStatement('for (i = 0, j = #, k = 0; ; ++i, ++j, ++k){}', [seq1],
+ 'for (i = 0, j = (1, 2, 3), k = 0;; ++i, ++j, ++k) {\n}'),
+ testStatement('x = #a', {'a': seq1}, 'x = (1, 2, 3);'),
+ testStatement(
+ 'x = (#a, #b)', {'a': seq1, 'b': seq1}, 'x = (1, 2, 3, 1, 2, 3);'),
+ testStatement(
+ 'x = #a, #b', {'a': seq1, 'b': seq1}, 'x = (1, 2, 3), 1, 2, 3;'),
+ testStatement(
+ 'for (i = 0, j = #a, k = 0; ; ++i, ++j, ++k){}',
+ {'a': seq1},
+ 'for (i = 0, j = (1, 2, 3), k = 0;; ++i, ++j, ++k) {\n}'),
- // Use the same name several times.
- testStatement('#a.prototype.#a = function(#b) { return #c.#c };',
- {'a': 'name1_2',
- 'b': ['r', 'y'],
- 'c': 'name4_5'},
- 'name1_2.prototype.name1_2 = function(r, y) {\n'
- ' return name4_5.name4_5;\n'
- '};'),
+ // Use the same name several times.
+ testStatement(
+ '#a.prototype.#a = function(#b) { return #c.#c };',
+ {
+ 'a': 'name1_2',
+ 'b': ['r', 'y'],
+ 'c': 'name4_5'
+ },
+ 'name1_2.prototype.name1_2 = function(r, y) {\n'
+ ' return name4_5.name4_5;\n'
+ '};'),
- testStatement('label: while (a) { label2: break label;}', [],
- 'label:\n while (a)\n label2:\n break label;\n '),
+ testStatement('label: while (a) { label2: break label;}', [],
+ 'label:\n while (a)\n label2:\n break label;\n '),
+ testStatement('var # = 3', ['x'], 'var x = 3;'),
+ testStatement(
+ 'var # = 3', [new jsAst.VariableDeclaration('x')], 'var x = 3;'),
+ testStatement(
+ 'var # = 3, # = #', ['x', 'y', js.number(2)], 'var x = 3, y = 2;'),
+ testStatement('var #a = 3, #b = #c',
+ {"a": 'x', "b": 'y', "c": js.number(2)}, 'var x = 3, y = 2;'),
+ testStatement('function #() {}', ['x'], 'function x() {\n}'),
+ testStatement('function #() {}', [new jsAst.VariableDeclaration('x')],
+ 'function x() {\n}'),
+ testStatement('try {} catch (#) {}', ['x'], 'try {\n} catch (x) {\n}'),
+ testStatement(
+ 'try {} catch (#a) {}', {"a": 'x'}, 'try {\n} catch (x) {\n}'),
+ testStatement(
+ 'try {} catch (#a) {}',
+ {"a": new jsAst.VariableDeclaration('x')},
+ 'try {\n} catch (x) {\n}'),
- testStatement('var # = 3', ['x'], 'var x = 3;'),
- testStatement('var # = 3',
- [new jsAst.VariableDeclaration('x')],
- 'var x = 3;'),
- testStatement('var # = 3, # = #',
- ['x', 'y', js.number(2)],
- 'var x = 3, y = 2;'),
- testStatement('var #a = 3, #b = #c',
- {"a": 'x', "b": 'y', "c": js.number(2)},
- 'var x = 3, y = 2;'),
- testStatement('function #() {}', ['x'], 'function x() {\n}'),
- testStatement('function #() {}',
- [new jsAst.VariableDeclaration('x')],
- 'function x() {\n}'),
- testStatement('try {} catch (#) {}', ['x'], 'try {\n} catch (x) {\n}'),
- testStatement('try {} catch (#a) {}', {"a": 'x'}, 'try {\n} catch (x) {\n}'),
- testStatement('try {} catch (#a) {}',
- {"a": new jsAst.VariableDeclaration('x')},
- 'try {\n} catch (x) {\n}'),
-
- // Test that braces around a single-statement block are removed by printer.
- testStatement('while (a) {foo()}', [],
- 'while (a)\n foo();'),
- testStatement('if (a) {foo();}', [],
- 'if (a)\n foo();'),
- testStatement('if (a) {foo();} else {foo2();}', [],
- 'if (a)\n foo();\nelse\n foo2();'),
- testStatement('if (a) foo(); else {foo2();}', [],
- 'if (a)\n foo();\nelse\n foo2();'),
- testStatement('do {foo();} while(a);', [],
- 'do\n foo();\nwhile (a);'),
- testStatement('label: {foo();}', [],
- 'label:\n foo();'),
- testStatement('for (var key in a) {foo();}', [],
- 'for (var key in a)\n foo();'),
- // `label: break label;` gives problems on IE. Test that it is avoided.
- testStatement('label: {break label;}', [],
- ';'),
- // This works on IE:
- testStatement('label: {label2: {break label;}}', [],
- 'label:\n label2:\n break label;\n'),
- // Test dangling else:
- testStatement('if (a) {if (b) {foo1();}} else {foo2();}', [], """
+ // Test that braces around a single-statement block are removed by printer.
+ testStatement('while (a) {foo()}', [], 'while (a)\n foo();'),
+ testStatement('if (a) {foo();}', [], 'if (a)\n foo();'),
+ testStatement('if (a) {foo();} else {foo2();}', [],
+ 'if (a)\n foo();\nelse\n foo2();'),
+ testStatement('if (a) foo(); else {foo2();}', [],
+ 'if (a)\n foo();\nelse\n foo2();'),
+ testStatement('do {foo();} while(a);', [], 'do\n foo();\nwhile (a);'),
+ testStatement('label: {foo();}', [], 'label:\n foo();'),
+ testStatement(
+ 'for (var key in a) {foo();}', [], 'for (var key in a)\n foo();'),
+ // `label: break label;` gives problems on IE. Test that it is avoided.
+ testStatement('label: {break label;}', [], ';'),
+ // This works on IE:
+ testStatement('label: {label2: {break label;}}', [],
+ 'label:\n label2:\n break label;\n'),
+ // Test dangling else:
+ testStatement(
+ 'if (a) {if (b) {foo1();}} else {foo2();}',
+ [],
+ """
if (a) {
if (b)
foo1();
} else
foo2();"""),
- testStatement('if (a) {if (b) {foo1();} else {foo2();}}', [], """
+ testStatement(
+ 'if (a) {if (b) {foo1();} else {foo2();}}',
+ [],
+ """
if (a)
if (b)
foo1();
else
foo2();
"""),
- testStatement('if (a) {if (b) {foo1();} else {foo2();}} else {foo3();}',
- [], """
+ testStatement(
+ 'if (a) {if (b) {foo1();} else {foo2();}} else {foo3();}',
+ [],
+ """
if (a)
if (b)
foo1();
@@ -390,13 +509,15 @@
foo2();
else
foo3();"""),
- testStatement('if (a) {while (true) if (b) {foo1();}} else {foo2();}',
- [], """
+ testStatement(
+ 'if (a) {while (true) if (b) {foo1();}} else {foo2();}',
+ [],
+ """
if (a) {
while (true)
if (b)
foo1();
} else
foo2();"""),
- ]));
+ ]));
}
diff --git a/tests/compiler/dart2js/js_parser_test.dart b/tests/compiler/dart2js/js_parser_test.dart
index 89d51070..513a04d 100644
--- a/tests/compiler/dart2js/js_parser_test.dart
+++ b/tests/compiler/dart2js/js_parser_test.dart
@@ -13,9 +13,7 @@
jsAst.Node node = js(expression);
return MockCompiler.create((MockCompiler compiler) {
String jsText =
- jsAst.prettyPrint(node,
- compiler,
- allowVariableMinification: false);
+ jsAst.prettyPrint(node, compiler, allowVariableMinification: false);
if (expect == "") {
Expect.stringEquals(expression, jsText);
} else {
@@ -30,173 +28,174 @@
Expect.isTrue(exception.toString().contains(expect));
return true;
}
+
Expect.throws(() => js(expression), doCheck);
});
}
void main() {
asyncTest(() => Future.wait([
- // Asterisk indicates deviations from real JS.
- // Simple var test.
- testExpression('var a = ""'),
- // Parse and print will normalize whitespace.
- testExpression(' var a = "" ', 'var a = ""'),
- // Operator precedence.
- testExpression('x = a + b * c'),
- testExpression('x = a * b + c'),
- testExpression('x = a + b * c + d'),
- testExpression('x = a * b + c * d'),
- testExpression('remaining = (remaining / 88) | 0',
- 'remaining = remaining / 88 | 0'),
- // Binary operators have left associativity.
- testExpression('x = a + b + c'),
- // We can cope with relational operators and non-relational.
- testExpression('a + b == c + d'),
- // The prettyprinter will insert braces where needed.
- testExpression('a + (b == c) + d'),
- // We can handle () for calls.
- testExpression('foo(bar)'),
- testExpression('foo(bar, baz)'),
- // Chained calls without parentheses.
- testExpression('foo(bar)(baz)'),
- // Chaned calls with and without new.
- testExpression('new foo(bar)(baz)'),
- testExpression('new foo.bar(bar)(baz)'),
- testExpression('foo.bar(bar)(baz)'),
- testExpression('constructor = new Function(str)()'),
- // The prettyprinter understands chained calls without extra parentheses.
- testExpression('(foo(bar))(baz)', 'foo(bar)(baz)'),
- // Chains of dotting and calls.
- testExpression('foo.bar(baz)'),
- // String literal.
- testExpression('var x = "fisk"'),
- // String literal with \n.
- testExpression(r'var x = "\n"'),
- // String literal with escaped quote.
- testExpression(r'var x = "\""'),
- // *No clever escapes.
- testError(r'var x = "\x42"', 'escapes are not allowed in literals'),
- // Operator new.
- testExpression('new Foo()'),
- // New with dotted access.
- testExpression('new Frobinator.frobinate()'),
- testExpression('new Frobinator().frobinate()'),
- // The prettyprinter strips some superfluous parentheses.
- testExpression('(new Frobinator()).frobinate()',
- 'new Frobinator().frobinate()'),
- // *We want a bracket on 'new'.
- testError('new Foo', 'Parentheses are required'),
- testError('(new Foo)', 'Parentheses are required'),
- // Bogus operators.
- testError('a +++ b', 'Unknown operator'),
- // This isn't perl. There are rules.
- testError('a <=> b', 'Unknown operator'),
- // Typeof.
- testExpression('typeof foo == "number"'),
- // Strange relation.
- testExpression('a < b < c'),
- // Chained var.
- testExpression('var x = 0, y = 1.2, z = 42'),
- // Empty object literal.
- testExpression('foo({}, {})'),
- // *Can't handle non-empty object literals
- testExpression('foo({meaning: 42})'),
- // Literals.
- testExpression('x(false, true, null)'),
- // *We should really throw here.
- testExpression('var false = 42'),
- testExpression('var new = 42'),
- // Bad keyword.
- testError('var typeof = 42', "Expected ALPHA"),
- // Malformed decimal/hex.
- testError('var x = 1.1.1', "Unparseable number"),
- testError('var x = 0xabcdefga', "Unparseable number"),
- testError('var x = 0xabcdef\$a', "Unparseable number"),
- testError('var x = 0x ', "Unparseable number"),
- // Good hex constants.
- testExpression('var x = 0xff'),
- testExpression('var x = 0xff + 0xff'),
- testExpression('var x = 0xaF + 0x0123456789abcdefABCDEF'),
- // All sorts of keywords are allowed as property names in ES5.
- testExpression('x.new = 0'),
- testExpression('x.delete = 0'),
- testExpression('x.for = 0'),
- testExpression('x.instanceof = 0'),
- testExpression('x.in = 0'),
- testExpression('x.void = 0'),
- testExpression('x.continue = 0'),
- // More unary.
- testExpression('x = !x'),
- testExpression('!x == false'),
- testExpression('var foo = void 0'),
- testExpression('delete foo.bar'),
- testExpression('delete foo'),
- testExpression('x in y'),
- testExpression('x instanceof y'),
- testExpression('a * b in c * d'),
- testExpression('a * b instanceof c * d'),
- testError('x typeof y', 'Unparsed junk'),
- testExpression('x &= ~mask'),
- // Await is parsed as an unary prefix operator.
- testExpression('var foo = await 0'),
- testExpression('await x++'),
- testExpression('void (await (x++))', 'void await x++'),
- testExpression('void (await x)++'),
- testExpression('++(await x)++'),
- // Adjacent tokens.
- testExpression('foo[x[bar]]'),
- testExpression('foo[[bar]]'),
- // Prefix ++ etc.
- testExpression("++x"),
- testExpression("++foo.bar"),
- testExpression("+x"),
- testExpression("+foo.bar"),
- testExpression("-x"),
- testExpression("-foo.bar"),
- testExpression("--x"),
- testExpression("--foo.bar"),
- // Postfix ++ etc.
- testExpression("x++"),
- testExpression("foo.bar++"),
- testExpression("x--"),
- testExpression("foo.bar--"),
- // Both!
- testExpression("++x++"),
- testExpression("++foo.bar++"),
- testExpression("--x--"),
- testExpression("--foo.bar--"),
- // *We can't handle stacked unary operators (apart from !).
- testError("x++ ++"),
- testError("++ typeof x"),
- testExpression(r"var $supportsProtoName = !!{}.__proto__"),
- // ++ used as a binary operator.
- testError("x++ ++ 42"),
- // Shift operators.
- testExpression("x << 5"),
- testExpression("x << y + 1"),
- testExpression("x <<= y + 1"),
- // Array initializers.
- testExpression("x = ['foo', 'bar', x[4]]"),
- testExpression("[]"),
- testError("[42 42]"),
- testExpression('beebop([1, 2, 3])'),
- // Array literals with holes in them.
- testExpression("[1,, 2]"),
- testExpression("[1,]", "[1]"),
- testExpression("[1,,]", "[1,,]"),
- testExpression("[,]"),
- testExpression("[,,]"),
- testExpression("[, 42]"),
- // Ternary operator.
- testExpression("x = a ? b : c"),
- testExpression("y = a == null ? b : a"),
- testExpression("y = a == null ? b + c : a + c"),
- testExpression("foo = a ? b : c ? d : e"),
- testExpression("foo = a ? b ? c : d : e"),
- testExpression("foo = (a = v) ? b = w : c = x ? d = y : e = z"),
- testExpression("foo = (a = v) ? b = w ? c = x : d = y : e = z"),
- // Stacked assignment.
- testExpression("a = b = c"),
- testExpression("var a = b = c"),
- ]));
+ // Asterisk indicates deviations from real JS.
+ // Simple var test.
+ testExpression('var a = ""'),
+ // Parse and print will normalize whitespace.
+ testExpression(' var a = "" ', 'var a = ""'),
+ // Operator precedence.
+ testExpression('x = a + b * c'),
+ testExpression('x = a * b + c'),
+ testExpression('x = a + b * c + d'),
+ testExpression('x = a * b + c * d'),
+ testExpression('remaining = (remaining / 88) | 0',
+ 'remaining = remaining / 88 | 0'),
+ // Binary operators have left associativity.
+ testExpression('x = a + b + c'),
+ // We can cope with relational operators and non-relational.
+ testExpression('a + b == c + d'),
+ // The prettyprinter will insert braces where needed.
+ testExpression('a + (b == c) + d'),
+ // We can handle () for calls.
+ testExpression('foo(bar)'),
+ testExpression('foo(bar, baz)'),
+ // Chained calls without parentheses.
+ testExpression('foo(bar)(baz)'),
+ // Chaned calls with and without new.
+ testExpression('new foo(bar)(baz)'),
+ testExpression('new foo.bar(bar)(baz)'),
+ testExpression('foo.bar(bar)(baz)'),
+ testExpression('constructor = new Function(str)()'),
+ // The prettyprinter understands chained calls without extra parentheses.
+ testExpression('(foo(bar))(baz)', 'foo(bar)(baz)'),
+ // Chains of dotting and calls.
+ testExpression('foo.bar(baz)'),
+ // String literal.
+ testExpression('var x = "fisk"'),
+ // String literal with \n.
+ testExpression(r'var x = "\n"'),
+ // String literal with escaped quote.
+ testExpression(r'var x = "\""'),
+ // *No clever escapes.
+ testError(r'var x = "\x42"', 'escapes are not allowed in literals'),
+ // Operator new.
+ testExpression('new Foo()'),
+ // New with dotted access.
+ testExpression('new Frobinator.frobinate()'),
+ testExpression('new Frobinator().frobinate()'),
+ // The prettyprinter strips some superfluous parentheses.
+ testExpression(
+ '(new Frobinator()).frobinate()', 'new Frobinator().frobinate()'),
+ // *We want a bracket on 'new'.
+ testError('new Foo', 'Parentheses are required'),
+ testError('(new Foo)', 'Parentheses are required'),
+ // Bogus operators.
+ testError('a +++ b', 'Unknown operator'),
+ // This isn't perl. There are rules.
+ testError('a <=> b', 'Unknown operator'),
+ // Typeof.
+ testExpression('typeof foo == "number"'),
+ // Strange relation.
+ testExpression('a < b < c'),
+ // Chained var.
+ testExpression('var x = 0, y = 1.2, z = 42'),
+ // Empty object literal.
+ testExpression('foo({}, {})'),
+ // *Can't handle non-empty object literals
+ testExpression('foo({meaning: 42})'),
+ // Literals.
+ testExpression('x(false, true, null)'),
+ // *We should really throw here.
+ testExpression('var false = 42'),
+ testExpression('var new = 42'),
+ // Bad keyword.
+ testError('var typeof = 42', "Expected ALPHA"),
+ // Malformed decimal/hex.
+ testError('var x = 1.1.1', "Unparseable number"),
+ testError('var x = 0xabcdefga', "Unparseable number"),
+ testError('var x = 0xabcdef\$a', "Unparseable number"),
+ testError('var x = 0x ', "Unparseable number"),
+ // Good hex constants.
+ testExpression('var x = 0xff'),
+ testExpression('var x = 0xff + 0xff'),
+ testExpression('var x = 0xaF + 0x0123456789abcdefABCDEF'),
+ // All sorts of keywords are allowed as property names in ES5.
+ testExpression('x.new = 0'),
+ testExpression('x.delete = 0'),
+ testExpression('x.for = 0'),
+ testExpression('x.instanceof = 0'),
+ testExpression('x.in = 0'),
+ testExpression('x.void = 0'),
+ testExpression('x.continue = 0'),
+ // More unary.
+ testExpression('x = !x'),
+ testExpression('!x == false'),
+ testExpression('var foo = void 0'),
+ testExpression('delete foo.bar'),
+ testExpression('delete foo'),
+ testExpression('x in y'),
+ testExpression('x instanceof y'),
+ testExpression('a * b in c * d'),
+ testExpression('a * b instanceof c * d'),
+ testError('x typeof y', 'Unparsed junk'),
+ testExpression('x &= ~mask'),
+ // Await is parsed as an unary prefix operator.
+ testExpression('var foo = await 0'),
+ testExpression('await x++'),
+ testExpression('void (await (x++))', 'void await x++'),
+ testExpression('void (await x)++'),
+ testExpression('++(await x)++'),
+ // Adjacent tokens.
+ testExpression('foo[x[bar]]'),
+ testExpression('foo[[bar]]'),
+ // Prefix ++ etc.
+ testExpression("++x"),
+ testExpression("++foo.bar"),
+ testExpression("+x"),
+ testExpression("+foo.bar"),
+ testExpression("-x"),
+ testExpression("-foo.bar"),
+ testExpression("--x"),
+ testExpression("--foo.bar"),
+ // Postfix ++ etc.
+ testExpression("x++"),
+ testExpression("foo.bar++"),
+ testExpression("x--"),
+ testExpression("foo.bar--"),
+ // Both!
+ testExpression("++x++"),
+ testExpression("++foo.bar++"),
+ testExpression("--x--"),
+ testExpression("--foo.bar--"),
+ // *We can't handle stacked unary operators (apart from !).
+ testError("x++ ++"),
+ testError("++ typeof x"),
+ testExpression(r"var $supportsProtoName = !!{}.__proto__"),
+ // ++ used as a binary operator.
+ testError("x++ ++ 42"),
+ // Shift operators.
+ testExpression("x << 5"),
+ testExpression("x << y + 1"),
+ testExpression("x <<= y + 1"),
+ // Array initializers.
+ testExpression("x = ['foo', 'bar', x[4]]"),
+ testExpression("[]"),
+ testError("[42 42]"),
+ testExpression('beebop([1, 2, 3])'),
+ // Array literals with holes in them.
+ testExpression("[1,, 2]"),
+ testExpression("[1,]", "[1]"),
+ testExpression("[1,,]", "[1,,]"),
+ testExpression("[,]"),
+ testExpression("[,,]"),
+ testExpression("[, 42]"),
+ // Ternary operator.
+ testExpression("x = a ? b : c"),
+ testExpression("y = a == null ? b : a"),
+ testExpression("y = a == null ? b + c : a + c"),
+ testExpression("foo = a ? b : c ? d : e"),
+ testExpression("foo = a ? b ? c : d : e"),
+ testExpression("foo = (a = v) ? b = w : c = x ? d = y : e = z"),
+ testExpression("foo = (a = v) ? b = w ? c = x : d = y : e = z"),
+ // Stacked assignment.
+ testExpression("a = b = c"),
+ testExpression("var a = b = c"),
+ ]));
}
diff --git a/tests/compiler/dart2js/js_safety_test.dart b/tests/compiler/dart2js/js_safety_test.dart
index 140f4b6..9a2df54 100644
--- a/tests/compiler/dart2js/js_safety_test.dart
+++ b/tests/compiler/dart2js/js_safety_test.dart
@@ -6,14 +6,13 @@
import 'package:compiler/src/js/js.dart' as js;
import 'package:compiler/src/js/placeholder_safety.dart';
-void test(String source, int expected, {List notNull: const[]}) {
- var predicate = (int pos) => ! notNull.contains(pos);
+void test(String source, int expected, {List notNull: const []}) {
+ var predicate = (int pos) => !notNull.contains(pos);
js.Template template = js.js.parseForeignJS(source);
int actual = PlaceholderSafetyAnalysis.analyze(template.ast, predicate);
Expect.equals(expected, actual, 'source: "$source", notNull: $notNull');
}
-
void main() {
test('0', 0);
@@ -39,7 +38,7 @@
test('#.x == 1 || # == 1', 1);
test('# == 1 || #.x == 1', 1);
- test('(# || 1, #)', 1); // Could also be 2.
+ test('(# || 1, #)', 1); // Could also be 2.
test('(#, null.a, #)', 1);
test('(#, undefined.a, #)', 1);
@@ -96,7 +95,7 @@
test('# ? # : #', 1);
test('(# ? 1 : #, #)', 1);
test('(# ? # : 2, #)', 1);
- test('(# ? 1 : 2, #)', 1); // Could also be 4.
+ test('(# ? 1 : 2, #)', 1); // Could also be 4.
test('{A:#, B:#, C:#}', 3);
test('[#,#,#,#]', 4);
diff --git a/tests/compiler/dart2js/js_spec_optimization_test.dart b/tests/compiler/dart2js/js_spec_optimization_test.dart
index 3c03c09..822175e 100644
--- a/tests/compiler/dart2js/js_spec_optimization_test.dart
+++ b/tests/compiler/dart2js/js_spec_optimization_test.dart
@@ -57,7 +57,6 @@
}
""";
-
main() {
RegExp directivePattern = new RegExp(
// \1 \2 \3
@@ -88,8 +87,8 @@
}
asyncTest(() => Future.wait([
- check(TEST_1),
- check(TEST_2),
- check(TEST_3),
- ]));
+ check(TEST_1),
+ check(TEST_2),
+ check(TEST_3),
+ ]));
}
diff --git a/tests/compiler/dart2js/js_spec_string_test.dart b/tests/compiler/dart2js/js_spec_string_test.dart
index fdd59da..bf18bce 100644
--- a/tests/compiler/dart2js/js_spec_string_test.dart
+++ b/tests/compiler/dart2js/js_spec_string_test.dart
@@ -8,8 +8,7 @@
import 'package:compiler/src/native/native.dart';
import 'package:compiler/src/diagnostics/diagnostic_listener.dart';
import 'package:compiler/src/diagnostics/messages.dart';
-import 'package:compiler/src/universe/side_effects.dart'
- show SideEffects;
+import 'package:compiler/src/universe/side_effects.dart' show SideEffects;
const OBJECT = 'Object';
const NULL = 'Null';
@@ -38,13 +37,13 @@
}
void test(String specString,
- {List returns,
- List creates,
- SideEffects expectedSideEffects,
- NativeThrowBehavior expectedThrows,
- bool expectedNew,
- bool expectedGvn,
- bool expectError: false}) {
+ {List returns,
+ List creates,
+ SideEffects expectedSideEffects,
+ NativeThrowBehavior expectedThrows,
+ bool expectedNew,
+ bool expectedGvn,
+ bool expectError: false}) {
List actualReturns = [];
List actualCreates = [];
SideEffects actualSideEffects;
@@ -53,17 +52,16 @@
bool actualGvn;
Listener listener = new Listener();
try {
- NativeBehavior.processSpecString(
- listener,
- null,
- specString,
- setSideEffects: (effects) { actualSideEffects = effects; },
- setThrows: (b) { actualThrows = b; },
- setIsAllocation: (b) { actualNew = b; },
- setUseGvn: (b) { actualGvn = b; },
+ NativeBehavior.processSpecString(listener, null, specString,
+ setSideEffects: (effects) => actualSideEffects = effects,
+ setThrows: (b) => actualThrows = b,
+ setIsAllocation: (b) => actualNew = b,
+ setUseGvn: (b) => actualGvn = b,
resolveType: (t) => t,
- typesReturned: actualReturns, typesInstantiated: actualCreates,
- objectType: OBJECT, nullType: NULL);
+ typesReturned: actualReturns,
+ typesInstantiated: actualCreates,
+ objectType: OBJECT,
+ nullType: NULL);
} catch (e) {
Expect.isTrue(expectError, 'Unexpected error "$specString"');
Expect.isNotNull(listener.errorMessage, 'Error message expected.');
@@ -84,30 +82,23 @@
}
void testWithSideEffects(String specString,
- {List returns,
- List creates,
- bool expectError: false}) {
-
+ {List returns, List creates, bool expectError: false}) {
void sideEffectsTest(String newSpecString, SideEffects expectedSideEffects,
- {bool sideEffectsExpectError}) {
+ {bool sideEffectsExpectError}) {
test(newSpecString,
- returns: returns,
- creates: creates,
- expectedSideEffects: expectedSideEffects,
- expectError: sideEffectsExpectError == null
- ? expectError
- : sideEffectsExpectError);
+ returns: returns,
+ creates: creates,
+ expectedSideEffects: expectedSideEffects,
+ expectError: sideEffectsExpectError == null
+ ? expectError
+ : sideEffectsExpectError);
}
SideEffects emptySideEffects = new SideEffects.empty();
- sideEffectsTest(specString + "effects:none;depends:none;",
- emptySideEffects);
- sideEffectsTest(specString + "depends:none;effects:none;",
- emptySideEffects);
- sideEffectsTest("effects:none;depends:none;" + specString,
- emptySideEffects);
- sideEffectsTest("depends:none;effects:none;" + specString,
- emptySideEffects);
+ sideEffectsTest(specString + "effects:none;depends:none;", emptySideEffects);
+ sideEffectsTest(specString + "depends:none;effects:none;", emptySideEffects);
+ sideEffectsTest("effects:none;depends:none;" + specString, emptySideEffects);
+ sideEffectsTest("depends:none;effects:none;" + specString, emptySideEffects);
SideEffects effects = new SideEffects();
effects.clearChangesIndex();
@@ -123,15 +114,15 @@
effects.clearChangesInstanceProperty();
effects.clearChangesStaticProperty();
effects.clearAllDependencies();
- sideEffectsTest(specString + "effects:no-instance,no-static;depends:none;",
- effects);
+ sideEffectsTest(
+ specString + "effects:no-instance,no-static;depends:none;", effects);
effects = new SideEffects();
effects.clearAllSideEffects();
effects.clearDependsOnInstancePropertyStore();
effects.clearDependsOnStaticPropertyStore();
- sideEffectsTest(specString + "effects:none;depends:no-instance,no-static;",
- effects);
+ sideEffectsTest(
+ specString + "effects:none;depends:no-instance,no-static;", effects);
effects = new SideEffects();
effects.clearChangesInstanceProperty();
@@ -158,54 +149,46 @@
effects = new SideEffects();
effects.clearChangesInstanceProperty();
effects.clearChangesStaticProperty();
- sideEffectsTest(specString + "effects:no-instance,no-static;depends:all;",
- effects);
+ sideEffectsTest(
+ specString + "effects:no-instance,no-static;depends:all;", effects);
effects = new SideEffects();
effects.clearDependsOnInstancePropertyStore();
effects.clearDependsOnStaticPropertyStore();
- sideEffectsTest(specString + "effects:all;depends:no-instance,no-static;",
- effects);
+ sideEffectsTest(
+ specString + "effects:all;depends:no-instance,no-static;", effects);
- sideEffectsTest(specString + "effects:no-instance,no-static;",
- effects,
- sideEffectsExpectError: true);
+ sideEffectsTest(specString + "effects:no-instance,no-static;", effects,
+ sideEffectsExpectError: true);
- sideEffectsTest(specString + "depends:no-instance,no-static;",
- effects,
- sideEffectsExpectError: true);
+ sideEffectsTest(specString + "depends:no-instance,no-static;", effects,
+ sideEffectsExpectError: true);
- sideEffectsTest(specString + "effects:none;",
- effects,
- sideEffectsExpectError: true);
+ sideEffectsTest(specString + "effects:none;", effects,
+ sideEffectsExpectError: true);
- sideEffectsTest(specString + "depends:all;",
- effects,
- sideEffectsExpectError: true);
+ sideEffectsTest(specString + "depends:all;", effects,
+ sideEffectsExpectError: true);
- sideEffectsTest(specString + "effects:no-instance,no-static;depends:foo;",
- effects,
- sideEffectsExpectError: true);
+ sideEffectsTest(
+ specString + "effects:no-instance,no-static;depends:foo;", effects,
+ sideEffectsExpectError: true);
- sideEffectsTest(specString + "effects:foo;depends:no-instance,no-static;",
- effects,
- sideEffectsExpectError: true);
+ sideEffectsTest(
+ specString + "effects:foo;depends:no-instance,no-static;", effects,
+ sideEffectsExpectError: true);
- sideEffectsTest(specString + "effects:all;depends:foo",
- effects,
- sideEffectsExpectError: true);
+ sideEffectsTest(specString + "effects:all;depends:foo", effects,
+ sideEffectsExpectError: true);
- sideEffectsTest(specString + "effects:foo;depends:none;",
- effects,
- sideEffectsExpectError: true);
+ sideEffectsTest(specString + "effects:foo;depends:none;", effects,
+ sideEffectsExpectError: true);
- sideEffectsTest(specString + "effects:;depends:none;",
- effects,
- sideEffectsExpectError: true);
+ sideEffectsTest(specString + "effects:;depends:none;", effects,
+ sideEffectsExpectError: true);
- sideEffectsTest(specString + "effects:all;depends:;",
- effects,
- sideEffectsExpectError: true);
+ sideEffectsTest(specString + "effects:all;depends:;", effects,
+ sideEffectsExpectError: true);
}
void main() {
@@ -242,8 +225,7 @@
test('returns:var;creates:A|B|C;',
returns: [OBJECT, NULL], creates: ['A', 'B', 'C']);
test('returns:A; creates:A|B|C; ', returns: ['A'], creates: ['A', 'B', 'C']);
- test(' returns:A|B; creates:A|C;',
- returns: ['A', 'B'], creates: ['A', 'C']);
+ test(' returns:A|B; creates:A|C;', returns: ['A', 'B'], creates: ['A', 'C']);
test(' returns:A|B|C; creates:A; ',
returns: ['A', 'B', 'C'], creates: ['A']);
@@ -252,8 +234,7 @@
testWithSideEffects('returns:;', returns: [OBJECT, NULL], creates: []);
testWithSideEffects('returns:var;', returns: [OBJECT, NULL], creates: []);
testWithSideEffects('returns:A;', returns: ['A'], creates: ['A']);
- testWithSideEffects('returns:A|B;',
- returns: ['A', 'B'], creates: ['A', 'B']);
+ testWithSideEffects('returns:A|B;', returns: ['A', 'B'], creates: ['A', 'B']);
testWithSideEffects('returns:A|B|C;',
returns: ['A', 'B', 'C'], creates: ['A', 'B', 'C']);
testWithSideEffects('returns: A| B |C ;',
diff --git a/tests/compiler/dart2js/js_throw_behavior_test.dart b/tests/compiler/dart2js/js_throw_behavior_test.dart
index 45d2790..e0b75b9 100644
--- a/tests/compiler/dart2js/js_throw_behavior_test.dart
+++ b/tests/compiler/dart2js/js_throw_behavior_test.dart
@@ -94,6 +94,6 @@
test('throw 123', MUST);
test('throw #', MUST);
- test('throw #.x', MUST); // Could be better: is also an NSM guard.
+ test('throw #.x', MUST); // Could be better: is also an NSM guard.
test('throw #.x = 123', MUST);
}
diff --git a/tests/compiler/dart2js/jsinterop/abstract_test.dart b/tests/compiler/dart2js/jsinterop/abstract_test.dart
index 1579fa3..3233e87 100644
--- a/tests/compiler/dart2js/jsinterop/abstract_test.dart
+++ b/tests/compiler/dart2js/jsinterop/abstract_test.dart
@@ -12,9 +12,8 @@
void main() {
asyncTest(() async {
DiagnosticCollector collector = new DiagnosticCollector();
- await runCompiler(
- diagnosticHandler: collector,
- memorySourceFiles: const {'main.dart': '''
+ await runCompiler(diagnosticHandler: collector, memorySourceFiles: const {
+ 'main.dart': '''
import 'package:js/js.dart';
@JS()
@@ -23,13 +22,11 @@
}
main() => new A();
-'''});
- Expect.equals(0, collector.errors.length,
- 'Unexpected error count.');
- Expect.equals(1, collector.warnings.length,
- 'Unexpected warning count.');
+'''
+ });
+ Expect.equals(0, collector.errors.length, 'Unexpected error count.');
+ Expect.equals(1, collector.warnings.length, 'Unexpected warning count.');
Expect.equals(MessageKind.ABSTRACT_GETTER,
- collector.warnings.first.messageKind,
- 'Unexpected warning.');
+ collector.warnings.first.messageKind, 'Unexpected warning.');
});
-}
\ No newline at end of file
+}
diff --git a/tests/compiler/dart2js/jsinterop/world_test.dart b/tests/compiler/dart2js/jsinterop/world_test.dart
index f196b8e..185e092 100644
--- a/tests/compiler/dart2js/jsinterop/world_test.dart
+++ b/tests/compiler/dart2js/jsinterop/world_test.dart
@@ -7,8 +7,7 @@
import 'package:expect/expect.dart';
import 'package:async_helper/async_helper.dart';
import 'package:compiler/src/common.dart';
-import 'package:compiler/src/elements/elements.dart'
- show Element, ClassElement;
+import 'package:compiler/src/elements/elements.dart' show Element, ClassElement;
import 'package:compiler/src/js_backend/js_backend.dart';
import 'package:compiler/src/world.dart';
import '../type_test_helper.dart';
@@ -22,8 +21,9 @@
testClasses() async {
test(String mainSource,
{List<String> directlyInstantiated: const <String>[],
- List<String> indirectlyInstantiated: const <String>[]}) async {
- TypeEnvironment env = await TypeEnvironment.create(r"""
+ List<String> indirectlyInstantiated: const <String>[]}) async {
+ TypeEnvironment env = await TypeEnvironment.create(
+ r"""
@JS()
class A {
get foo;
@@ -72,11 +72,13 @@
newD() => new D(foo: 3);
newE() => new E(4);
newF() => new F(5);
-""", mainSource: """
+""",
+ mainSource: """
import 'package:js/js.dart';
$mainSource
-""", useMockCompiler: false);
+""",
+ useMockCompiler: false);
Map<String, ClassElement> classEnvironment = <String, ClassElement>{};
ClassElement registerClass(ClassElement cls) {
@@ -113,20 +115,23 @@
bool isInstantiated = false;
if (directlyInstantiated.contains(name)) {
isInstantiated = true;
- Expect.isTrue(world.isDirectlyInstantiated(cls),
+ Expect.isTrue(
+ world.isDirectlyInstantiated(cls),
"Expected $name to be directly instantiated in `${mainSource}`:"
- "\n${world.dump(cls)}");
+ "\n${world.dump(cls)}");
}
if (indirectlyInstantiated.contains(name)) {
isInstantiated = true;
- Expect.isTrue(world.isIndirectlyInstantiated(cls),
+ Expect.isTrue(
+ world.isIndirectlyInstantiated(cls),
"Expected $name to be indirectly instantiated in `${mainSource}`:"
- "\n${world.dump(cls)}");
+ "\n${world.dump(cls)}");
}
if (!isInstantiated && (name != 'Object' && name != 'Interceptor')) {
- Expect.isFalse(world.isInstantiated(cls),
+ Expect.isFalse(
+ world.isInstantiated(cls),
"Expected $name to be uninstantiated in `${mainSource}`:"
- "\n${world.dump(cls)}");
+ "\n${world.dump(cls)}");
}
}
}
@@ -149,11 +154,9 @@
directlyInstantiated: ['A', 'B', 'C', 'D'],
indirectlyInstantiated: ['Object', 'Interceptor', 'JavaScriptObject']);
- await test('main() => newE();',
- directlyInstantiated: ['E']);
+ await test('main() => newE();', directlyInstantiated: ['E']);
- await test('main() => newF();',
- directlyInstantiated: ['F']);
+ await test('main() => newF();', directlyInstantiated: ['F']);
await test('main() => [newD(), newE()];',
directlyInstantiated: ['A', 'B', 'C', 'D', 'E'],
diff --git a/tests/compiler/dart2js/kernel/helper.dart b/tests/compiler/dart2js/kernel/helper.dart
index 30512d8..4e89025 100644
--- a/tests/compiler/dart2js/kernel/helper.dart
+++ b/tests/compiler/dart2js/kernel/helper.dart
@@ -6,14 +6,15 @@
import 'package:compiler/src/compiler.dart' show Compiler;
import 'package:compiler/src/elements/elements.dart' show Element;
-import 'package:compiler/src/js_backend/backend.dart' as js show JavaScriptBackend;
+import 'package:compiler/src/js_backend/backend.dart' as js
+ show JavaScriptBackend;
import 'package:compiler/src/commandline_options.dart' show Flags;
import 'package:test/test.dart';
import '../memory_compiler.dart';
-Future<String> compile(String code, {String entry: 'main',
- bool useKernel: true}) async {
+Future<String> compile(String code,
+ {String entry: 'main', bool useKernel: true}) async {
List<String> options = <String>[
Flags.disableTypeInference,
Flags.disableInlining,
@@ -24,8 +25,7 @@
code = "$code\n\nmain() => $entry;";
}
CompilationResult result = await runCompiler(
- memorySourceFiles: {'main.dart': code},
- options: options);
+ memorySourceFiles: {'main.dart': code}, options: options);
expect(result.isSuccess, isTrue);
Compiler compiler = result.compiler;
Element element = compiler.mainApp.find(entry);
diff --git a/tests/compiler/dart2js/kernel/impact_test.dart b/tests/compiler/dart2js/kernel/impact_test.dart
index 0720bca..9581e13 100644
--- a/tests/compiler/dart2js/kernel/impact_test.dart
+++ b/tests/compiler/dart2js/kernel/impact_test.dart
@@ -18,6 +18,8 @@
const Map<String, String> SOURCE = const <String, String>{
'main.dart': '''
+import 'helper.dart';
+
main() {
testEmpty();
testNull();
@@ -39,8 +41,29 @@
testNonEmptyMapLiteral();
testNot();
testUnaryMinus();
+ testConditional();
+ testPostInc(null);
+ testPostDec(null);
+ testPreInc(null);
+ testPreDec(null);
testIfThen();
testIfThenElse();
+ testTopLevelInvoke();
+ testTopLevelInvokeTyped();
+ testTopLevelField();
+ testTopLevelFieldTyped();
+ testDynamicInvoke(null);
+ testDynamicGet(null);
+ testDynamicSet(null);
+ testLocalWithInitializer();
+ testInvokeIndex(null);
+ testInvokeIndexSet(null);
+ testAssert();
+ testAssertWithMessage();
+ testFactoryInvoke();
+ testFactoryInvokeGeneric();
+ testFactoryInvokeGenericRaw();
+ testFactoryInvokeGenericDynamic();
}
testEmpty() {}
@@ -63,6 +86,11 @@
testNonEmptyMapLiteral() => {0: true};
testNot() => !false;
testUnaryMinus() => -1;
+testConditional() => true ? 1 : '';
+testPostInc(o) => o++;
+testPostDec(o) => o--;
+testPreInc(o) => ++o;
+testPreDec(o) => --o;
testIfThen() {
if (false) return 42;
return 1;
@@ -74,7 +102,85 @@
return 1;
}
}
-'''
+topLevelFunction1(a) {}
+topLevelFunction2(a, [b, c]) {}
+topLevelFunction3(a, {b, c}) {}
+testTopLevelInvoke() {
+ topLevelFunction1(0);
+ topLevelFunction2(1);
+ topLevelFunction2(2, 3);
+ topLevelFunction2(4, 5, 6);
+ topLevelFunction3(7);
+ topLevelFunction3(8, b: 9);
+ topLevelFunction3(10, c: 11);
+ topLevelFunction3(12, b: 13, c: 14);
+ topLevelFunction3(15, c: 16, b: 17);
+}
+void topLevelFunction1Typed(int a) {}
+int topLevelFunction2Typed(String a, [num b, double c]) => null;
+double topLevelFunction3Typed(bool a, {List<int> b, Map<String, bool> c}) {
+ return null;
+}
+testTopLevelInvokeTyped() {
+ topLevelFunction1Typed(0);
+ topLevelFunction2Typed('1');
+ topLevelFunction2Typed('2', 3);
+ topLevelFunction2Typed('3', 5, 6.0);
+ topLevelFunction3Typed(true);
+ topLevelFunction3Typed(false, b: []);
+ topLevelFunction3Typed(null, c: {});
+ topLevelFunction3Typed(true, b: [13], c: {'14': true});
+ topLevelFunction3Typed(false, c: {'16': false}, b: [17]);
+}
+var topLevelField;
+testTopLevelField() => topLevelField;
+int topLevelFieldTyped;
+testTopLevelFieldTyped() => topLevelFieldTyped;
+testDynamicInvoke(o) {
+ o.f1(0);
+ o.f2(1);
+ o.f3(2, 3);
+ o.f4(4, 5, 6);
+ o.f5(7);
+ o.f6(8, b: 9);
+ o.f7(10, c: 11);
+ o.f8(12, b: 13, c: 14);
+ o.f9(15, c: 16, b: 17);
+}
+testDynamicGet(o) => o.foo;
+testDynamicSet(o) => o.foo = 42;
+testLocalWithInitializer() {
+ var l = 42;
+}
+testInvokeIndex(o) => o[42];
+testInvokeIndexSet(o) => o[42] = null;
+testAssert() {
+ assert(true);
+}
+testAssertWithMessage() {
+ assert(true, 'ok');
+}
+testFactoryInvoke() {
+ new Class.fact();
+}
+testFactoryInvokeGeneric() {
+ new GenericClass<int, String>.fact();
+}
+testFactoryInvokeGenericRaw() {
+ new GenericClass.fact();
+}
+testFactoryInvokeGenericDynamic() {
+ new GenericClass<dynamic, dynamic>.fact();
+}
+''',
+ 'helper.dart': '''
+class Class {
+ factory Class.fact() => null;
+}
+class GenericClass<X, Y> {
+ factory GenericClass.fact() => null;
+}
+''',
};
main(List<String> args) {
@@ -84,11 +190,24 @@
Compiler compiler = compilerFor(
entryPoint: entryPoint,
memorySourceFiles: SOURCE,
- options: [Flags.analyzeOnly, Flags.useKernel]);
+ options: [
+ Flags.analyzeAll,
+ Flags.useKernel,
+ Flags.enableAssertMessage
+ ]);
compiler.resolution.retainCachesForTesting = true;
await compiler.run(entryPoint);
- compiler.mainApp
- .forEachLocalMember((element) => checkElement(compiler, element));
+ checkLibrary(compiler, compiler.mainApp);
+ });
+}
+
+void checkLibrary(Compiler compiler, LibraryElement library) {
+ library.forEachLocalMember((AstElement element) {
+ if (element.isClass) {
+ // TODO(johnniwinther): Handle class members.
+ } else {
+ checkElement(compiler, element);
+ }
});
}
diff --git a/tests/compiler/dart2js/kernel/literals_test.dart b/tests/compiler/dart2js/kernel/literals_test.dart
new file mode 100644
index 0000000..bf84989
--- /dev/null
+++ b/tests/compiler/dart2js/kernel/literals_test.dart
@@ -0,0 +1,22 @@
+// Copyright (c) 2016, 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/test.dart';
+
+import 'helper.dart' show check;
+
+main() {
+ test('compile function that returns a literal list', () {
+ return check('main() { return [1, 2, 3]; }');
+ });
+ test('compile function that returns a const list', () {
+ return check('main() { return const [1, 2, 3]; }');
+ });
+ test('compile function that returns a literal map', () {
+ return check('main() { return {"a": 1, "b": 2, "c": 3}; }');
+ });
+ test('compile function that returns a literal map', () {
+ return check('main() { return const {"a": 1, "b": 2, "c": 3}; }');
+ });
+}
diff --git a/tests/compiler/dart2js/least_upper_bound_language_test.dart b/tests/compiler/dart2js/least_upper_bound_language_test.dart
index ad01ad0..53d5900 100644
--- a/tests/compiler/dart2js/least_upper_bound_language_test.dart
+++ b/tests/compiler/dart2js/least_upper_bound_language_test.dart
@@ -13,8 +13,8 @@
/// can contain a list of line numbers for keys 'missing' and 'unexpected' for
/// the warnings of each category.
const Map<String, dynamic> TESTS = const {
- 'language/least_upper_bound_test.dart': null,
- 'language/least_upper_bound_expansive_test.dart': null,
+ 'language/least_upper_bound_test.dart': null,
+ 'language/least_upper_bound_expansive_test.dart': null,
};
void main() {
diff --git a/tests/compiler/dart2js/least_upper_bound_test.dart b/tests/compiler/dart2js/least_upper_bound_test.dart
index 7f15f88..c184635 100644
--- a/tests/compiler/dart2js/least_upper_bound_test.dart
+++ b/tests/compiler/dart2js/least_upper_bound_test.dart
@@ -7,8 +7,7 @@
import 'package:expect/expect.dart';
import 'package:async_helper/async_helper.dart';
import 'package:compiler/src/dart_types.dart';
-import 'package:compiler/src/elements/elements.dart'
- show Element, ClassElement;
+import 'package:compiler/src/elements/elements.dart' show Element, ClassElement;
import 'type_test_helper.dart';
@@ -28,49 +27,48 @@
class I implements A, B {}
class J implements A, B {}
""").then((env) {
+ DartType Object_ = env['Object'];
+ DartType A = env['A'];
+ DartType B = env['B'];
+ DartType I = env['I'];
+ DartType J = env['J'];
- DartType Object_ = env['Object'];
- DartType A = env['A'];
- DartType B = env['B'];
- DartType I = env['I'];
- DartType J = env['J'];
+ checkLub(DartType a, DartType b, DartType expect) {
+ DartType lub = env.computeLeastUpperBound(a, b);
+ Expect.equals(
+ expect, lub, 'Unexpected lub($a,$b) = $lub, expected $expect.');
+ }
- checkLub(DartType a, DartType b, DartType expect) {
- DartType lub = env.computeLeastUpperBound(a, b);
- Expect.equals(expect, lub,
- 'Unexpected lub($a,$b) = $lub, expected $expect.');
- }
+ checkLub(Object_, Object_, Object_);
+ checkLub(Object_, A, Object_);
+ checkLub(Object_, B, Object_);
+ checkLub(Object_, I, Object_);
+ checkLub(Object_, J, Object_);
- checkLub(Object_, Object_, Object_);
- checkLub(Object_, A, Object_);
- checkLub(Object_, B, Object_);
- checkLub(Object_, I, Object_);
- checkLub(Object_, J, Object_);
+ checkLub(A, Object_, Object_);
+ checkLub(A, A, A);
+ checkLub(A, B, Object_);
+ checkLub(A, I, A);
+ checkLub(A, J, A);
- checkLub(A, Object_, Object_);
- checkLub(A, A, A);
- checkLub(A, B, Object_);
- checkLub(A, I, A);
- checkLub(A, J, A);
+ checkLub(B, Object_, Object_);
+ checkLub(B, A, Object_);
+ checkLub(B, B, B);
+ checkLub(B, I, B);
+ checkLub(B, J, B);
- checkLub(B, Object_, Object_);
- checkLub(B, A, Object_);
- checkLub(B, B, B);
- checkLub(B, I, B);
- checkLub(B, J, B);
+ checkLub(I, Object_, Object_);
+ checkLub(I, A, A);
+ checkLub(I, B, B);
+ checkLub(I, I, I);
+ checkLub(I, J, Object_);
- checkLub(I, Object_, Object_);
- checkLub(I, A, A);
- checkLub(I, B, B);
- checkLub(I, I, I);
- checkLub(I, J, Object_);
-
- checkLub(J, Object_, Object_);
- checkLub(J, A, A);
- checkLub(J, B, B);
- checkLub(J, I, Object_);
- checkLub(J, J, J);
- }));
+ checkLub(J, Object_, Object_);
+ checkLub(J, A, A);
+ checkLub(J, B, B);
+ checkLub(J, I, Object_);
+ checkLub(J, J, J);
+ }));
}
void testInterface2() {
@@ -81,62 +79,61 @@
class I implements A, C {}
class J implements A, C {}
""").then((env) {
+ DartType Object_ = env['Object'];
+ DartType A = env['A'];
+ DartType B = env['B'];
+ DartType C = env['C'];
+ DartType I = env['I'];
+ DartType J = env['J'];
- DartType Object_ = env['Object'];
- DartType A = env['A'];
- DartType B = env['B'];
- DartType C = env['C'];
- DartType I = env['I'];
- DartType J = env['J'];
+ checkLub(DartType a, DartType b, DartType expectedLub) {
+ DartType lub = env.computeLeastUpperBound(a, b);
+ Expect.equals(expectedLub, lub,
+ 'Unexpected lub($a,$b) = $lub, expected $expectedLub');
+ }
- checkLub(DartType a, DartType b, DartType expectedLub) {
- DartType lub = env.computeLeastUpperBound(a, b);
- Expect.equals(expectedLub, lub,
- 'Unexpected lub($a,$b) = $lub, expected $expectedLub');
- }
+ checkLub(Object_, Object_, Object_);
+ checkLub(Object_, A, Object_);
+ checkLub(Object_, B, Object_);
+ checkLub(Object_, C, Object_);
+ checkLub(Object_, I, Object_);
+ checkLub(Object_, J, Object_);
- checkLub(Object_, Object_, Object_);
- checkLub(Object_, A, Object_);
- checkLub(Object_, B, Object_);
- checkLub(Object_, C, Object_);
- checkLub(Object_, I, Object_);
- checkLub(Object_, J, Object_);
+ checkLub(A, Object_, Object_);
+ checkLub(A, A, A);
+ checkLub(A, B, Object_);
+ checkLub(A, C, Object_);
+ checkLub(A, I, A);
+ checkLub(A, J, A);
- checkLub(A, Object_, Object_);
- checkLub(A, A, A);
- checkLub(A, B, Object_);
- checkLub(A, C, Object_);
- checkLub(A, I, A);
- checkLub(A, J, A);
+ checkLub(B, Object_, Object_);
+ checkLub(B, A, Object_);
+ checkLub(B, B, B);
+ checkLub(B, C, B);
+ checkLub(B, I, B);
+ checkLub(B, J, B);
- checkLub(B, Object_, Object_);
- checkLub(B, A, Object_);
- checkLub(B, B, B);
- checkLub(B, C, B);
- checkLub(B, I, B);
- checkLub(B, J, B);
+ checkLub(C, Object_, Object_);
+ checkLub(C, A, Object_);
+ checkLub(C, B, B);
+ checkLub(C, C, C);
+ checkLub(C, I, C);
+ checkLub(C, J, C);
- checkLub(C, Object_, Object_);
- checkLub(C, A, Object_);
- checkLub(C, B, B);
- checkLub(C, C, C);
- checkLub(C, I, C);
- checkLub(C, J, C);
+ checkLub(I, Object_, Object_);
+ checkLub(I, A, A);
+ checkLub(I, B, B);
+ checkLub(I, C, C);
+ checkLub(I, I, I);
+ checkLub(I, J, C);
- checkLub(I, Object_, Object_);
- checkLub(I, A, A);
- checkLub(I, B, B);
- checkLub(I, C, C);
- checkLub(I, I, I);
- checkLub(I, J, C);
-
- checkLub(J, Object_, Object_);
- checkLub(J, A, A);
- checkLub(J, B, B);
- checkLub(J, C, C);
- checkLub(J, I, C);
- checkLub(J, J, J);
- }));
+ checkLub(J, Object_, Object_);
+ checkLub(J, A, A);
+ checkLub(J, B, B);
+ checkLub(J, C, C);
+ checkLub(J, I, C);
+ checkLub(J, J, J);
+ }));
}
void testGeneric() {
@@ -146,78 +143,77 @@
class C extends B {}
class I<T> {}
""").then((env) {
+ DartType Object_ = env['Object'];
+ DartType A = env['A'];
+ DartType B = env['B'];
+ DartType C = env['C'];
+ ClassElement I = env.getElement('I');
+ DartType I_A = instantiate(I, [A]);
+ DartType I_B = instantiate(I, [B]);
+ DartType I_C = instantiate(I, [C]);
- DartType Object_ = env['Object'];
- DartType A = env['A'];
- DartType B = env['B'];
- DartType C = env['C'];
- ClassElement I = env.getElement('I');
- DartType I_A = instantiate(I, [A]);
- DartType I_B = instantiate(I, [B]);
- DartType I_C = instantiate(I, [C]);
+ checkLub(DartType a, DartType b, DartType expectedLub) {
+ DartType lub = env.computeLeastUpperBound(a, b);
+ Expect.equals(expectedLub, lub,
+ 'Unexpected lub($a,$b) = $lub, expected $expectedLub');
+ }
- checkLub(DartType a, DartType b, DartType expectedLub) {
- DartType lub = env.computeLeastUpperBound(a, b);
- Expect.equals(expectedLub, lub,
- 'Unexpected lub($a,$b) = $lub, expected $expectedLub');
- }
+ checkLub(Object_, Object_, Object_);
+ checkLub(Object_, A, Object_);
+ checkLub(Object_, B, Object_);
+ checkLub(Object_, C, Object_);
+ checkLub(Object_, I_A, Object_);
+ checkLub(Object_, I_B, Object_);
+ checkLub(Object_, I_C, Object_);
- checkLub(Object_, Object_, Object_);
- checkLub(Object_, A, Object_);
- checkLub(Object_, B, Object_);
- checkLub(Object_, C, Object_);
- checkLub(Object_, I_A, Object_);
- checkLub(Object_, I_B, Object_);
- checkLub(Object_, I_C, Object_);
+ checkLub(A, Object_, Object_);
+ checkLub(A, A, A);
+ checkLub(A, B, Object_);
+ checkLub(A, C, Object_);
+ checkLub(A, I_A, Object_);
+ checkLub(A, I_B, Object_);
+ checkLub(A, I_C, Object_);
- checkLub(A, Object_, Object_);
- checkLub(A, A, A);
- checkLub(A, B, Object_);
- checkLub(A, C, Object_);
- checkLub(A, I_A, Object_);
- checkLub(A, I_B, Object_);
- checkLub(A, I_C, Object_);
+ checkLub(B, Object_, Object_);
+ checkLub(B, A, Object_);
+ checkLub(B, B, B);
+ checkLub(B, C, B);
+ checkLub(B, I_A, Object_);
+ checkLub(B, I_B, Object_);
+ checkLub(B, I_C, Object_);
- checkLub(B, Object_, Object_);
- checkLub(B, A, Object_);
- checkLub(B, B, B);
- checkLub(B, C, B);
- checkLub(B, I_A, Object_);
- checkLub(B, I_B, Object_);
- checkLub(B, I_C, Object_);
+ checkLub(C, Object_, Object_);
+ checkLub(C, A, Object_);
+ checkLub(C, B, B);
+ checkLub(C, C, C);
+ checkLub(C, I_A, Object_);
+ checkLub(C, I_B, Object_);
+ checkLub(C, I_C, Object_);
- checkLub(C, Object_, Object_);
- checkLub(C, A, Object_);
- checkLub(C, B, B);
- checkLub(C, C, C);
- checkLub(C, I_A, Object_);
- checkLub(C, I_B, Object_);
- checkLub(C, I_C, Object_);
+ checkLub(I_A, Object_, Object_);
+ checkLub(I_A, A, Object_);
+ checkLub(I_A, B, Object_);
+ checkLub(I_A, C, Object_);
+ checkLub(I_A, I_A, I_A);
+ checkLub(I_A, I_B, Object_);
+ checkLub(I_A, I_C, Object_);
- checkLub(I_A, Object_, Object_);
- checkLub(I_A, A, Object_);
- checkLub(I_A, B, Object_);
- checkLub(I_A, C, Object_);
- checkLub(I_A, I_A, I_A);
- checkLub(I_A, I_B, Object_);
- checkLub(I_A, I_C, Object_);
+ checkLub(I_B, Object_, Object_);
+ checkLub(I_B, A, Object_);
+ checkLub(I_B, B, Object_);
+ checkLub(I_B, C, Object_);
+ checkLub(I_B, I_A, Object_);
+ checkLub(I_B, I_B, I_B);
+ checkLub(I_B, I_C, Object_);
- checkLub(I_B, Object_, Object_);
- checkLub(I_B, A, Object_);
- checkLub(I_B, B, Object_);
- checkLub(I_B, C, Object_);
- checkLub(I_B, I_A, Object_);
- checkLub(I_B, I_B, I_B);
- checkLub(I_B, I_C, Object_);
-
- checkLub(I_C, Object_, Object_);
- checkLub(I_C, A, Object_);
- checkLub(I_C, B, Object_);
- checkLub(I_C, C, Object_);
- checkLub(I_C, I_A, Object_);
- checkLub(I_C, I_B, Object_);
- checkLub(I_C, I_C, I_C);
- }));
+ checkLub(I_C, Object_, Object_);
+ checkLub(I_C, A, Object_);
+ checkLub(I_C, B, Object_);
+ checkLub(I_C, C, Object_);
+ checkLub(I_C, I_A, Object_);
+ checkLub(I_C, I_B, Object_);
+ checkLub(I_C, I_C, I_C);
+ }));
}
void testMixin() {
@@ -230,94 +226,93 @@
class I2 extends Object with A, B implements A, D {}
class J extends Object with B, A implements A, D {}
""").then((env) {
+ DartType Object_ = env['Object'];
+ DartType A = env['A'];
+ DartType B = env['B'];
+ DartType C = env['C'];
+ DartType D = env['D'];
+ DartType I = env['I'];
+ DartType I2 = env['I2'];
+ DartType J = env['J'];
- DartType Object_ = env['Object'];
- DartType A = env['A'];
- DartType B = env['B'];
- DartType C = env['C'];
- DartType D = env['D'];
- DartType I = env['I'];
- DartType I2 = env['I2'];
- DartType J = env['J'];
+ checkLub(DartType a, DartType b, DartType expectedLub) {
+ DartType lub = env.computeLeastUpperBound(a, b);
+ Expect.equals(expectedLub, lub,
+ 'Unexpected lub($a,$b) = $lub, expected $expectedLub');
+ }
- checkLub(DartType a, DartType b, DartType expectedLub) {
- DartType lub = env.computeLeastUpperBound(a, b);
- Expect.equals(expectedLub, lub,
- 'Unexpected lub($a,$b) = $lub, expected $expectedLub');
- }
+ checkLub(Object_, Object_, Object_);
+ checkLub(Object_, A, Object_);
+ checkLub(Object_, B, Object_);
+ checkLub(Object_, C, Object_);
+ checkLub(Object_, D, Object_);
+ checkLub(Object_, I, Object_);
+ checkLub(Object_, I2, Object_);
+ checkLub(Object_, J, Object_);
- checkLub(Object_, Object_, Object_);
- checkLub(Object_, A, Object_);
- checkLub(Object_, B, Object_);
- checkLub(Object_, C, Object_);
- checkLub(Object_, D, Object_);
- checkLub(Object_, I, Object_);
- checkLub(Object_, I2, Object_);
- checkLub(Object_, J, Object_);
+ checkLub(A, Object_, Object_);
+ checkLub(A, A, A);
+ checkLub(A, B, Object_);
+ checkLub(A, C, Object_);
+ checkLub(A, D, Object_);
+ checkLub(A, I, A);
+ checkLub(A, I2, A);
+ checkLub(A, J, A);
- checkLub(A, Object_, Object_);
- checkLub(A, A, A);
- checkLub(A, B, Object_);
- checkLub(A, C, Object_);
- checkLub(A, D, Object_);
- checkLub(A, I, A);
- checkLub(A, I2, A);
- checkLub(A, J, A);
+ checkLub(B, Object_, Object_);
+ checkLub(B, A, Object_);
+ checkLub(B, B, B);
+ checkLub(B, C, B);
+ checkLub(B, D, B);
+ checkLub(B, I, B);
+ checkLub(B, I2, B);
+ checkLub(B, J, B);
- checkLub(B, Object_, Object_);
- checkLub(B, A, Object_);
- checkLub(B, B, B);
- checkLub(B, C, B);
- checkLub(B, D, B);
- checkLub(B, I, B);
- checkLub(B, I2, B);
- checkLub(B, J, B);
+ checkLub(C, Object_, Object_);
+ checkLub(C, A, Object_);
+ checkLub(C, B, B);
+ checkLub(C, C, C);
+ checkLub(C, D, C);
+ checkLub(C, I, C);
+ checkLub(C, I2, C);
+ checkLub(C, J, C);
- checkLub(C, Object_, Object_);
- checkLub(C, A, Object_);
- checkLub(C, B, B);
- checkLub(C, C, C);
- checkLub(C, D, C);
- checkLub(C, I, C);
- checkLub(C, I2, C);
- checkLub(C, J, C);
+ checkLub(D, Object_, Object_);
+ checkLub(D, A, Object_);
+ checkLub(D, B, B);
+ checkLub(D, C, C);
+ checkLub(D, D, D);
+ checkLub(D, I, D);
+ checkLub(D, I2, D);
+ checkLub(D, J, D);
- checkLub(D, Object_, Object_);
- checkLub(D, A, Object_);
- checkLub(D, B, B);
- checkLub(D, C, C);
- checkLub(D, D, D);
- checkLub(D, I, D);
- checkLub(D, I2, D);
- checkLub(D, J, D);
+ checkLub(I, Object_, Object_);
+ checkLub(I, A, A);
+ checkLub(I, B, B);
+ checkLub(I, C, C);
+ checkLub(I, D, D);
+ checkLub(I, I, I);
+ checkLub(I, I2, D);
+ checkLub(I, J, D);
- checkLub(I, Object_, Object_);
- checkLub(I, A, A);
- checkLub(I, B, B);
- checkLub(I, C, C);
- checkLub(I, D, D);
- checkLub(I, I, I);
- checkLub(I, I2, D);
- checkLub(I, J, D);
+ checkLub(I2, Object_, Object_);
+ checkLub(I2, A, A);
+ checkLub(I2, B, B);
+ checkLub(I2, C, C);
+ checkLub(I2, D, D);
+ checkLub(I2, I, D);
+ checkLub(I2, I2, I2);
+ checkLub(I2, J, D);
- checkLub(I2, Object_, Object_);
- checkLub(I2, A, A);
- checkLub(I2, B, B);
- checkLub(I2, C, C);
- checkLub(I2, D, D);
- checkLub(I2, I, D);
- checkLub(I2, I2, I2);
- checkLub(I2, J, D);
-
- checkLub(J, Object_, Object_);
- checkLub(J, A, A);
- checkLub(J, B, B);
- checkLub(J, C, C);
- checkLub(J, D, D);
- checkLub(J, I, D);
- checkLub(J, I2, D);
- checkLub(J, J, J);
- }));
+ checkLub(J, Object_, Object_);
+ checkLub(J, A, A);
+ checkLub(J, B, B);
+ checkLub(J, C, C);
+ checkLub(J, D, D);
+ checkLub(J, I, D);
+ checkLub(J, I2, D);
+ checkLub(J, J, J);
+ }));
}
void testFunction() {
@@ -345,357 +340,355 @@
typedef void void____B_C({B a, C b});
typedef void void____C_C({C a, C b});
""").then((env) {
+ DartType Object_ = env['Object'];
+ DartType Function_ = env['Function'];
+ DartType dynamic__ = env['dynamic__'];
+ DartType void__ = env['void__'];
+ DartType A__ = env['A__'];
+ DartType B__ = env['B__'];
+ DartType C__ = env['C__'];
+ DartType void__A_B = env['void__A_B'];
+ DartType void__A_C = env['void__A_C'];
+ DartType void__B_A = env['void__B_A'];
+ DartType void__B_C = env['void__B_C'];
+ DartType void___B = env['void___B'];
+ DartType void___B_C = env['void___B_C'];
+ DartType void___C_C = env['void___C_C'];
+ DartType void____B = env['void____B'];
+ DartType void____B_C = env['void____B_C'];
+ DartType void____C_C = env['void____C_C'];
- DartType Object_ = env['Object'];
- DartType Function_ = env['Function'];
- DartType dynamic__ = env['dynamic__'];
- DartType void__ = env['void__'];
- DartType A__ = env['A__'];
- DartType B__ = env['B__'];
- DartType C__ = env['C__'];
- DartType void__A_B = env['void__A_B'];
- DartType void__A_C = env['void__A_C'];
- DartType void__B_A = env['void__B_A'];
- DartType void__B_C = env['void__B_C'];
- DartType void___B = env['void___B'];
- DartType void___B_C = env['void___B_C'];
- DartType void___C_C = env['void___C_C'];
- DartType void____B = env['void____B'];
- DartType void____B_C = env['void____B_C'];
- DartType void____C_C = env['void____C_C'];
+ // Types used only for checking results.
+ DartType void_ = env['void'];
+ DartType B = env['B'];
+ DartType C = env['C'];
+ FunctionType Object__ = env.functionType(Object_, []);
+ FunctionType void__Object_Object =
+ env.functionType(void_, [Object_, Object_]);
+ FunctionType void__Object_B = env.functionType(void_, [Object_, B]);
+ FunctionType void__Object_C = env.functionType(void_, [Object_, C]);
+ FunctionType void__B_Object = env.functionType(void_, [B, Object_]);
- // Types used only for checking results.
- DartType void_ = env['void'];
- DartType B = env['B'];
- DartType C = env['C'];
- FunctionType Object__ = env.functionType(Object_, []);
- FunctionType void__Object_Object =
- env.functionType(void_, [Object_, Object_]);
- FunctionType void__Object_B =
- env.functionType(void_, [Object_, B]);
- FunctionType void__Object_C =
- env.functionType(void_, [Object_, C]);
- FunctionType void__B_Object =
- env.functionType(void_, [B, Object_]);
+ checkLub(DartType a, DartType b, DartType expectedLub) {
+ DartType lub = env.computeLeastUpperBound(a, b);
+ if (a != b) {
+ expectedLub = expectedLub.unaliased;
+ lub = lub.unaliased;
+ }
+ Expect.equals(
+ expectedLub,
+ lub,
+ 'Unexpected lub(${a.unaliased},'
+ '${b.unaliased} = '
+ '${lub}, expected ${expectedLub}');
+ }
- checkLub(DartType a, DartType b, DartType expectedLub) {
- DartType lub = env.computeLeastUpperBound(a, b);
- if (a != b) {
- expectedLub = expectedLub.unaliased;
- lub = lub.unaliased;
- }
- Expect.equals(expectedLub, lub,
- 'Unexpected lub(${a.unaliased},'
- '${b.unaliased} = '
- '${lub}, expected ${expectedLub}');
- }
+ checkLub(Object_, Object_, Object_);
+ checkLub(Object_, Function_, Object_);
+ checkLub(Object_, dynamic__, Object_);
+ checkLub(Object_, void__, Object_);
+ checkLub(Object_, A__, Object_);
+ checkLub(Object_, B__, Object_);
+ checkLub(Object_, C__, Object_);
+ checkLub(Object_, void__A_B, Object_);
+ checkLub(Object_, void__A_C, Object_);
+ checkLub(Object_, void__B_A, Object_);
+ checkLub(Object_, void__B_C, Object_);
+ checkLub(Object_, void___B, Object_);
+ checkLub(Object_, void___B_C, Object_);
+ checkLub(Object_, void___C_C, Object_);
+ checkLub(Object_, void____B, Object_);
+ checkLub(Object_, void____B_C, Object_);
+ checkLub(Object_, void____C_C, Object_);
- checkLub(Object_, Object_, Object_);
- checkLub(Object_, Function_, Object_);
- checkLub(Object_, dynamic__, Object_);
- checkLub(Object_, void__, Object_);
- checkLub(Object_, A__, Object_);
- checkLub(Object_, B__, Object_);
- checkLub(Object_, C__, Object_);
- checkLub(Object_, void__A_B, Object_);
- checkLub(Object_, void__A_C, Object_);
- checkLub(Object_, void__B_A, Object_);
- checkLub(Object_, void__B_C, Object_);
- checkLub(Object_, void___B, Object_);
- checkLub(Object_, void___B_C, Object_);
- checkLub(Object_, void___C_C, Object_);
- checkLub(Object_, void____B, Object_);
- checkLub(Object_, void____B_C, Object_);
- checkLub(Object_, void____C_C, Object_);
+ checkLub(Function_, Object_, Object_);
+ checkLub(Function_, Function_, Function_);
+ checkLub(Function_, dynamic__, Function_);
+ checkLub(Function_, void__, Function_);
+ checkLub(Function_, A__, Function_);
+ checkLub(Function_, B__, Function_);
+ checkLub(Function_, C__, Function_);
+ checkLub(Function_, void__A_B, Function_);
+ checkLub(Function_, void__A_C, Function_);
+ checkLub(Function_, void__B_A, Function_);
+ checkLub(Function_, void__B_C, Function_);
+ checkLub(Function_, void___B, Function_);
+ checkLub(Function_, void___B_C, Function_);
+ checkLub(Function_, void___C_C, Function_);
+ checkLub(Function_, void____B, Function_);
+ checkLub(Function_, void____B_C, Function_);
+ checkLub(Function_, void____C_C, Function_);
- checkLub(Function_, Object_, Object_);
- checkLub(Function_, Function_, Function_);
- checkLub(Function_, dynamic__, Function_);
- checkLub(Function_, void__, Function_);
- checkLub(Function_, A__, Function_);
- checkLub(Function_, B__, Function_);
- checkLub(Function_, C__, Function_);
- checkLub(Function_, void__A_B, Function_);
- checkLub(Function_, void__A_C, Function_);
- checkLub(Function_, void__B_A, Function_);
- checkLub(Function_, void__B_C, Function_);
- checkLub(Function_, void___B, Function_);
- checkLub(Function_, void___B_C, Function_);
- checkLub(Function_, void___C_C, Function_);
- checkLub(Function_, void____B, Function_);
- checkLub(Function_, void____B_C, Function_);
- checkLub(Function_, void____C_C, Function_);
+ checkLub(dynamic__, Object_, Object_);
+ checkLub(dynamic__, Function_, Function_);
+ checkLub(dynamic__, dynamic__, dynamic__);
+ checkLub(dynamic__, void__, dynamic__);
+ checkLub(dynamic__, A__, dynamic__);
+ checkLub(dynamic__, B__, dynamic__);
+ checkLub(dynamic__, C__, dynamic__);
+ checkLub(dynamic__, void__A_B, Function_);
+ checkLub(dynamic__, void__A_C, Function_);
+ checkLub(dynamic__, void__B_A, Function_);
+ checkLub(dynamic__, void__B_C, Function_);
+ checkLub(dynamic__, void___B, dynamic__);
+ checkLub(dynamic__, void___B_C, dynamic__);
+ checkLub(dynamic__, void___C_C, dynamic__);
+ checkLub(dynamic__, void____B, dynamic__);
+ checkLub(dynamic__, void____B_C, dynamic__);
+ checkLub(dynamic__, void____C_C, dynamic__);
- checkLub(dynamic__, Object_, Object_);
- checkLub(dynamic__, Function_, Function_);
- checkLub(dynamic__, dynamic__, dynamic__);
- checkLub(dynamic__, void__, dynamic__);
- checkLub(dynamic__, A__, dynamic__);
- checkLub(dynamic__, B__, dynamic__);
- checkLub(dynamic__, C__, dynamic__);
- checkLub(dynamic__, void__A_B, Function_);
- checkLub(dynamic__, void__A_C, Function_);
- checkLub(dynamic__, void__B_A, Function_);
- checkLub(dynamic__, void__B_C, Function_);
- checkLub(dynamic__, void___B, dynamic__);
- checkLub(dynamic__, void___B_C, dynamic__);
- checkLub(dynamic__, void___C_C, dynamic__);
- checkLub(dynamic__, void____B, dynamic__);
- checkLub(dynamic__, void____B_C, dynamic__);
- checkLub(dynamic__, void____C_C, dynamic__);
+ checkLub(void__, Object_, Object_);
+ checkLub(void__, Function_, Function_);
+ checkLub(void__, dynamic__, dynamic__);
+ checkLub(void__, void__, void__);
+ checkLub(void__, A__, void__);
+ checkLub(void__, B__, void__);
+ checkLub(void__, C__, void__);
+ checkLub(void__, void__A_B, Function_);
+ checkLub(void__, void__A_C, Function_);
+ checkLub(void__, void__B_A, Function_);
+ checkLub(void__, void__B_C, Function_);
+ checkLub(void__, void___B, void__);
+ checkLub(void__, void___B_C, void__);
+ checkLub(void__, void___C_C, void__);
+ checkLub(void__, void____B, void__);
+ checkLub(void__, void____B_C, void__);
+ checkLub(void__, void____C_C, void__);
- checkLub(void__, Object_, Object_);
- checkLub(void__, Function_, Function_);
- checkLub(void__, dynamic__, dynamic__);
- checkLub(void__, void__, void__);
- checkLub(void__, A__, void__);
- checkLub(void__, B__, void__);
- checkLub(void__, C__, void__);
- checkLub(void__, void__A_B, Function_);
- checkLub(void__, void__A_C, Function_);
- checkLub(void__, void__B_A, Function_);
- checkLub(void__, void__B_C, Function_);
- checkLub(void__, void___B, void__);
- checkLub(void__, void___B_C, void__);
- checkLub(void__, void___C_C, void__);
- checkLub(void__, void____B, void__);
- checkLub(void__, void____B_C, void__);
- checkLub(void__, void____C_C, void__);
+ checkLub(A__, Object_, Object_);
+ checkLub(A__, Function_, Function_);
+ checkLub(A__, dynamic__, dynamic__);
+ checkLub(A__, void__, void__);
+ checkLub(A__, A__, A__);
+ checkLub(A__, B__, Object__);
+ checkLub(A__, C__, Object__);
+ checkLub(A__, void__A_B, Function_);
+ checkLub(A__, void__A_C, Function_);
+ checkLub(A__, void__B_A, Function_);
+ checkLub(A__, void__B_C, Function_);
+ checkLub(A__, void___B, void__);
+ checkLub(A__, void___B_C, void__);
+ checkLub(A__, void___C_C, void__);
+ checkLub(A__, void____B, void__);
+ checkLub(A__, void____B_C, void__);
+ checkLub(A__, void____C_C, void__);
- checkLub(A__, Object_, Object_);
- checkLub(A__, Function_, Function_);
- checkLub(A__, dynamic__, dynamic__);
- checkLub(A__, void__, void__);
- checkLub(A__, A__, A__);
- checkLub(A__, B__, Object__);
- checkLub(A__, C__, Object__);
- checkLub(A__, void__A_B, Function_);
- checkLub(A__, void__A_C, Function_);
- checkLub(A__, void__B_A, Function_);
- checkLub(A__, void__B_C, Function_);
- checkLub(A__, void___B, void__);
- checkLub(A__, void___B_C, void__);
- checkLub(A__, void___C_C, void__);
- checkLub(A__, void____B, void__);
- checkLub(A__, void____B_C, void__);
- checkLub(A__, void____C_C, void__);
+ checkLub(B__, Object_, Object_);
+ checkLub(B__, Function_, Function_);
+ checkLub(B__, dynamic__, dynamic__);
+ checkLub(B__, void__, void__);
+ checkLub(B__, A__, Object__);
+ checkLub(B__, B__, B__);
+ checkLub(B__, C__, B__);
+ checkLub(B__, void__A_B, Function_);
+ checkLub(B__, void__A_C, Function_);
+ checkLub(B__, void__B_A, Function_);
+ checkLub(B__, void__B_C, Function_);
+ checkLub(B__, void___B, void__);
+ checkLub(B__, void___B_C, void__);
+ checkLub(B__, void___C_C, void__);
+ checkLub(B__, void____B, void__);
+ checkLub(B__, void____B_C, void__);
+ checkLub(B__, void____C_C, void__);
- checkLub(B__, Object_, Object_);
- checkLub(B__, Function_, Function_);
- checkLub(B__, dynamic__, dynamic__);
- checkLub(B__, void__, void__);
- checkLub(B__, A__, Object__);
- checkLub(B__, B__, B__);
- checkLub(B__, C__, B__);
- checkLub(B__, void__A_B, Function_);
- checkLub(B__, void__A_C, Function_);
- checkLub(B__, void__B_A, Function_);
- checkLub(B__, void__B_C, Function_);
- checkLub(B__, void___B, void__);
- checkLub(B__, void___B_C, void__);
- checkLub(B__, void___C_C, void__);
- checkLub(B__, void____B, void__);
- checkLub(B__, void____B_C, void__);
- checkLub(B__, void____C_C, void__);
+ checkLub(C__, Object_, Object_);
+ checkLub(C__, Function_, Function_);
+ checkLub(C__, dynamic__, dynamic__);
+ checkLub(C__, void__, void__);
+ checkLub(C__, A__, Object__);
+ checkLub(C__, B__, B__);
+ checkLub(C__, C__, C__);
+ checkLub(C__, void__A_B, Function_);
+ checkLub(C__, void__A_C, Function_);
+ checkLub(C__, void__B_A, Function_);
+ checkLub(C__, void__B_C, Function_);
+ checkLub(C__, void___B, void__);
+ checkLub(C__, void___B_C, void__);
+ checkLub(C__, void___C_C, void__);
+ checkLub(C__, void____B, void__);
+ checkLub(C__, void____B_C, void__);
+ checkLub(C__, void____C_C, void__);
- checkLub(C__, Object_, Object_);
- checkLub(C__, Function_, Function_);
- checkLub(C__, dynamic__, dynamic__);
- checkLub(C__, void__, void__);
- checkLub(C__, A__, Object__);
- checkLub(C__, B__, B__);
- checkLub(C__, C__, C__);
- checkLub(C__, void__A_B, Function_);
- checkLub(C__, void__A_C, Function_);
- checkLub(C__, void__B_A, Function_);
- checkLub(C__, void__B_C, Function_);
- checkLub(C__, void___B, void__);
- checkLub(C__, void___B_C, void__);
- checkLub(C__, void___C_C, void__);
- checkLub(C__, void____B, void__);
- checkLub(C__, void____B_C, void__);
- checkLub(C__, void____C_C, void__);
+ checkLub(void__A_B, Object_, Object_);
+ checkLub(void__A_B, Function_, Function_);
+ checkLub(void__A_B, dynamic__, Function_);
+ checkLub(void__A_B, void__, Function_);
+ checkLub(void__A_B, A__, Function_);
+ checkLub(void__A_B, B__, Function_);
+ checkLub(void__A_B, C__, Function_);
+ checkLub(void__A_B, void__A_B, void__A_B);
+ checkLub(void__A_B, void__A_C, void__A_B);
+ checkLub(void__A_B, void__B_A, void__Object_Object);
+ checkLub(void__A_B, void__B_C, void__Object_B);
+ checkLub(void__A_B, void___B, Function_);
+ checkLub(void__A_B, void___B_C, Function_);
+ checkLub(void__A_B, void___C_C, Function_);
+ checkLub(void__A_B, void____B, Function_);
+ checkLub(void__A_B, void____B_C, Function_);
+ checkLub(void__A_B, void____C_C, Function_);
- checkLub(void__A_B, Object_, Object_);
- checkLub(void__A_B, Function_, Function_);
- checkLub(void__A_B, dynamic__, Function_);
- checkLub(void__A_B, void__, Function_);
- checkLub(void__A_B, A__, Function_);
- checkLub(void__A_B, B__, Function_);
- checkLub(void__A_B, C__, Function_);
- checkLub(void__A_B, void__A_B, void__A_B);
- checkLub(void__A_B, void__A_C, void__A_B);
- checkLub(void__A_B, void__B_A, void__Object_Object);
- checkLub(void__A_B, void__B_C, void__Object_B);
- checkLub(void__A_B, void___B, Function_);
- checkLub(void__A_B, void___B_C, Function_);
- checkLub(void__A_B, void___C_C, Function_);
- checkLub(void__A_B, void____B, Function_);
- checkLub(void__A_B, void____B_C, Function_);
- checkLub(void__A_B, void____C_C, Function_);
+ checkLub(void__A_C, Object_, Object_);
+ checkLub(void__A_C, Function_, Function_);
+ checkLub(void__A_C, dynamic__, Function_);
+ checkLub(void__A_C, void__, Function_);
+ checkLub(void__A_C, A__, Function_);
+ checkLub(void__A_C, B__, Function_);
+ checkLub(void__A_C, C__, Function_);
+ checkLub(void__A_C, void__A_B, void__A_B);
+ checkLub(void__A_C, void__A_C, void__A_C);
+ checkLub(void__A_C, void__B_A, void__Object_Object);
+ checkLub(void__A_C, void__B_C, void__Object_C);
+ checkLub(void__A_C, void___B, Function_);
+ checkLub(void__A_C, void___B_C, Function_);
+ checkLub(void__A_C, void___C_C, Function_);
+ checkLub(void__A_C, void____B, Function_);
+ checkLub(void__A_C, void____B_C, Function_);
+ checkLub(void__A_C, void____C_C, Function_);
- checkLub(void__A_C, Object_, Object_);
- checkLub(void__A_C, Function_, Function_);
- checkLub(void__A_C, dynamic__, Function_);
- checkLub(void__A_C, void__, Function_);
- checkLub(void__A_C, A__, Function_);
- checkLub(void__A_C, B__, Function_);
- checkLub(void__A_C, C__, Function_);
- checkLub(void__A_C, void__A_B, void__A_B);
- checkLub(void__A_C, void__A_C, void__A_C);
- checkLub(void__A_C, void__B_A, void__Object_Object);
- checkLub(void__A_C, void__B_C, void__Object_C);
- checkLub(void__A_C, void___B, Function_);
- checkLub(void__A_C, void___B_C, Function_);
- checkLub(void__A_C, void___C_C, Function_);
- checkLub(void__A_C, void____B, Function_);
- checkLub(void__A_C, void____B_C, Function_);
- checkLub(void__A_C, void____C_C, Function_);
+ checkLub(void__B_A, Object_, Object_);
+ checkLub(void__B_A, Function_, Function_);
+ checkLub(void__B_A, dynamic__, Function_);
+ checkLub(void__B_A, void__, Function_);
+ checkLub(void__B_A, A__, Function_);
+ checkLub(void__B_A, B__, Function_);
+ checkLub(void__B_A, C__, Function_);
+ checkLub(void__B_A, void__A_B, void__Object_Object);
+ checkLub(void__B_A, void__A_C, void__Object_Object);
+ checkLub(void__B_A, void__B_A, void__B_A);
+ checkLub(void__B_A, void__B_C, void__B_Object);
+ checkLub(void__B_A, void___B, Function_);
+ checkLub(void__B_A, void___B_C, Function_);
+ checkLub(void__B_A, void___C_C, Function_);
+ checkLub(void__B_A, void____B, Function_);
+ checkLub(void__B_A, void____B_C, Function_);
+ checkLub(void__B_A, void____C_C, Function_);
- checkLub(void__B_A, Object_, Object_);
- checkLub(void__B_A, Function_, Function_);
- checkLub(void__B_A, dynamic__, Function_);
- checkLub(void__B_A, void__, Function_);
- checkLub(void__B_A, A__, Function_);
- checkLub(void__B_A, B__, Function_);
- checkLub(void__B_A, C__, Function_);
- checkLub(void__B_A, void__A_B, void__Object_Object);
- checkLub(void__B_A, void__A_C, void__Object_Object);
- checkLub(void__B_A, void__B_A, void__B_A);
- checkLub(void__B_A, void__B_C, void__B_Object);
- checkLub(void__B_A, void___B, Function_);
- checkLub(void__B_A, void___B_C, Function_);
- checkLub(void__B_A, void___C_C, Function_);
- checkLub(void__B_A, void____B, Function_);
- checkLub(void__B_A, void____B_C, Function_);
- checkLub(void__B_A, void____C_C, Function_);
+ checkLub(void__B_C, Object_, Object_);
+ checkLub(void__B_C, Function_, Function_);
+ checkLub(void__B_C, dynamic__, Function_);
+ checkLub(void__B_C, void__, Function_);
+ checkLub(void__B_C, A__, Function_);
+ checkLub(void__B_C, B__, Function_);
+ checkLub(void__B_C, C__, Function_);
+ checkLub(void__B_C, void__A_B, void__Object_B);
+ checkLub(void__B_C, void__A_C, void__Object_C);
+ checkLub(void__B_C, void__B_A, void__B_Object);
+ checkLub(void__B_C, void__B_C, void__B_C);
+ checkLub(void__B_C, void___B, Function_);
+ checkLub(void__B_C, void___B_C, Function_);
+ checkLub(void__B_C, void___C_C, Function_);
+ checkLub(void__B_C, void____B, Function_);
+ checkLub(void__B_C, void____B_C, Function_);
+ checkLub(void__B_C, void____C_C, Function_);
- checkLub(void__B_C, Object_, Object_);
- checkLub(void__B_C, Function_, Function_);
- checkLub(void__B_C, dynamic__, Function_);
- checkLub(void__B_C, void__, Function_);
- checkLub(void__B_C, A__, Function_);
- checkLub(void__B_C, B__, Function_);
- checkLub(void__B_C, C__, Function_);
- checkLub(void__B_C, void__A_B, void__Object_B);
- checkLub(void__B_C, void__A_C, void__Object_C);
- checkLub(void__B_C, void__B_A, void__B_Object);
- checkLub(void__B_C, void__B_C, void__B_C);
- checkLub(void__B_C, void___B, Function_);
- checkLub(void__B_C, void___B_C, Function_);
- checkLub(void__B_C, void___C_C, Function_);
- checkLub(void__B_C, void____B, Function_);
- checkLub(void__B_C, void____B_C, Function_);
- checkLub(void__B_C, void____C_C, Function_);
+ checkLub(void___B, Object_, Object_);
+ checkLub(void___B, Function_, Function_);
+ checkLub(void___B, dynamic__, dynamic__);
+ checkLub(void___B, void__, void__);
+ checkLub(void___B, A__, void__);
+ checkLub(void___B, B__, void__);
+ checkLub(void___B, C__, void__);
+ checkLub(void___B, void__A_B, Function_);
+ checkLub(void___B, void__A_C, Function_);
+ checkLub(void___B, void__B_A, Function_);
+ checkLub(void___B, void__B_C, Function_);
+ checkLub(void___B, void___B, void___B);
+ checkLub(void___B, void___B_C, void___B);
+ checkLub(void___B, void___C_C, void___B);
+ checkLub(void___B, void____B, void__);
+ checkLub(void___B, void____B_C, void__);
+ checkLub(void___B, void____C_C, void__);
- checkLub(void___B, Object_, Object_);
- checkLub(void___B, Function_, Function_);
- checkLub(void___B, dynamic__, dynamic__);
- checkLub(void___B, void__, void__);
- checkLub(void___B, A__, void__);
- checkLub(void___B, B__, void__);
- checkLub(void___B, C__, void__);
- checkLub(void___B, void__A_B, Function_);
- checkLub(void___B, void__A_C, Function_);
- checkLub(void___B, void__B_A, Function_);
- checkLub(void___B, void__B_C, Function_);
- checkLub(void___B, void___B, void___B);
- checkLub(void___B, void___B_C, void___B);
- checkLub(void___B, void___C_C, void___B);
- checkLub(void___B, void____B, void__);
- checkLub(void___B, void____B_C, void__);
- checkLub(void___B, void____C_C, void__);
+ checkLub(void___B_C, Object_, Object_);
+ checkLub(void___B_C, Function_, Function_);
+ checkLub(void___B_C, dynamic__, dynamic__);
+ checkLub(void___B_C, void__, void__);
+ checkLub(void___B_C, A__, void__);
+ checkLub(void___B_C, B__, void__);
+ checkLub(void___B_C, C__, void__);
+ checkLub(void___B_C, void__A_B, Function_);
+ checkLub(void___B_C, void__A_C, Function_);
+ checkLub(void___B_C, void__B_A, Function_);
+ checkLub(void___B_C, void__B_C, Function_);
+ checkLub(void___B_C, void___B, void___B);
+ checkLub(void___B_C, void___B_C, void___B_C);
+ checkLub(void___B_C, void___C_C, void___B_C);
+ checkLub(void___B_C, void____B, void__);
+ checkLub(void___B_C, void____B_C, void__);
+ checkLub(void___B_C, void____C_C, void__);
- checkLub(void___B_C, Object_, Object_);
- checkLub(void___B_C, Function_, Function_);
- checkLub(void___B_C, dynamic__, dynamic__);
- checkLub(void___B_C, void__, void__);
- checkLub(void___B_C, A__, void__);
- checkLub(void___B_C, B__, void__);
- checkLub(void___B_C, C__, void__);
- checkLub(void___B_C, void__A_B, Function_);
- checkLub(void___B_C, void__A_C, Function_);
- checkLub(void___B_C, void__B_A, Function_);
- checkLub(void___B_C, void__B_C, Function_);
- checkLub(void___B_C, void___B, void___B);
- checkLub(void___B_C, void___B_C, void___B_C);
- checkLub(void___B_C, void___C_C, void___B_C);
- checkLub(void___B_C, void____B, void__);
- checkLub(void___B_C, void____B_C, void__);
- checkLub(void___B_C, void____C_C, void__);
+ checkLub(void___C_C, Object_, Object_);
+ checkLub(void___C_C, Function_, Function_);
+ checkLub(void___C_C, dynamic__, dynamic__);
+ checkLub(void___C_C, void__, void__);
+ checkLub(void___C_C, A__, void__);
+ checkLub(void___C_C, B__, void__);
+ checkLub(void___C_C, C__, void__);
+ checkLub(void___C_C, void__A_B, Function_);
+ checkLub(void___C_C, void__A_C, Function_);
+ checkLub(void___C_C, void__B_A, Function_);
+ checkLub(void___C_C, void__B_C, Function_);
+ checkLub(void___C_C, void___B, void___B);
+ checkLub(void___C_C, void___B_C, void___B_C);
+ checkLub(void___C_C, void___C_C, void___C_C);
+ checkLub(void___C_C, void____B, void__);
+ checkLub(void___C_C, void____B_C, void__);
+ checkLub(void___C_C, void____C_C, void__);
- checkLub(void___C_C, Object_, Object_);
- checkLub(void___C_C, Function_, Function_);
- checkLub(void___C_C, dynamic__, dynamic__);
- checkLub(void___C_C, void__, void__);
- checkLub(void___C_C, A__, void__);
- checkLub(void___C_C, B__, void__);
- checkLub(void___C_C, C__, void__);
- checkLub(void___C_C, void__A_B, Function_);
- checkLub(void___C_C, void__A_C, Function_);
- checkLub(void___C_C, void__B_A, Function_);
- checkLub(void___C_C, void__B_C, Function_);
- checkLub(void___C_C, void___B, void___B);
- checkLub(void___C_C, void___B_C, void___B_C);
- checkLub(void___C_C, void___C_C, void___C_C);
- checkLub(void___C_C, void____B, void__);
- checkLub(void___C_C, void____B_C, void__);
- checkLub(void___C_C, void____C_C, void__);
+ checkLub(void____B, Object_, Object_);
+ checkLub(void____B, Function_, Function_);
+ checkLub(void____B, dynamic__, dynamic__);
+ checkLub(void____B, void__, void__);
+ checkLub(void____B, A__, void__);
+ checkLub(void____B, B__, void__);
+ checkLub(void____B, C__, void__);
+ checkLub(void____B, void__A_B, Function_);
+ checkLub(void____B, void__A_C, Function_);
+ checkLub(void____B, void__B_A, Function_);
+ checkLub(void____B, void__B_C, Function_);
+ checkLub(void____B, void___B, void__);
+ checkLub(void____B, void___B_C, void__);
+ checkLub(void____B, void___C_C, void__);
+ checkLub(void____B, void____B, void____B);
+ checkLub(void____B, void____B_C, void____B);
+ checkLub(void____B, void____C_C, void____B);
- checkLub(void____B, Object_, Object_);
- checkLub(void____B, Function_, Function_);
- checkLub(void____B, dynamic__, dynamic__);
- checkLub(void____B, void__, void__);
- checkLub(void____B, A__, void__);
- checkLub(void____B, B__, void__);
- checkLub(void____B, C__, void__);
- checkLub(void____B, void__A_B, Function_);
- checkLub(void____B, void__A_C, Function_);
- checkLub(void____B, void__B_A, Function_);
- checkLub(void____B, void__B_C, Function_);
- checkLub(void____B, void___B, void__);
- checkLub(void____B, void___B_C, void__);
- checkLub(void____B, void___C_C, void__);
- checkLub(void____B, void____B, void____B);
- checkLub(void____B, void____B_C, void____B);
- checkLub(void____B, void____C_C, void____B);
+ checkLub(void____B_C, Object_, Object_);
+ checkLub(void____B_C, Function_, Function_);
+ checkLub(void____B_C, dynamic__, dynamic__);
+ checkLub(void____B_C, void__, void__);
+ checkLub(void____B_C, A__, void__);
+ checkLub(void____B_C, B__, void__);
+ checkLub(void____B_C, C__, void__);
+ checkLub(void____B_C, void__A_B, Function_);
+ checkLub(void____B_C, void__A_C, Function_);
+ checkLub(void____B_C, void__B_A, Function_);
+ checkLub(void____B_C, void__B_C, Function_);
+ checkLub(void____B_C, void___B, void__);
+ checkLub(void____B_C, void___B_C, void__);
+ checkLub(void____B_C, void___C_C, void__);
+ checkLub(void____B_C, void____B, void____B);
+ checkLub(void____B_C, void____B_C, void____B_C);
+ checkLub(void____B_C, void____C_C, void____B_C);
- checkLub(void____B_C, Object_, Object_);
- checkLub(void____B_C, Function_, Function_);
- checkLub(void____B_C, dynamic__, dynamic__);
- checkLub(void____B_C, void__, void__);
- checkLub(void____B_C, A__, void__);
- checkLub(void____B_C, B__, void__);
- checkLub(void____B_C, C__, void__);
- checkLub(void____B_C, void__A_B, Function_);
- checkLub(void____B_C, void__A_C, Function_);
- checkLub(void____B_C, void__B_A, Function_);
- checkLub(void____B_C, void__B_C, Function_);
- checkLub(void____B_C, void___B, void__);
- checkLub(void____B_C, void___B_C, void__);
- checkLub(void____B_C, void___C_C, void__);
- checkLub(void____B_C, void____B, void____B);
- checkLub(void____B_C, void____B_C, void____B_C);
- checkLub(void____B_C, void____C_C, void____B_C);
-
- checkLub(void____C_C, Object_, Object_);
- checkLub(void____C_C, Function_, Function_);
- checkLub(void____C_C, dynamic__, dynamic__);
- checkLub(void____C_C, void__, void__);
- checkLub(void____C_C, A__, void__);
- checkLub(void____C_C, B__, void__);
- checkLub(void____C_C, C__, void__);
- checkLub(void____C_C, void__A_B, Function_);
- checkLub(void____C_C, void__A_C, Function_);
- checkLub(void____C_C, void__B_A, Function_);
- checkLub(void____C_C, void__B_C, Function_);
- checkLub(void____C_C, void___B, void__);
- checkLub(void____C_C, void___B_C, void__);
- checkLub(void____C_C, void___C_C, void__);
- checkLub(void____C_C, void____B, void____B);
- checkLub(void____C_C, void____B_C, void____B_C);
- checkLub(void____C_C, void____C_C, void____C_C);
- }));
+ checkLub(void____C_C, Object_, Object_);
+ checkLub(void____C_C, Function_, Function_);
+ checkLub(void____C_C, dynamic__, dynamic__);
+ checkLub(void____C_C, void__, void__);
+ checkLub(void____C_C, A__, void__);
+ checkLub(void____C_C, B__, void__);
+ checkLub(void____C_C, C__, void__);
+ checkLub(void____C_C, void__A_B, Function_);
+ checkLub(void____C_C, void__A_C, Function_);
+ checkLub(void____C_C, void__B_A, Function_);
+ checkLub(void____C_C, void__B_C, Function_);
+ checkLub(void____C_C, void___B, void__);
+ checkLub(void____C_C, void___B_C, void__);
+ checkLub(void____C_C, void___C_C, void__);
+ checkLub(void____C_C, void____B, void____B);
+ checkLub(void____C_C, void____B_C, void____B_C);
+ checkLub(void____C_C, void____C_C, void____C_C);
+ }));
}
void testTypeVariable() {
@@ -710,143 +703,140 @@
W extends V,
X extends T> {}
""").then((env) {
+ // A B
+ // | / \
+ // S T C
+ // / \ \
+ // V X U
+ // /
+ // W
- // A B
- // | / \
- // S T C
- // / \ \
- // V X U
- // /
- // W
+ DartType Object_ = env['Object'];
+ DartType A = env['A'];
+ DartType B = env['B'];
+ DartType C = env['C'];
+ ClassElement I = env.getElement('I');
+ DartType S = I.typeVariables[0];
+ DartType T = I.typeVariables[1];
+ DartType U = I.typeVariables[2];
+ DartType V = I.typeVariables[3];
+ DartType W = I.typeVariables[4];
+ DartType X = I.typeVariables[5];
- DartType Object_ = env['Object'];
- DartType A = env['A'];
- DartType B = env['B'];
- DartType C = env['C'];
- ClassElement I = env.getElement('I');
- DartType S = I.typeVariables[0];
- DartType T = I.typeVariables[1];
- DartType U = I.typeVariables[2];
- DartType V = I.typeVariables[3];
- DartType W = I.typeVariables[4];
- DartType X = I.typeVariables[5];
+ checkLub(DartType a, DartType b, DartType expectedLub) {
+ DartType lub = env.computeLeastUpperBound(a, b);
+ Expect.equals(expectedLub, lub,
+ 'Unexpected lub($a,$b) = $lub, expected $expectedLub');
+ }
- checkLub(DartType a, DartType b, DartType expectedLub) {
- DartType lub = env.computeLeastUpperBound(a, b);
- Expect.equals(expectedLub, lub,
- 'Unexpected lub($a,$b) = $lub, expected $expectedLub');
- }
+ checkLub(Object_, Object_, Object_);
+ checkLub(Object_, A, Object_);
+ checkLub(Object_, B, Object_);
+ checkLub(Object_, C, Object_);
+ checkLub(Object_, S, Object_);
+ checkLub(Object_, T, Object_);
+ checkLub(Object_, U, Object_);
+ checkLub(Object_, V, Object_);
+ checkLub(Object_, W, Object_);
+ checkLub(Object_, X, Object_);
- checkLub(Object_, Object_, Object_);
- checkLub(Object_, A, Object_);
- checkLub(Object_, B, Object_);
- checkLub(Object_, C, Object_);
- checkLub(Object_, S, Object_);
- checkLub(Object_, T, Object_);
- checkLub(Object_, U, Object_);
- checkLub(Object_, V, Object_);
- checkLub(Object_, W, Object_);
- checkLub(Object_, X, Object_);
+ checkLub(A, Object_, Object_);
+ checkLub(A, A, A);
+ checkLub(A, B, Object_);
+ checkLub(A, C, Object_);
+ checkLub(A, S, A);
+ checkLub(A, T, Object_);
+ checkLub(A, U, Object_);
+ checkLub(A, V, Object_);
+ checkLub(A, W, Object_);
+ checkLub(A, X, Object_);
- checkLub(A, Object_, Object_);
- checkLub(A, A, A);
- checkLub(A, B, Object_);
- checkLub(A, C, Object_);
- checkLub(A, S, A);
- checkLub(A, T, Object_);
- checkLub(A, U, Object_);
- checkLub(A, V, Object_);
- checkLub(A, W, Object_);
- checkLub(A, X, Object_);
+ checkLub(B, Object_, Object_);
+ checkLub(B, A, Object_);
+ checkLub(B, B, B);
+ checkLub(B, C, B);
+ checkLub(B, S, Object_);
+ checkLub(B, T, B);
+ checkLub(B, U, B);
+ checkLub(B, V, B);
+ checkLub(B, W, B);
+ checkLub(B, X, B);
- checkLub(B, Object_, Object_);
- checkLub(B, A, Object_);
- checkLub(B, B, B);
- checkLub(B, C, B);
- checkLub(B, S, Object_);
- checkLub(B, T, B);
- checkLub(B, U, B);
- checkLub(B, V, B);
- checkLub(B, W, B);
- checkLub(B, X, B);
+ checkLub(C, Object_, Object_);
+ checkLub(C, A, Object_);
+ checkLub(C, B, B);
+ checkLub(C, C, C);
+ checkLub(C, S, Object_);
+ checkLub(C, T, B);
+ checkLub(C, U, C);
+ checkLub(C, V, B);
+ checkLub(C, W, B);
+ checkLub(C, X, B);
- checkLub(C, Object_, Object_);
- checkLub(C, A, Object_);
- checkLub(C, B, B);
- checkLub(C, C, C);
- checkLub(C, S, Object_);
- checkLub(C, T, B);
- checkLub(C, U, C);
- checkLub(C, V, B);
- checkLub(C, W, B);
- checkLub(C, X, B);
+ checkLub(S, Object_, Object_);
+ checkLub(S, A, A);
+ checkLub(S, B, Object_);
+ checkLub(S, C, Object_);
+ checkLub(S, S, S);
+ checkLub(S, T, Object_);
+ checkLub(S, U, Object_);
+ checkLub(S, V, Object_);
+ checkLub(S, W, Object_);
+ checkLub(S, X, Object_);
- checkLub(S, Object_, Object_);
- checkLub(S, A, A);
- checkLub(S, B, Object_);
- checkLub(S, C, Object_);
- checkLub(S, S, S);
- checkLub(S, T, Object_);
- checkLub(S, U, Object_);
- checkLub(S, V, Object_);
- checkLub(S, W, Object_);
- checkLub(S, X, Object_);
+ checkLub(T, Object_, Object_);
+ checkLub(T, A, Object_);
+ checkLub(T, B, B);
+ checkLub(T, C, B);
+ checkLub(T, S, Object_);
+ checkLub(T, T, T);
+ checkLub(T, U, B);
+ checkLub(T, V, T);
+ checkLub(T, W, T);
+ checkLub(T, X, T);
- checkLub(T, Object_, Object_);
- checkLub(T, A, Object_);
- checkLub(T, B, B);
- checkLub(T, C, B);
- checkLub(T, S, Object_);
- checkLub(T, T, T);
- checkLub(T, U, B);
- checkLub(T, V, T);
- checkLub(T, W, T);
- checkLub(T, X, T);
+ checkLub(U, Object_, Object_);
+ checkLub(U, A, Object_);
+ checkLub(U, B, B);
+ checkLub(U, C, C);
+ checkLub(U, S, Object_);
+ checkLub(U, T, B);
+ checkLub(U, U, U);
+ checkLub(U, V, B);
+ checkLub(U, W, B);
+ checkLub(U, X, B);
- checkLub(U, Object_, Object_);
- checkLub(U, A, Object_);
- checkLub(U, B, B);
- checkLub(U, C, C);
- checkLub(U, S, Object_);
- checkLub(U, T, B);
- checkLub(U, U, U);
- checkLub(U, V, B);
- checkLub(U, W, B);
- checkLub(U, X, B);
+ checkLub(V, Object_, Object_);
+ checkLub(V, A, Object_);
+ checkLub(V, B, B);
+ checkLub(V, C, B);
+ checkLub(V, S, Object_);
+ checkLub(V, T, T);
+ checkLub(V, U, B);
+ checkLub(V, V, V);
+ checkLub(V, W, V);
+ checkLub(V, X, T);
- checkLub(V, Object_, Object_);
- checkLub(V, A, Object_);
- checkLub(V, B, B);
- checkLub(V, C, B);
- checkLub(V, S, Object_);
- checkLub(V, T, T);
- checkLub(V, U, B);
- checkLub(V, V, V);
- checkLub(V, W, V);
- checkLub(V, X, T);
+ checkLub(W, Object_, Object_);
+ checkLub(W, A, Object_);
+ checkLub(W, B, B);
+ checkLub(W, C, B);
+ checkLub(W, S, Object_);
+ checkLub(W, T, T);
+ checkLub(W, U, B);
+ checkLub(W, V, V);
+ checkLub(W, W, W);
+ checkLub(W, X, T);
- checkLub(W, Object_, Object_);
- checkLub(W, A, Object_);
- checkLub(W, B, B);
- checkLub(W, C, B);
- checkLub(W, S, Object_);
- checkLub(W, T, T);
- checkLub(W, U, B);
- checkLub(W, V, V);
- checkLub(W, W, W);
- checkLub(W, X, T);
-
- checkLub(X, Object_, Object_);
- checkLub(X, A, Object_);
- checkLub(X, B, B);
- checkLub(X, C, B);
- checkLub(X, S, Object_);
- checkLub(X, T, T);
- checkLub(X, U, B);
- checkLub(X, V, T);
- checkLub(X, W, T);
- checkLub(X, X, X);
- }));
+ checkLub(X, Object_, Object_);
+ checkLub(X, A, Object_);
+ checkLub(X, B, B);
+ checkLub(X, C, B);
+ checkLub(X, S, Object_);
+ checkLub(X, T, T);
+ checkLub(X, U, B);
+ checkLub(X, V, T);
+ checkLub(X, W, T);
+ checkLub(X, X, X);
+ }));
}
-
-
diff --git a/tests/compiler/dart2js/library_env_test.dart b/tests/compiler/dart2js/library_env_test.dart
index d162b72..d07450a 100644
--- a/tests/compiler/dart2js/library_env_test.dart
+++ b/tests/compiler/dart2js/library_env_test.dart
@@ -9,18 +9,14 @@
import "package:async_helper/async_helper.dart";
-import 'package:expect/expect.dart' show
- Expect;
+import 'package:expect/expect.dart' show Expect;
-import 'package:compiler/src/null_compiler_output.dart' show
- NullCompilerOutput;
+import 'package:compiler/src/null_compiler_output.dart' show NullCompilerOutput;
-import 'package:compiler/src/options.dart' show
- CompilerOptions;
+import 'package:compiler/src/options.dart' show CompilerOptions;
-import 'package:compiler/compiler_new.dart' show
- CompilerInput,
- CompilerDiagnostics;
+import 'package:compiler/compiler_new.dart'
+ show CompilerInput, CompilerDiagnostics;
const clientPlatform = r'''
[dart-spec]
@@ -75,13 +71,13 @@
class CustomCompiler extends CompilerImpl {
CustomCompiler(options, environment)
: super(
- const DummyCompilerInput(),
- const NullCompilerOutput(),
- const DummyCompilerDiagnostics(),
- new CompilerOptions.parse(
- libraryRoot: Uri.base.resolve("sdk/"),
- options: options,
- environment: environment));
+ const DummyCompilerInput(),
+ const NullCompilerOutput(),
+ const DummyCompilerDiagnostics(),
+ new CompilerOptions.parse(
+ libraryRoot: Uri.base.resolve("sdk/"),
+ options: options,
+ environment: environment));
}
runTest() async {
@@ -121,8 +117,7 @@
// Check that user-defined env-variables win.
compiler = new CustomCompiler([],
- {'dart.library.collection': "false",
- 'dart.library.mock.client': "foo"});
+ {'dart.library.collection': "false", 'dart.library.mock.client': "foo"});
await compiler.setupSdk();
diff --git a/tests/compiler/dart2js/library_resolution_test.dart b/tests/compiler/dart2js/library_resolution_test.dart
index 93a039e..2482cca 100644
--- a/tests/compiler/dart2js/library_resolution_test.dart
+++ b/tests/compiler/dart2js/library_resolution_test.dart
@@ -32,15 +32,17 @@
Uri mock2LibraryUri = sdkRoot.resolve("lib/mock2.dart");
class CustomCompiler extends CompilerImpl {
- CustomCompiler(provider, handler, libraryRoot, packageRoot)
- : super(provider, const NullCompilerOutput(), handler,
+ CustomCompiler(provider, handler, libraryRoot, packageConfig)
+ : super(
+ provider,
+ const NullCompilerOutput(),
+ handler,
new CompilerOptions(
- libraryRoot: libraryRoot,
- packageRoot: packageRoot));
+ libraryRoot: libraryRoot, packageConfig: packageConfig));
}
main() async {
- Uri packageRoot = Uri.base.resolve(Platform.packageRoot);
+ Uri packageConfig = Uri.base.resolve('.packages');
var provider = new MemorySourceFileProvider(MEMORY_SOURCE_FILES);
var handler = new FormattingDiagnosticHandler(provider);
@@ -55,8 +57,8 @@
return provider.readStringFromUri(uri);
}
- String expectedMessage = MessageTemplate.TEMPLATES[
- MessageKind.LIBRARY_NOT_FOUND]
+ String expectedMessage = MessageTemplate
+ .TEMPLATES[MessageKind.LIBRARY_NOT_FOUND]
.message({'resolvedUri': 'dart:mock2.dart'}).computeMessage();
int actualMessageCount = 0;
@@ -77,7 +79,7 @@
new LegacyCompilerInput(wrappedProvider),
new LegacyCompilerDiagnostics(wrappedHandler),
sdkRoot,
- packageRoot);
+ packageConfig);
asyncStart();
await compiler.setupSdk();
diff --git a/tests/compiler/dart2js/line_column_provider_test.dart b/tests/compiler/dart2js/line_column_provider_test.dart
index ae90daf..bb640e3 100644
--- a/tests/compiler/dart2js/line_column_provider_test.dart
+++ b/tests/compiler/dart2js/line_column_provider_test.dart
@@ -25,19 +25,24 @@
expectedPositions.forEach((int offset, List<int> expectedPosition) {
if (expectedPosition == null) {
- Expect.throws(() => lineColumnProvider.getLine(offset),
- (e) => true,
- 'Expected out-of-bounds offset: $offset\n'
- 'text:"""${sink.text}"""\n'
- 'lineColumnProvider:$lineColumnProvider');
+ Expect.throws(
+ () => lineColumnProvider.getLine(offset),
+ (e) => true,
+ 'Expected out-of-bounds offset: $offset\n'
+ 'text:"""${sink.text}"""\n'
+ 'lineColumnProvider:$lineColumnProvider');
} else {
int line = lineColumnProvider.getLine(offset);
int column = lineColumnProvider.getColumn(line, offset);
- Expect.equals(expectedPosition[0], line,
+ Expect.equals(
+ expectedPosition[0],
+ line,
'Unexpected result: $offset -> $expectedPosition = [$line,$column]\n'
'text:"""${sink.text}"""\n'
'lineColumnProvider:$lineColumnProvider');
- Expect.equals(expectedPosition[1], column,
+ Expect.equals(
+ expectedPosition[1],
+ column,
'Unexpected result: $offset -> $expectedPosition = [$line,$column]\n'
'text:"""${sink.text}"""\n'
'lineColumnProvider:$lineColumnProvider');
@@ -46,19 +51,39 @@
}
main() {
- test([""], {0: [0, 0], 1: null});
+ test([
+ ""
+ ], {
+ 0: [0, 0],
+ 1: null
+ });
- test([" "], {0: [0, 0], 1: [0, 1], 2: null});
+ test([
+ " "
+ ], {
+ 0: [0, 0],
+ 1: [0, 1],
+ 2: null
+ });
- test(["\n "], {0: [0, 0], 1: [1, 0], 2: [1, 1], 3: null});
+ test([
+ "\n "
+ ], {
+ 0: [0, 0],
+ 1: [1, 0],
+ 2: [1, 1],
+ 3: null
+ });
- Map positions = {0: [0, 0],
- 1: [0, 1],
- 2: [1, 0],
- 3: [1, 1],
- 4: [2, 0],
- 5: [2, 1],
- 6: null};
+ Map positions = {
+ 0: [0, 0],
+ 1: [0, 1],
+ 2: [1, 0],
+ 3: [1, 1],
+ 4: [2, 0],
+ 5: [2, 1],
+ 6: null
+ };
test(["a\nb\nc"], positions);
diff --git a/tests/compiler/dart2js/link_test.dart b/tests/compiler/dart2js/link_test.dart
index 5ee61e4..841c89f 100644
--- a/tests/compiler/dart2js/link_test.dart
+++ b/tests/compiler/dart2js/link_test.dart
@@ -8,9 +8,9 @@
main() {
test(const Link<Comparable>().prepend('three').prepend(2).prepend('one'),
- ['one', 2, 'three']);
+ ['one', 2, 'three']);
test(const Link<Comparable>().prepend(3).prepend('two').prepend(1),
- [1, 'two', 3]);
+ [1, 'two', 3]);
test(const Link<String>().prepend('single'), ['single']);
test(const Link(), []);
testFromList([]);
@@ -51,7 +51,7 @@
testSkip() {
var nonEmptyLink = LinkFromList([0, 1, 2, 3, 4, 5]);
- for (int i = 0 ; i < 5; i++) {
+ for (int i = 0; i < 5; i++) {
var link = nonEmptyLink.skip(i);
Expect.isFalse(link.isEmpty);
Expect.equals(i, link.head);
diff --git a/tests/compiler/dart2js/list_tracer2_test.dart b/tests/compiler/dart2js/list_tracer2_test.dart
index 040ffb2..d03ab91 100644
--- a/tests/compiler/dart2js/list_tracer2_test.dart
+++ b/tests/compiler/dart2js/list_tracer2_test.dart
@@ -7,8 +7,7 @@
import 'package:expect/expect.dart';
import "package:async_helper/async_helper.dart";
-import 'package:compiler/src/types/types.dart'
- show ContainerTypeMask, TypeMask;
+import 'package:compiler/src/types/types.dart' show ContainerTypeMask, TypeMask;
import 'compiler_helper.dart';
import 'type_mask_test_helper.dart';
@@ -25,14 +24,14 @@
Uri uri = new Uri(scheme: 'source');
var compiler = compilerFor(TEST, uri);
asyncTest(() => compiler.run(uri).then((_) {
- var typesInferrer = compiler.globalInference.typesInferrer;
+ var typesInferrer = compiler.globalInference.typesInferrer;
- checkType(String name, type) {
- var element = findElement(compiler, name);
- ContainerTypeMask mask = typesInferrer.getTypeOfElement(element);
- Expect.equals(type, simplify(mask.elementType, compiler), name);
- }
+ checkType(String name, type) {
+ var element = findElement(compiler, name);
+ ContainerTypeMask mask = typesInferrer.getTypeOfElement(element);
+ Expect.equals(type, simplify(mask.elementType, compiler), name);
+ }
- checkType('myList', compiler.commonMasks.uint31Type);
- }));
+ checkType('myList', compiler.commonMasks.uint31Type);
+ }));
}
diff --git a/tests/compiler/dart2js/list_tracer3_test.dart b/tests/compiler/dart2js/list_tracer3_test.dart
index ee0bc06..cb1b936 100644
--- a/tests/compiler/dart2js/list_tracer3_test.dart
+++ b/tests/compiler/dart2js/list_tracer3_test.dart
@@ -7,13 +7,11 @@
import 'package:expect/expect.dart';
import "package:async_helper/async_helper.dart";
-import 'package:compiler/src/types/types.dart'
- show ContainerTypeMask, TypeMask;
+import 'package:compiler/src/types/types.dart' show ContainerTypeMask, TypeMask;
import 'compiler_helper.dart';
import 'type_mask_test_helper.dart';
-
const String TEST = r'''
var myList = [];
var otherList = ['foo', 42];
@@ -28,17 +26,17 @@
Uri uri = new Uri(scheme: 'source');
var compiler = compilerFor(TEST, uri);
asyncTest(() => compiler.run(uri).then((_) {
- var typesInferrer = compiler.globalInference.typesInferrer;
+ var typesInferrer = compiler.globalInference.typesInferrer;
- checkType(String name, type) {
- var element = findElement(compiler, name);
- ContainerTypeMask mask = typesInferrer.getTypeOfElement(element);
- Expect.equals(type, simplify(mask.elementType, compiler), name);
- }
+ checkType(String name, type) {
+ var element = findElement(compiler, name);
+ ContainerTypeMask mask = typesInferrer.getTypeOfElement(element);
+ Expect.equals(type, simplify(mask.elementType, compiler), name);
+ }
- var interceptorType =
- findTypeMask(compiler, 'Interceptor', 'nonNullSubclass');
+ var interceptorType =
+ findTypeMask(compiler, 'Interceptor', 'nonNullSubclass');
- checkType('myList', interceptorType);
- }));
+ checkType('myList', interceptorType);
+ }));
}
diff --git a/tests/compiler/dart2js/list_tracer_length_test.dart b/tests/compiler/dart2js/list_tracer_length_test.dart
index 51ffdcf..e2d7b6a 100644
--- a/tests/compiler/dart2js/list_tracer_length_test.dart
+++ b/tests/compiler/dart2js/list_tracer_length_test.dart
@@ -89,8 +89,8 @@
void checkRangeError(String test, {bool hasRangeError}) {
asyncTest(() => compileAll(test).then((generated) {
- Expect.equals(hasRangeError, generated.contains('ioore'));
- }));
+ Expect.equals(hasRangeError, generated.contains('ioore'));
+ }));
}
main() {
diff --git a/tests/compiler/dart2js/list_tracer_node_type_test.dart b/tests/compiler/dart2js/list_tracer_node_type_test.dart
index 092f554..7c91c8c 100644
--- a/tests/compiler/dart2js/list_tracer_node_type_test.dart
+++ b/tests/compiler/dart2js/list_tracer_node_type_test.dart
@@ -66,31 +66,30 @@
""";
}
-
main() {
asyncTest(() => compileAll(TEST1).then((generated) {
- Expect.isTrue(generated.contains('if (typeof t1'));
- }));
+ Expect.isTrue(generated.contains('if (typeof t1'));
+ }));
asyncTest(() => compileAll(TEST2).then((generated) {
- Expect.isTrue(generated.contains('if (typeof t1'));
- }));
+ Expect.isTrue(generated.contains('if (typeof t1'));
+ }));
asyncTest(() => compileAll(TEST3).then((generated) {
- Expect.isTrue(generated.contains('if (typeof t1'));
- }));
+ Expect.isTrue(generated.contains('if (typeof t1'));
+ }));
asyncTest(() => compileAll(TEST4).then((generated) {
- Expect.isTrue(generated.contains('if (typeof t1'));
- }));
+ Expect.isTrue(generated.contains('if (typeof t1'));
+ }));
asyncTest(() => compileAll(TEST5).then((generated) {
- Expect.isFalse(generated.contains('iae'));
- }));
+ Expect.isFalse(generated.contains('iae'));
+ }));
asyncTest(() => compileAll(TEST6).then((generated) {
- Expect.isFalse(generated.contains('iae'));
- }));
+ Expect.isFalse(generated.contains('iae'));
+ }));
var memberInvocations = const <String>[
'first',
@@ -101,14 +100,14 @@
'removeAt(0)',
'removeLast()',
];
- memberInvocations.map((member) => generateTest('$member'))
+ memberInvocations
+ .map((member) => generateTest('$member'))
.forEach((String test) {
asyncTest(() => compileAll(test, expectedErrors: 0, expectedWarnings: 0)
- .then((generated) {
- Expect.isTrue(generated.contains('+ 42'));
- Expect.isFalse(generated.contains('if (typeof t1'));
- Expect.isFalse(generated.contains('if (t1 == null)'));
- }));
+ .then((generated) {
+ Expect.isTrue(generated.contains('+ 42'));
+ Expect.isFalse(generated.contains('if (typeof t1'));
+ Expect.isFalse(generated.contains('if (t1 == null)'));
+ }));
});
-
}
diff --git a/tests/compiler/dart2js/list_tracer_test.dart b/tests/compiler/dart2js/list_tracer_test.dart
index cff8c88..fe1bd17 100644
--- a/tests/compiler/dart2js/list_tracer_test.dart
+++ b/tests/compiler/dart2js/list_tracer_test.dart
@@ -4,8 +4,7 @@
import 'package:expect/expect.dart';
import "package:async_helper/async_helper.dart";
-import 'package:compiler/src/types/types.dart'
- show ContainerTypeMask, TypeMask;
+import 'package:compiler/src/types/types.dart' show ContainerTypeMask, TypeMask;
import 'compiler_helper.dart';
import 'type_mask_test_helper.dart';
@@ -199,45 +198,45 @@
var compiler = compilerFor(generateTest(allocation), uri,
expectedErrors: 0, expectedWarnings: 1);
asyncTest(() => compiler.run(uri).then((_) {
- var commonMasks = compiler.commonMasks;
- var typesInferrer = compiler.globalInference.typesInferrer;
+ var commonMasks = compiler.commonMasks;
+ var typesInferrer = compiler.globalInference.typesInferrer;
- checkType(String name, type) {
- var element = findElement(compiler, name);
- ContainerTypeMask mask = typesInferrer.getTypeOfElement(element);
- if (nullify) type = type.nullable();
- Expect.equals(type, simplify(mask.elementType, compiler), name);
- }
+ checkType(String name, type) {
+ var element = findElement(compiler, name);
+ ContainerTypeMask mask = typesInferrer.getTypeOfElement(element);
+ if (nullify) type = type.nullable();
+ Expect.equals(type, simplify(mask.elementType, compiler), name);
+ }
- checkType('listInField', commonMasks.numType);
- checkType('listPassedToMethod', commonMasks.numType);
- checkType('listReturnedFromMethod', commonMasks.numType);
- checkType('listUsedWithCascade', commonMasks.numType);
- checkType('listUsedInClosure', commonMasks.numType);
- checkType('listPassedToSelector', commonMasks.numType);
- checkType('listReturnedFromSelector', commonMasks.numType);
- checkType('listUsedWithAddAndInsert', commonMasks.numType);
- checkType('listUsedWithConstraint', commonMasks.positiveIntType);
- checkType('listEscapingFromSetter', commonMasks.numType);
- checkType('listUsedInLocal', commonMasks.numType);
- checkType('listEscapingInSetterValue', commonMasks.numType);
- checkType('listEscapingInIndex', commonMasks.numType);
- checkType('listEscapingInIndexSet', commonMasks.uint31Type);
- checkType('listEscapingTwiceInIndexSet', commonMasks.numType);
- checkType('listSetInNonFinalField', commonMasks.numType);
- checkType('listWithChangedLength', commonMasks.uint31Type.nullable());
+ checkType('listInField', commonMasks.numType);
+ checkType('listPassedToMethod', commonMasks.numType);
+ checkType('listReturnedFromMethod', commonMasks.numType);
+ checkType('listUsedWithCascade', commonMasks.numType);
+ checkType('listUsedInClosure', commonMasks.numType);
+ checkType('listPassedToSelector', commonMasks.numType);
+ checkType('listReturnedFromSelector', commonMasks.numType);
+ checkType('listUsedWithAddAndInsert', commonMasks.numType);
+ checkType('listUsedWithConstraint', commonMasks.positiveIntType);
+ checkType('listEscapingFromSetter', commonMasks.numType);
+ checkType('listUsedInLocal', commonMasks.numType);
+ checkType('listEscapingInSetterValue', commonMasks.numType);
+ checkType('listEscapingInIndex', commonMasks.numType);
+ checkType('listEscapingInIndexSet', commonMasks.uint31Type);
+ checkType('listEscapingTwiceInIndexSet', commonMasks.numType);
+ checkType('listSetInNonFinalField', commonMasks.numType);
+ checkType('listWithChangedLength', commonMasks.uint31Type.nullable());
- checkType('listPassedToClosure', commonMasks.dynamicType);
- checkType('listReturnedFromClosure', commonMasks.dynamicType);
- checkType('listUsedWithNonOkSelector', commonMasks.dynamicType);
- checkType('listPassedAsOptionalParameter', commonMasks.numType);
- checkType('listPassedAsNamedParameter', commonMasks.numType);
- checkType('listStoredInList', commonMasks.uint31Type);
- checkType('listStoredInListButEscapes', commonMasks.dynamicType);
+ checkType('listPassedToClosure', commonMasks.dynamicType);
+ checkType('listReturnedFromClosure', commonMasks.dynamicType);
+ checkType('listUsedWithNonOkSelector', commonMasks.dynamicType);
+ checkType('listPassedAsOptionalParameter', commonMasks.numType);
+ checkType('listPassedAsNamedParameter', commonMasks.numType);
+ checkType('listStoredInList', commonMasks.uint31Type);
+ checkType('listStoredInListButEscapes', commonMasks.dynamicType);
- if (!allocation.contains('filled')) {
- checkType('listUnset', new TypeMask.nonNullEmpty());
- checkType('listOnlySetWithConstraint', new TypeMask.nonNullEmpty());
- }
- }));
+ if (!allocation.contains('filled')) {
+ checkType('listUnset', new TypeMask.nonNullEmpty());
+ checkType('listOnlySetWithConstraint', new TypeMask.nonNullEmpty());
+ }
+ }));
}
diff --git a/tests/compiler/dart2js/list_tracer_typed_data_length_test.dart b/tests/compiler/dart2js/list_tracer_typed_data_length_test.dart
index 594d26f..b0dc4fd 100644
--- a/tests/compiler/dart2js/list_tracer_typed_data_length_test.dart
+++ b/tests/compiler/dart2js/list_tracer_typed_data_length_test.dart
@@ -4,8 +4,7 @@
import 'package:expect/expect.dart';
import 'package:async_helper/async_helper.dart';
-import 'package:compiler/src/types/types.dart'
- show ContainerTypeMask, TypeMask;
+import 'package:compiler/src/types/types.dart' show ContainerTypeMask, TypeMask;
import 'package:compiler/src/compiler.dart';
import 'memory_compiler.dart';
@@ -13,7 +12,7 @@
import 'type_mask_test_helper.dart';
const TEST = const {
- 'main.dart' : r'''
+ 'main.dart': r'''
import 'dart:typed_data';
var myList = new Float32List(42);
@@ -23,7 +22,8 @@
var a = new Float32List(9);
return myList[0] + myOtherList[0];
}
-'''};
+'''
+};
void main() {
asyncTest(() async {
diff --git a/tests/compiler/dart2js/literal_list_test.dart b/tests/compiler/dart2js/literal_list_test.dart
index 7544f90..32120bf 100644
--- a/tests/compiler/dart2js/literal_list_test.dart
+++ b/tests/compiler/dart2js/literal_list_test.dart
@@ -17,8 +17,8 @@
main() {
asyncTest(() => compile(TEST_ONE, entry: 'foo', check: (String generated) {
- Expect.isTrue(generated.contains('print([1, 2]);'));
- Expect.isTrue(generated.contains('print([3]);'));
- Expect.isTrue(generated.contains('print([4, 5]);'));
- }));
+ Expect.isTrue(generated.contains('print([1, 2]);'));
+ Expect.isTrue(generated.contains('print([3]);'));
+ Expect.isTrue(generated.contains('print([4, 5]);'));
+ }));
}
diff --git a/tests/compiler/dart2js/literal_map_test.dart b/tests/compiler/dart2js/literal_map_test.dart
index b2862ea..e460618 100644
--- a/tests/compiler/dart2js/literal_map_test.dart
+++ b/tests/compiler/dart2js/literal_map_test.dart
@@ -16,12 +16,11 @@
main() {
asyncTest(() => compile(TEST, entry: 'foo', check: (String generated) {
- // Make sure we have all the type information we need.
- Expect.isFalse(generated.contains('bailout'));
- Expect.isFalse(generated.contains('interceptor'));
- // Make sure we don't go through an interceptor.
- Expect.isTrue(
- generated.contains(r'a.$indexSet(a') ||
- generated.contains(r'.$indexSet(0'));
- }));
+ // Make sure we have all the type information we need.
+ Expect.isFalse(generated.contains('bailout'));
+ Expect.isFalse(generated.contains('interceptor'));
+ // Make sure we don't go through an interceptor.
+ Expect.isTrue(generated.contains(r'a.$indexSet(a') ||
+ generated.contains(r'.$indexSet(0'));
+ }));
}
diff --git a/tests/compiler/dart2js/load_elimination_test.dart b/tests/compiler/dart2js/load_elimination_test.dart
index a5d4147..efbc841 100644
--- a/tests/compiler/dart2js/load_elimination_test.dart
+++ b/tests/compiler/dart2js/load_elimination_test.dart
@@ -234,33 +234,34 @@
}
""";
-
main() {
test(String code, String expected) {
return () => compileAll(code, disableInlining: false).then((generated) {
- Expect.isTrue(generated.contains(expected),
- "Generated code didn't contain '$expected'.\n"
- "Test:\n$code, Generated:\n$generated");
- });
+ Expect.isTrue(
+ generated.contains(expected),
+ "Generated code didn't contain '$expected'.\n"
+ "Test:\n$code, Generated:\n$generated");
+ });
}
+
asyncTest(() => Future.forEach([
- test(TEST_1, 'return 42'),
- test(TEST_2, 'return 42'),
- test(TEST_3, 'return 84'),
- test(TEST_4, 'return t1 + t1'),
- test(TEST_5, 'return 84'),
- test(TEST_6, 'return 84'),
- test(TEST_7, 'return 32'),
- test(TEST_8, 'return a.a'),
- test(TEST_9, 'return a.a'),
- test(TEST_10, 'return 2'),
- test(TEST_11, 'return a.a'),
- test(TEST_12, 'return 6'),
- test(TEST_13, 'return 6'),
- test(TEST_14, 'return t1[0]'),
- test(TEST_15, 'return 42'),
- test(TEST_16, 'return \$.a'),
- test(TEST_17, 'return t1'),
- test(TEST_18, 'return t1'),
- ], (f) => f()));
+ test(TEST_1, 'return 42'),
+ test(TEST_2, 'return 42'),
+ test(TEST_3, 'return 84'),
+ test(TEST_4, 'return t1 + t1'),
+ test(TEST_5, 'return 84'),
+ test(TEST_6, 'return 84'),
+ test(TEST_7, 'return 32'),
+ test(TEST_8, 'return a.a'),
+ test(TEST_9, 'return a.a'),
+ test(TEST_10, 'return 2'),
+ test(TEST_11, 'return a.a'),
+ test(TEST_12, 'return 6'),
+ test(TEST_13, 'return 6'),
+ test(TEST_14, 'return t1[0]'),
+ test(TEST_15, 'return 42'),
+ test(TEST_16, 'return \$.a'),
+ test(TEST_17, 'return t1'),
+ test(TEST_18, 'return t1'),
+ ], (f) => f()));
}
diff --git a/tests/compiler/dart2js/logical_expression_test.dart b/tests/compiler/dart2js/logical_expression_test.dart
index 5e9056a..cead66c 100644
--- a/tests/compiler/dart2js/logical_expression_test.dart
+++ b/tests/compiler/dart2js/logical_expression_test.dart
@@ -26,25 +26,28 @@
main() {
asyncTest(() => Future.wait([
- // We want something like:
- // var t1 = bar.call$0() === true;
- // if (t1 || gee.call$0() === true) gee.call$0();
- // if (t1 || gee.call$0() === true) gee.call$0();
- compileAndDoNotMatchFuzzy(TEST_ONE, 'foo',
- r"""var x = [a-zA-Z0-9$.]+\(\) == true;
+ // We want something like:
+ // var t1 = bar.call$0() === true;
+ // if (t1 || gee.call$0() === true) gee.call$0();
+ // if (t1 || gee.call$0() === true) gee.call$0();
+ compileAndDoNotMatchFuzzy(
+ TEST_ONE,
+ 'foo',
+ r"""var x = [a-zA-Z0-9$.]+\(\) == true;
if \(x \|\| [a-zA-Z0-9$.]+\(\) === true\) [^;]+;
if \(x \|\| [a-zA-Z0-9$.]+\(\) === true\) [^;]+;"""),
-
- // We want something like:
- // var t1 = list == null;
- // if (t1) bar.call$0();
- // if (t1 || bar.call$0() === true) bar.call$0();
- // if (t1 || bar.call$0() === true) bar.call$0();
- compileAndMatchFuzzy(TEST_TWO, 'foo',
- r"""var x = x == null;
+ // We want something like:
+ // var t1 = list == null;
+ // if (t1) bar.call$0();
+ // if (t1 || bar.call$0() === true) bar.call$0();
+ // if (t1 || bar.call$0() === true) bar.call$0();
+ compileAndMatchFuzzy(
+ TEST_TWO,
+ 'foo',
+ r"""var x = x == null;
if \(x\) [^;]+;
if \(x \|\| [a-zA-Z0-9$.]+\(\) === true\) [^;]+;
if \(x \|\| [a-zA-Z0-9$.]+\(\) === true\) [^;]+;"""),
- ]));
+ ]));
}
diff --git a/tests/compiler/dart2js/lookup_map_test.dart b/tests/compiler/dart2js/lookup_map_test.dart
index d3893b0..33a324f 100644
--- a/tests/compiler/dart2js/lookup_map_test.dart
+++ b/tests/compiler/dart2js/lookup_map_test.dart
@@ -16,7 +16,6 @@
class C {}
class D {}
class E {}''',
-
'const keys': r'''
import 'package:lookup_map/lookup_map.dart';
class Key { final name; const Key(this.name); }
@@ -25,7 +24,6 @@
const C = const Key("C");
const D = const Key("D");
const E = const Key("E");''',
-
'mixed keys': r'''
import 'package:lookup_map/lookup_map.dart';
class Key { final name; const Key(this.name); }
diff --git a/tests/compiler/dart2js/lookup_member_test.dart b/tests/compiler/dart2js/lookup_member_test.dart
index aec363a..27f49c7 100644
--- a/tests/compiler/dart2js/lookup_member_test.dart
+++ b/tests/compiler/dart2js/lookup_member_test.dart
@@ -9,7 +9,7 @@
import 'type_test_helper.dart';
import 'package:compiler/src/dart_types.dart';
import "package:compiler/src/elements/elements.dart"
- show Element, ClassElement, MemberSignature, PublicName;
+ show Element, ClassElement, MemberSignature, PublicName;
void main() {
test();
@@ -30,50 +30,49 @@
V boz;
}
""").then((env) {
- void expect(InterfaceType receiverType, String memberName,
- DartType expectedType) {
- MemberSignature member = receiverType.lookupInterfaceMember(
- new PublicName(memberName));
- Expect.isNotNull(member);
- DartType memberType = member.type;
- Expect.equals(expectedType, memberType,
- 'Wrong member type for $receiverType.$memberName.');
- }
+ void expect(InterfaceType receiverType, String memberName,
+ DartType expectedType) {
+ MemberSignature member =
+ receiverType.lookupInterfaceMember(new PublicName(memberName));
+ Expect.isNotNull(member);
+ DartType memberType = member.type;
+ Expect.equals(expectedType, memberType,
+ 'Wrong member type for $receiverType.$memberName.');
+ }
- DartType int_ = env['int'];
- DartType String_ = env['String'];
+ DartType int_ = env['int'];
+ DartType String_ = env['String'];
- ClassElement A = env.getElement('A');
- DartType T = A.typeVariables.first;
- DartType A_T = A.thisType;
- expect(A_T, 'foo', T);
+ ClassElement A = env.getElement('A');
+ DartType T = A.typeVariables.first;
+ DartType A_T = A.thisType;
+ expect(A_T, 'foo', T);
- DartType A_int = instantiate(A, [int_]);
- expect(A_int, 'foo', int_);
+ DartType A_int = instantiate(A, [int_]);
+ expect(A_int, 'foo', int_);
- ClassElement B = env.getElement('B');
- DartType S = B.typeVariables.first;
- DartType B_S = B.thisType;
- expect(B_S, 'foo', instantiate(A, [S]));
- expect(B_S, 'bar', S);
+ ClassElement B = env.getElement('B');
+ DartType S = B.typeVariables.first;
+ DartType B_S = B.thisType;
+ expect(B_S, 'foo', instantiate(A, [S]));
+ expect(B_S, 'bar', S);
- DartType B_int = instantiate(B, [int_]);
- expect(B_int, 'foo', A_int);
- expect(B_int, 'bar', int_);
+ DartType B_int = instantiate(B, [int_]);
+ expect(B_int, 'foo', A_int);
+ expect(B_int, 'bar', int_);
- ClassElement C = env.getElement('C');
- DartType U = C.typeVariables.first;
- DartType C_U = C.thisType;
- expect(C_U, 'foo', instantiate(A, [String_]));
- expect(C_U, 'bar', String_);
- expect(C_U, 'baz', U);
- expect(C_U, 'boz', instantiate(B, [U]));
+ ClassElement C = env.getElement('C');
+ DartType U = C.typeVariables.first;
+ DartType C_U = C.thisType;
+ expect(C_U, 'foo', instantiate(A, [String_]));
+ expect(C_U, 'bar', String_);
+ expect(C_U, 'baz', U);
+ expect(C_U, 'boz', instantiate(B, [U]));
- DartType C_int = instantiate(C, [int_]);
- expect(C_int, 'foo', instantiate(A, [String_]));
- expect(C_int, 'bar', String_);
- expect(C_int, 'baz', int_);
- expect(C_int, 'boz', instantiate(B, [int_]));
- }));
+ DartType C_int = instantiate(C, [int_]);
+ expect(C_int, 'foo', instantiate(A, [String_]));
+ expect(C_int, 'bar', String_);
+ expect(C_int, 'baz', int_);
+ expect(C_int, 'boz', instantiate(B, [int_]));
+ }));
}
-
diff --git a/tests/compiler/dart2js/loop_test.dart b/tests/compiler/dart2js/loop_test.dart
index fbb092a..c622d72 100644
--- a/tests/compiler/dart2js/loop_test.dart
+++ b/tests/compiler/dart2js/loop_test.dart
@@ -55,17 +55,17 @@
main() {
asyncTest(() => Future.wait([
- compile(TEST_ONE, entry: 'foo', check: (String generated) {
- Expect.isTrue(generated.contains(r'for ('));
- }),
- compile(TEST_TWO, entry: 'foo', check: (String generated) {
- Expect.isTrue(!generated.contains(r'break'));
- }),
- compile(TEST_THREE, entry: 'foo', check: (String generated) {
- Expect.isTrue(generated.contains(r'continue'));
- }),
- compile(TEST_FOUR, entry: 'foo', check: (String generated) {
- Expect.isTrue(generated.contains(r'continue'));
- }),
- ]));
+ compile(TEST_ONE, entry: 'foo', check: (String generated) {
+ Expect.isTrue(generated.contains(r'for ('));
+ }),
+ compile(TEST_TWO, entry: 'foo', check: (String generated) {
+ Expect.isTrue(!generated.contains(r'break'));
+ }),
+ compile(TEST_THREE, entry: 'foo', check: (String generated) {
+ Expect.isTrue(generated.contains(r'continue'));
+ }),
+ compile(TEST_FOUR, entry: 'foo', check: (String generated) {
+ Expect.isTrue(generated.contains(r'continue'));
+ }),
+ ]));
}
diff --git a/tests/compiler/dart2js/malformed_uri_test.dart b/tests/compiler/dart2js/malformed_uri_test.dart
index 70ec4a6..f36bef0 100644
--- a/tests/compiler/dart2js/malformed_uri_test.dart
+++ b/tests/compiler/dart2js/malformed_uri_test.dart
@@ -23,12 +23,11 @@
asyncTest(() async {
var collector = new DiagnosticCollector();
await runCompiler(
- memorySourceFiles: MEMORY_SOURCE_FILES,
- diagnosticHandler: collector);
+ memorySourceFiles: MEMORY_SOURCE_FILES, diagnosticHandler: collector);
Expect.equals(1, collector.errors.length);
});
}
void main() {
testMalformedUri();
-}
\ No newline at end of file
+}
diff --git a/tests/compiler/dart2js/map_tracer_const_test.dart b/tests/compiler/dart2js/map_tracer_const_test.dart
index 1bb6ca0..ee20f9f 100644
--- a/tests/compiler/dart2js/map_tracer_const_test.dart
+++ b/tests/compiler/dart2js/map_tracer_const_test.dart
@@ -30,14 +30,13 @@
void main() {
Uri uri = new Uri(scheme: 'source');
- var compiler = compilerFor(TEST, uri,
- expectedErrors: 0, expectedWarnings: 0);
+ var compiler = compilerFor(TEST, uri, expectedErrors: 0, expectedWarnings: 0);
compiler.stopAfterTypeInference = true;
asyncTest(() => compiler.run(uri).then((_) {
- var commonMasks = compiler.commonMasks;
- var typesInferrer = compiler.globalInference.typesInferrer;
- var element = findElement(compiler, 'closure');
- var mask = typesInferrer.getReturnTypeOfElement(element);
- Expect.equals(commonMasks.numType, simplify(mask, compiler));
- }));
+ var commonMasks = compiler.commonMasks;
+ var typesInferrer = compiler.globalInference.typesInferrer;
+ var element = findElement(compiler, 'closure');
+ var mask = typesInferrer.getReturnTypeOfElement(element);
+ Expect.equals(commonMasks.numType, simplify(mask, compiler));
+ }));
}
diff --git a/tests/compiler/dart2js/map_tracer_keys_test.dart b/tests/compiler/dart2js/map_tracer_keys_test.dart
index 4f429d3..4516fb3 100644
--- a/tests/compiler/dart2js/map_tracer_keys_test.dart
+++ b/tests/compiler/dart2js/map_tracer_keys_test.dart
@@ -4,12 +4,10 @@
import 'package:expect/expect.dart';
import "package:async_helper/async_helper.dart";
-import 'package:compiler/src/types/types.dart'
- show ContainerTypeMask, TypeMask;
+import 'package:compiler/src/types/types.dart' show ContainerTypeMask, TypeMask;
import 'compiler_helper.dart';
-
String generateTest(String key, String value, bool initial) {
return """
double aDouble = 42.5;
@@ -18,15 +16,16 @@
consume(x) => x;
main() {
-""" + (initial ?
-"""
+""" +
+ (initial
+ ? """
var theMap = {'a': 2.2, 'b': 3.3, 'c': 4.4, $key: $value};
-""" :
"""
+ : """
var theMap = {'a': 2.2, 'b': 3.3, 'c': 4.4};
theMap[$key] = $value;
""") +
-"""
+ """
for (var key in theMap.keys) {
aDouble = theMap[key];
}
@@ -49,27 +48,30 @@
doTest(value: "aList", initial: true);
}
-void doTest({String key: "'d'", String value: "5.5", bool bail: false,
- bool initial: false}) {
+void doTest(
+ {String key: "'d'",
+ String value: "5.5",
+ bool bail: false,
+ bool initial: false}) {
Uri uri = new Uri(scheme: 'source');
var compiler = compilerFor(generateTest(key, value, initial), uri,
expectedErrors: 0, expectedWarnings: 0);
asyncTest(() => compiler.run(uri).then((_) {
- var commonMasks = compiler.commonMasks;
- var typesInferrer = compiler.globalInference.typesInferrer;
- var aDoubleType =
- typesInferrer.getTypeOfElement(findElement(compiler, 'aDouble'));
- var aListType =
- typesInferrer.getTypeOfElement(findElement(compiler, 'aList'));
+ var commonMasks = compiler.commonMasks;
+ var typesInferrer = compiler.globalInference.typesInferrer;
+ var aDoubleType =
+ typesInferrer.getTypeOfElement(findElement(compiler, 'aDouble'));
+ var aListType =
+ typesInferrer.getTypeOfElement(findElement(compiler, 'aList'));
- Expect.equals(aDoubleType, commonMasks.doubleType);
- Expect.isTrue(aListType is ContainerTypeMask);
- ContainerTypeMask container = aListType;
- TypeMask elementType = container.elementType;
- if (bail) {
- Expect.equals(elementType, commonMasks.dynamicType);
- } else {
- Expect.equals(elementType, commonMasks.uint31Type);
- }
- }));
+ Expect.equals(aDoubleType, commonMasks.doubleType);
+ Expect.isTrue(aListType is ContainerTypeMask);
+ ContainerTypeMask container = aListType;
+ TypeMask elementType = container.elementType;
+ if (bail) {
+ Expect.equals(elementType, commonMasks.dynamicType);
+ } else {
+ Expect.equals(elementType, commonMasks.uint31Type);
+ }
+ }));
}
diff --git a/tests/compiler/dart2js/map_tracer_test.dart b/tests/compiler/dart2js/map_tracer_test.dart
index 1f313da..1f8e806 100644
--- a/tests/compiler/dart2js/map_tracer_test.dart
+++ b/tests/compiler/dart2js/map_tracer_test.dart
@@ -4,13 +4,11 @@
import 'package:expect/expect.dart';
import "package:async_helper/async_helper.dart";
-import 'package:compiler/src/types/types.dart'
- show MapTypeMask, TypeMask;
+import 'package:compiler/src/types/types.dart' show MapTypeMask, TypeMask;
import 'compiler_helper.dart';
import 'type_mask_test_helper.dart';
-
String generateTest(String mapAllocation) {
return """
int anInt = 42;
@@ -209,77 +207,80 @@
doTest('{aDouble : anInt}', "aDouble", "anInt");
}
-void doTest(String allocation, [String keyElement,
- String valueElement]) {
+void doTest(String allocation, [String keyElement, String valueElement]) {
Uri uri = new Uri(scheme: 'source');
var compiler = compilerFor(generateTest(allocation), uri,
expectedErrors: 0, expectedWarnings: 1);
var classWorld = compiler.world;
asyncTest(() => compiler.run(uri).then((_) {
- var keyType, valueType;
- var commonMasks = compiler.commonMasks;
- var typesInferrer = compiler.globalInference.typesInferrer;
- var emptyType = new TypeMask.nonNullEmpty();
- var aKeyType =
- typesInferrer.getTypeOfElement(findElement(compiler, 'aKey'));
- if (keyElement != null) {
- keyType =
- typesInferrer.getTypeOfElement(findElement(compiler, keyElement));
- }
- if (valueElement != null) {
- valueType =
- typesInferrer.getTypeOfElement(findElement(compiler, valueElement));
- }
- if (keyType == null) keyType = emptyType;
- if (valueType == null) valueType = emptyType;
+ var keyType, valueType;
+ var commonMasks = compiler.commonMasks;
+ var typesInferrer = compiler.globalInference.typesInferrer;
+ var emptyType = new TypeMask.nonNullEmpty();
+ var aKeyType =
+ typesInferrer.getTypeOfElement(findElement(compiler, 'aKey'));
+ if (keyElement != null) {
+ keyType =
+ typesInferrer.getTypeOfElement(findElement(compiler, keyElement));
+ }
+ if (valueElement != null) {
+ valueType = typesInferrer
+ .getTypeOfElement(findElement(compiler, valueElement));
+ }
+ if (keyType == null) keyType = emptyType;
+ if (valueType == null) valueType = emptyType;
- checkType(String name, keyType, valueType) {
- var element = findElement(compiler, name);
- MapTypeMask mask = typesInferrer.getTypeOfElement(element);
- Expect.equals(keyType, simplify(mask.keyType, compiler), name);
- Expect.equals(valueType, simplify(mask.valueType, compiler), name);
- }
+ checkType(String name, keyType, valueType) {
+ var element = findElement(compiler, name);
+ MapTypeMask mask = typesInferrer.getTypeOfElement(element);
+ Expect.equals(keyType, simplify(mask.keyType, compiler), name);
+ Expect.equals(valueType, simplify(mask.valueType, compiler), name);
+ }
- K(TypeMask other) => simplify(keyType.union(other, classWorld), compiler);
- V(TypeMask other) =>
- simplify(valueType.union(other, classWorld), compiler).nullable();
+ K(TypeMask other) =>
+ simplify(keyType.union(other, classWorld), compiler);
+ V(TypeMask other) =>
+ simplify(valueType.union(other, classWorld), compiler).nullable();
- checkType('mapInField', K(aKeyType), V(commonMasks.numType));
- checkType('mapPassedToMethod', K(aKeyType), V(commonMasks.numType));
- checkType('mapReturnedFromMethod', K(aKeyType), V(commonMasks.numType));
- checkType('mapUsedWithCascade', K(aKeyType), V(commonMasks.numType));
- checkType('mapUsedInClosure', K(aKeyType), V(commonMasks.numType));
- checkType('mapPassedToSelector', K(aKeyType), V(commonMasks.numType));
- checkType('mapReturnedFromSelector', K(aKeyType), V(commonMasks.numType));
- checkType('mapUsedWithConstraint', K(aKeyType), V(commonMasks.uint31Type));
- checkType('mapEscapingFromSetter', K(aKeyType), V(commonMasks.numType));
- checkType('mapUsedInLocal', K(aKeyType), V(commonMasks.numType));
- checkType('mapEscapingInSetterValue', K(aKeyType), V(commonMasks.numType));
- checkType('mapEscapingInIndex', K(aKeyType), V(commonMasks.numType));
- checkType('mapEscapingInIndexSet', K(aKeyType), V(commonMasks.uint31Type));
- checkType('mapEscapingTwiceInIndexSet',
- K(aKeyType), V(commonMasks.numType));
- checkType('mapSetInNonFinalField', K(aKeyType), V(commonMasks.numType));
+ checkType('mapInField', K(aKeyType), V(commonMasks.numType));
+ checkType('mapPassedToMethod', K(aKeyType), V(commonMasks.numType));
+ checkType('mapReturnedFromMethod', K(aKeyType), V(commonMasks.numType));
+ checkType('mapUsedWithCascade', K(aKeyType), V(commonMasks.numType));
+ checkType('mapUsedInClosure', K(aKeyType), V(commonMasks.numType));
+ checkType('mapPassedToSelector', K(aKeyType), V(commonMasks.numType));
+ checkType(
+ 'mapReturnedFromSelector', K(aKeyType), V(commonMasks.numType));
+ checkType(
+ 'mapUsedWithConstraint', K(aKeyType), V(commonMasks.uint31Type));
+ checkType('mapEscapingFromSetter', K(aKeyType), V(commonMasks.numType));
+ checkType('mapUsedInLocal', K(aKeyType), V(commonMasks.numType));
+ checkType(
+ 'mapEscapingInSetterValue', K(aKeyType), V(commonMasks.numType));
+ checkType('mapEscapingInIndex', K(aKeyType), V(commonMasks.numType));
+ checkType(
+ 'mapEscapingInIndexSet', K(aKeyType), V(commonMasks.uint31Type));
+ checkType(
+ 'mapEscapingTwiceInIndexSet', K(aKeyType), V(commonMasks.numType));
+ checkType('mapSetInNonFinalField', K(aKeyType), V(commonMasks.numType));
- checkType('mapPassedToClosure', K(commonMasks.dynamicType),
- V(commonMasks.dynamicType));
- checkType('mapReturnedFromClosure', K(commonMasks.dynamicType),
- V(commonMasks.dynamicType));
- checkType('mapUsedWithNonOkSelector', K(commonMasks.dynamicType),
- V(commonMasks.dynamicType));
- checkType('mapPassedAsOptionalParameter', K(aKeyType),
- V(commonMasks.numType));
- checkType('mapPassedAsNamedParameter', K(aKeyType),
- V(commonMasks.numType));
- checkType('mapStoredInList', K(aKeyType),
- V(commonMasks.uint31Type));
- checkType('mapStoredInListButEscapes', K(commonMasks.dynamicType),
- V(commonMasks.dynamicType));
- checkType('mapStoredInMap', K(aKeyType), V(commonMasks.uint31Type));
- checkType('mapStoredInMapButEscapes', K(commonMasks.dynamicType),
- V(commonMasks.dynamicType));
+ checkType('mapPassedToClosure', K(commonMasks.dynamicType),
+ V(commonMasks.dynamicType));
+ checkType('mapReturnedFromClosure', K(commonMasks.dynamicType),
+ V(commonMasks.dynamicType));
+ checkType('mapUsedWithNonOkSelector', K(commonMasks.dynamicType),
+ V(commonMasks.dynamicType));
+ checkType('mapPassedAsOptionalParameter', K(aKeyType),
+ V(commonMasks.numType));
+ checkType(
+ 'mapPassedAsNamedParameter', K(aKeyType), V(commonMasks.numType));
+ checkType('mapStoredInList', K(aKeyType), V(commonMasks.uint31Type));
+ checkType('mapStoredInListButEscapes', K(commonMasks.dynamicType),
+ V(commonMasks.dynamicType));
+ checkType('mapStoredInMap', K(aKeyType), V(commonMasks.uint31Type));
+ checkType('mapStoredInMapButEscapes', K(commonMasks.dynamicType),
+ V(commonMasks.dynamicType));
- checkType('mapUnset', K(emptyType), V(emptyType));
- checkType('mapOnlySetWithConstraint', K(aKeyType), V(emptyType));
- }));
+ checkType('mapUnset', K(emptyType), V(emptyType));
+ checkType('mapOnlySetWithConstraint', K(aKeyType), V(emptyType));
+ }));
}
diff --git a/tests/compiler/dart2js/members_test.dart b/tests/compiler/dart2js/members_test.dart
index 10e8859..c058761 100644
--- a/tests/compiler/dart2js/members_test.dart
+++ b/tests/compiler/dart2js/members_test.dart
@@ -8,18 +8,10 @@
import "package:async_helper/async_helper.dart";
import 'type_test_helper.dart';
import 'package:compiler/src/dart_types.dart';
-import "package:compiler/src/elements/elements.dart" show
- Element,
- ClassElement,
- MemberSignature,
- Name,
- PublicName,
- Member;
-import "package:compiler/src/resolution/class_members.dart" show
- MembersCreator,
- DeclaredMember,
- ErroneousMember,
- SyntheticMember;
+import "package:compiler/src/elements/elements.dart"
+ show Element, ClassElement, MemberSignature, Name, PublicName, Member;
+import "package:compiler/src/resolution/class_members.dart"
+ show MembersCreator, DeclaredMember, ErroneousMember, SyntheticMember;
void main() {
testClassMembers();
@@ -30,13 +22,11 @@
}
MemberSignature getMember(InterfaceType cls, String name,
- {bool isSetter: false,
- int checkType: CHECK_INTERFACE}) {
- Name memberName =
- new Name(name, cls.element.library, isSetter: isSetter);
+ {bool isSetter: false, int checkType: CHECK_INTERFACE}) {
+ Name memberName = new Name(name, cls.element.library, isSetter: isSetter);
MemberSignature member = checkType == CHECK_CLASS
- ? cls.element.lookupClassMember(memberName)
- : cls.element.lookupInterfaceMember(memberName);
+ ? cls.element.lookupClassMember(memberName)
+ : cls.element.lookupInterfaceMember(memberName);
if (member != null) {
Expect.equals(memberName, member.name);
}
@@ -45,10 +35,13 @@
/// Check interface member only.
const int CHECK_INTERFACE = 0;
+
/// Check class member only.
const int CHECK_CLASS = 1;
+
/// Check that there is no class member for the interface member.
const int NO_CLASS_MEMBER = 2;
+
/// Check that the interface member is also a class member.
const int ALSO_CLASS_MEMBER = 3;
@@ -73,18 +66,17 @@
* If [isClassMember] is `true` it is checked that the member is also a class
* member.
*/
-MemberSignature checkMember(InterfaceType cls,
- String name,
- {bool isStatic: false,
- bool isSetter: false,
- bool isGetter: false,
- InterfaceType declarer,
- DartType type,
- FunctionType functionType,
- InterfaceType inheritedFrom,
- List<InterfaceType> synthesizedFrom,
- List<InterfaceType> erroneousFrom,
- int checkType: ALSO_CLASS_MEMBER}) {
+MemberSignature checkMember(InterfaceType cls, String name,
+ {bool isStatic: false,
+ bool isSetter: false,
+ bool isGetter: false,
+ InterfaceType declarer,
+ DartType type,
+ FunctionType functionType,
+ InterfaceType inheritedFrom,
+ List<InterfaceType> synthesizedFrom,
+ List<InterfaceType> erroneousFrom,
+ int checkType: ALSO_CLASS_MEMBER}) {
String memberKind = checkType == CHECK_CLASS ? 'class' : 'interface';
MemberSignature member =
getMember(cls, name, isSetter: isSetter, checkType: checkType);
@@ -102,20 +94,22 @@
DeclaredMember inherited = checkType == CHECK_CLASS
? inheritedFrom.element.lookupClassMember(memberName)
: inheritedFrom.element.lookupInterfaceMember(memberName);
- Expect.isNotNull(inherited,
- "No $memberKind member '$memberName' in $inheritedFrom.");
+ Expect.isNotNull(
+ inherited, "No $memberKind member '$memberName' in $inheritedFrom.");
Expect.equals(inherited.inheritFrom(inheritedFrom), member);
} else {
if (erroneousFrom != null || synthesizedFrom != null) {
- Expect.notEquals(checkType, CHECK_CLASS,
+ Expect.notEquals(
+ checkType,
+ CHECK_CLASS,
"Arguments 'erroneousFrom' and 'synthesizedFrom' only apply "
"to interface members.");
if (synthesizedFrom != null) {
- Expect.isTrue(member is SyntheticMember,
- "Member '$member' is not synthesized.");
+ Expect.isTrue(
+ member is SyntheticMember, "Member '$member' is not synthesized.");
} else {
- Expect.isTrue(member is ErroneousMember,
- "Member '$member' is not erroneous.");
+ Expect.isTrue(
+ member is ErroneousMember, "Member '$member' is not erroneous.");
}
Set<MemberSignature> members = new Set<MemberSignature>();
List from = synthesizedFrom != null ? synthesizedFrom : erroneousFrom;
@@ -128,7 +122,9 @@
Expect.setEquals(members, member.declarations);
} else if (declarer != null) {
DeclaredMember declared = member;
- Expect.equals(declarer, declared.declarer,
+ Expect.equals(
+ declarer,
+ declared.declarer,
"Unexpected declarer '${declared.declarer}' of $memberKind member "
"'$member'. Expected '${declarer}'.");
} else {
@@ -145,7 +141,7 @@
if (functionType != null) {
if (type == null) {
Expect.equals(member.type, member.functionType,
- "Unexpected type of $memberKind member '$member'.");
+ "Unexpected type of $memberKind member '$member'.");
}
Expect.equals(functionType, member.functionType,
"Unexpected member type of $memberKind member '$member'.");
@@ -155,7 +151,7 @@
}
void checkMemberCount(InterfaceType cls, int expectedCount,
- {bool interfaceMembers: true}) {
+ {bool interfaceMembers: true}) {
int count = 0;
if (interfaceMembers) {
cls.element.forEachInterfaceMember((_) => count++);
@@ -166,7 +162,9 @@
}
void testClassMembers() {
- asyncTest(() => TypeEnvironment.create(r"""
+ asyncTest(() => TypeEnvironment
+ .create(
+ r"""
abstract class A {
int field;
final finalField = 0;
@@ -190,181 +188,220 @@
class C<S> extends B<S> {}
class D extends C<int> {}
class E extends D {}
- """, useMockCompiler: false).then((env) {
+ """,
+ useMockCompiler: false)
+ .then((env) {
+ InterfaceType bool_ = env['bool'];
+ InterfaceType String_ = env['String'];
+ InterfaceType num_ = env['num'];
+ InterfaceType int_ = env['int'];
+ DynamicType dynamic_ = env['dynamic'];
+ VoidType void_ = env['void'];
+ InterfaceType Type_ = env['Type'];
+ InterfaceType Invocation_ = env['Invocation'];
- InterfaceType bool_ = env['bool'];
- InterfaceType String_ = env['String'];
- InterfaceType num_ = env['num'];
- InterfaceType int_ = env['int'];
- DynamicType dynamic_ = env['dynamic'];
- VoidType void_ = env['void'];
- InterfaceType Type_ = env['Type'];
- InterfaceType Invocation_ = env['Invocation'];
+ InterfaceType Object_ = env['Object'];
+ checkMemberCount(Object_, 5 /*declared*/, interfaceMembers: true);
+ checkMemberCount(Object_, 5 /*declared*/, interfaceMembers: false);
- InterfaceType Object_ = env['Object'];
- checkMemberCount(Object_, 5 /*declared*/, interfaceMembers: true);
- checkMemberCount(Object_, 5 /*declared*/, interfaceMembers: false);
+ checkMember(Object_, '==',
+ functionType: env.functionType(bool_, [dynamic_]));
+ checkMember(Object_, 'hashCode',
+ isGetter: true,
+ type: int_,
+ functionType: env.functionType(int_, []));
+ checkMember(Object_, 'noSuchMethod',
+ functionType: env.functionType(dynamic_, [Invocation_]));
+ checkMember(Object_, 'runtimeType',
+ isGetter: true,
+ type: Type_,
+ functionType: env.functionType(Type_, []));
+ checkMember(Object_, 'toString',
+ functionType: env.functionType(String_, []));
- checkMember(Object_, '==',
- functionType: env.functionType(bool_, [dynamic_]));
- checkMember(Object_, 'hashCode',
- isGetter: true,
- type: int_, functionType: env.functionType(int_, []));
- checkMember(Object_, 'noSuchMethod',
- functionType: env.functionType(dynamic_, [Invocation_]));
- checkMember(Object_, 'runtimeType',
- isGetter: true,
- type: Type_, functionType: env.functionType(Type_, []));
- checkMember(Object_, 'toString',
- functionType: env.functionType(String_, []));
+ InterfaceType A = env['A'];
+ MembersCreator.computeAllClassMembers(env.resolution, A.element);
- InterfaceType A = env['A'];
- MembersCreator.computeAllClassMembers(env.resolution, A.element);
+ checkMemberCount(A, 5 /*inherited*/ + 9 /*non-static declared*/,
+ interfaceMembers: true);
+ checkMemberCount(
+ A,
+ 5 /*inherited*/ +
+ 9 /*non-abstract declared*/ +
+ 3 /* abstract declared */,
+ interfaceMembers: false);
- checkMemberCount(A, 5 /*inherited*/ + 9 /*non-static declared*/,
- interfaceMembers: true);
- checkMemberCount(A, 5 /*inherited*/ + 9 /*non-abstract declared*/ +
- 3 /* abstract declared */,
- interfaceMembers: false);
+ checkMember(A, '==', inheritedFrom: Object_);
+ checkMember(A, 'hashCode', inheritedFrom: Object_);
+ checkMember(A, 'noSuchMethod', inheritedFrom: Object_);
+ checkMember(A, 'runtimeType', inheritedFrom: Object_);
+ checkMember(A, 'toString', inheritedFrom: Object_);
- checkMember(A, '==', inheritedFrom: Object_);
- checkMember(A, 'hashCode', inheritedFrom: Object_);
- checkMember(A, 'noSuchMethod', inheritedFrom: Object_);
- checkMember(A, 'runtimeType', inheritedFrom: Object_);
- checkMember(A, 'toString', inheritedFrom: Object_);
+ checkMember(A, 'field',
+ isGetter: true,
+ type: int_,
+ functionType: env.functionType(int_, []));
+ checkMember(A, 'field',
+ isSetter: true,
+ type: int_,
+ functionType: env.functionType(void_, [int_]));
+ checkMember(A, 'finalField',
+ isGetter: true,
+ type: dynamic_,
+ functionType: env.functionType(dynamic_, []));
+ checkMember(A, 'staticField',
+ isGetter: true,
+ isStatic: true,
+ checkType: CHECK_CLASS,
+ type: dynamic_,
+ functionType: env.functionType(dynamic_, []));
+ checkMember(A, 'staticField',
+ isSetter: true,
+ isStatic: true,
+ checkType: CHECK_CLASS,
+ type: dynamic_,
+ functionType: env.functionType(void_, [dynamic_]));
- checkMember(A, 'field', isGetter: true,
- type: int_, functionType: env.functionType(int_, []));
- checkMember(A, 'field', isSetter: true,
- type: int_, functionType: env.functionType(void_, [int_]));
- checkMember(A, 'finalField', isGetter: true,
- type: dynamic_, functionType: env.functionType(dynamic_, []));
- checkMember(A, 'staticField', isGetter: true, isStatic: true,
- checkType: CHECK_CLASS,
- type: dynamic_, functionType: env.functionType(dynamic_, []));
- checkMember(A, 'staticField', isSetter: true, isStatic: true,
- checkType: CHECK_CLASS, type: dynamic_,
- functionType: env.functionType(void_, [dynamic_]));
+ checkMember(A, 'getter',
+ isGetter: true,
+ type: int_,
+ functionType: env.functionType(int_, []));
+ checkMember(A, 'abstractGetter',
+ isGetter: true,
+ type: dynamic_,
+ functionType: env.functionType(dynamic_, []));
+ checkMember(A, 'setter',
+ isSetter: true,
+ type: int_,
+ functionType: env.functionType(void_, [int_]));
+ checkMember(A, 'abstractSetter',
+ isSetter: true,
+ type: dynamic_,
+ functionType: env.functionType(dynamic_, [dynamic_]));
- checkMember(A, 'getter', isGetter: true,
- type: int_, functionType: env.functionType(int_, []));
- checkMember(A, 'abstractGetter', isGetter: true,
- type: dynamic_, functionType: env.functionType(dynamic_, []));
- checkMember(A, 'setter', isSetter: true,
- type: int_, functionType: env.functionType(void_, [int_]));
- checkMember(A, 'abstractSetter', isSetter: true,
- type: dynamic_,
- functionType: env.functionType(dynamic_, [dynamic_]));
+ checkMember(A, 'method', functionType: env.functionType(dynamic_, []));
+ checkMember(A, 'abstractMethod',
+ functionType: env.functionType(dynamic_, []));
+ checkMember(A, 'staticMethod',
+ checkType: CHECK_CLASS,
+ isStatic: true,
+ functionType: env.functionType(dynamic_, []));
- checkMember(A, 'method', functionType: env.functionType(dynamic_, []));
- checkMember(A, 'abstractMethod',
- functionType: env.functionType(dynamic_, []));
- checkMember(A, 'staticMethod',
- checkType: CHECK_CLASS,
- isStatic: true, functionType: env.functionType(dynamic_, []));
+ ClassElement B = env.getElement('B');
+ MembersCreator.computeAllClassMembers(env.resolution, B);
+ InterfaceType B_this = B.thisType;
+ TypeVariableType B_T = B_this.typeArguments.first;
+ checkMemberCount(B_this, 4 /*inherited*/ + 4 /*non-static declared*/,
+ interfaceMembers: true);
+ checkMemberCount(B_this, 4 /*inherited*/ + 5 /*declared*/,
+ interfaceMembers: false);
- ClassElement B = env.getElement('B');
- MembersCreator.computeAllClassMembers(env.resolution, B);
- InterfaceType B_this = B.thisType;
- TypeVariableType B_T = B_this.typeArguments.first;
- checkMemberCount(B_this, 4 /*inherited*/ + 4 /*non-static declared*/,
- interfaceMembers: true);
- checkMemberCount(B_this, 4 /*inherited*/ + 5 /*declared*/,
- interfaceMembers: false);
+ checkMember(B_this, '==', inheritedFrom: Object_);
+ checkMember(B_this, 'hashCode', inheritedFrom: Object_);
+ checkMember(B_this, 'noSuchMethod', inheritedFrom: Object_);
+ checkMember(B_this, 'runtimeType', inheritedFrom: Object_);
- checkMember(B_this, '==', inheritedFrom: Object_);
- checkMember(B_this, 'hashCode', inheritedFrom: Object_);
- checkMember(B_this, 'noSuchMethod', inheritedFrom: Object_);
- checkMember(B_this, 'runtimeType', inheritedFrom: Object_);
+ checkMember(B_this, 'field',
+ isGetter: true, type: B_T, functionType: env.functionType(B_T, []));
+ checkMember(B_this, 'field',
+ isSetter: true,
+ type: B_T,
+ functionType: env.functionType(void_, [B_T]));
+ checkMember(B_this, 'method',
+ functionType: env.functionType(void_, [B_T]));
+ checkMember(B_this, 'staticMethod',
+ checkType: CHECK_CLASS,
+ isStatic: true,
+ functionType: env.functionType(dynamic_, []));
+ checkMember(B_this, 'toString',
+ functionType:
+ env.functionType(dynamic_, [], optionalParameters: [B_T]));
- checkMember(B_this, 'field', isGetter: true,
- type: B_T, functionType: env.functionType(B_T, []));
- checkMember(B_this, 'field', isSetter: true,
- type: B_T, functionType: env.functionType(void_, [B_T]));
- checkMember(B_this, 'method', functionType: env.functionType(void_, [B_T]));
- checkMember(B_this, 'staticMethod',
- checkType: CHECK_CLASS,
- isStatic: true, functionType: env.functionType(dynamic_, []));
- checkMember(B_this, 'toString',
- functionType: env.functionType(dynamic_, [],
- optionalParameters: [B_T]));
+ ClassElement C = env.getElement('C');
+ MembersCreator.computeAllClassMembers(env.resolution, C);
+ InterfaceType C_this = C.thisType;
+ TypeVariableType C_S = C_this.typeArguments.first;
+ checkMemberCount(C_this, 8 /*inherited*/, interfaceMembers: true);
+ checkMemberCount(C_this, 8 /*inherited*/, interfaceMembers: false);
+ InterfaceType B_S = instantiate(B, [C_S]);
- ClassElement C = env.getElement('C');
- MembersCreator.computeAllClassMembers(env.resolution, C);
- InterfaceType C_this = C.thisType;
- TypeVariableType C_S = C_this.typeArguments.first;
- checkMemberCount(C_this, 8 /*inherited*/, interfaceMembers: true);
- checkMemberCount(C_this, 8 /*inherited*/, interfaceMembers: false);
- InterfaceType B_S = instantiate(B, [C_S]);
+ checkMember(C_this, '==', inheritedFrom: Object_);
+ checkMember(C_this, 'hashCode', inheritedFrom: Object_);
+ checkMember(C_this, 'noSuchMethod', inheritedFrom: Object_);
+ checkMember(C_this, 'runtimeType', inheritedFrom: Object_);
- checkMember(C_this, '==', inheritedFrom: Object_);
- checkMember(C_this, 'hashCode', inheritedFrom: Object_);
- checkMember(C_this, 'noSuchMethod', inheritedFrom: Object_);
- checkMember(C_this, 'runtimeType', inheritedFrom: Object_);
+ checkMember(C_this, 'field',
+ isGetter: true,
+ declarer: B_S,
+ type: C_S,
+ functionType: env.functionType(C_S, []));
+ checkMember(C_this, 'field',
+ isSetter: true,
+ declarer: B_S,
+ type: C_S,
+ functionType: env.functionType(void_, [C_S]));
+ checkMember(C_this, 'method',
+ declarer: B_S, functionType: env.functionType(void_, [C_S]));
+ checkMember(C_this, 'toString',
+ declarer: B_S,
+ functionType:
+ env.functionType(dynamic_, [], optionalParameters: [C_S]));
- checkMember(C_this, 'field', isGetter: true,
- declarer: B_S,
- type: C_S, functionType: env.functionType(C_S, []));
- checkMember(C_this, 'field', isSetter: true,
- declarer: B_S,
- type: C_S, functionType: env.functionType(void_, [C_S]));
- checkMember(C_this, 'method',
- declarer: B_S,
- functionType: env.functionType(void_, [C_S]));
- checkMember(C_this, 'toString',
- declarer: B_S,
- functionType: env.functionType(dynamic_, [],
- optionalParameters: [C_S]));
+ InterfaceType D = env['D'];
+ MembersCreator.computeAllClassMembers(env.resolution, D.element);
+ checkMemberCount(D, 8 /*inherited*/, interfaceMembers: true);
+ checkMemberCount(D, 8 /*inherited*/, interfaceMembers: false);
+ InterfaceType B_int = instantiate(B, [int_]);
- InterfaceType D = env['D'];
- MembersCreator.computeAllClassMembers(env.resolution, D.element);
- checkMemberCount(D, 8 /*inherited*/, interfaceMembers: true);
- checkMemberCount(D, 8 /*inherited*/, interfaceMembers: false);
- InterfaceType B_int = instantiate(B, [int_]);
+ checkMember(D, '==', inheritedFrom: Object_);
+ checkMember(D, 'hashCode', inheritedFrom: Object_);
+ checkMember(D, 'noSuchMethod', inheritedFrom: Object_);
+ checkMember(D, 'runtimeType', inheritedFrom: Object_);
- checkMember(D, '==', inheritedFrom: Object_);
- checkMember(D, 'hashCode', inheritedFrom: Object_);
- checkMember(D, 'noSuchMethod', inheritedFrom: Object_);
- checkMember(D, 'runtimeType', inheritedFrom: Object_);
+ checkMember(D, 'field',
+ isGetter: true,
+ declarer: B_int,
+ type: int_,
+ functionType: env.functionType(int_, []));
+ checkMember(D, 'field',
+ isSetter: true,
+ declarer: B_int,
+ type: int_,
+ functionType: env.functionType(void_, [int_]));
+ checkMember(D, 'method',
+ declarer: B_int, functionType: env.functionType(void_, [int_]));
+ checkMember(D, 'toString',
+ declarer: B_int,
+ functionType:
+ env.functionType(dynamic_, [], optionalParameters: [int_]));
- checkMember(D, 'field', isGetter: true,
- declarer: B_int,
- type: int_, functionType: env.functionType(int_, []));
- checkMember(D, 'field', isSetter: true,
- declarer: B_int,
- type: int_, functionType: env.functionType(void_, [int_]));
- checkMember(D, 'method',
- declarer: B_int,
- functionType: env.functionType(void_, [int_]));
- checkMember(D, 'toString',
- declarer: B_int,
- functionType: env.functionType(dynamic_, [],
- optionalParameters: [int_]));
+ InterfaceType E = env['E'];
+ MembersCreator.computeAllClassMembers(env.resolution, E.element);
+ checkMemberCount(E, 8 /*inherited*/, interfaceMembers: true);
+ checkMemberCount(E, 8 /*inherited*/, interfaceMembers: false);
- InterfaceType E = env['E'];
- MembersCreator.computeAllClassMembers(env.resolution, E.element);
- checkMemberCount(E, 8 /*inherited*/, interfaceMembers: true);
- checkMemberCount(E, 8 /*inherited*/, interfaceMembers: false);
+ checkMember(E, '==', inheritedFrom: Object_);
+ checkMember(E, 'hashCode', inheritedFrom: Object_);
+ checkMember(E, 'noSuchMethod', inheritedFrom: Object_);
+ checkMember(E, 'runtimeType', inheritedFrom: Object_);
- checkMember(E, '==', inheritedFrom: Object_);
- checkMember(E, 'hashCode', inheritedFrom: Object_);
- checkMember(E, 'noSuchMethod', inheritedFrom: Object_);
- checkMember(E, 'runtimeType', inheritedFrom: Object_);
-
- checkMember(E, 'field', isGetter: true,
- declarer: B_int,
- type: int_, functionType: env.functionType(int_, []));
- checkMember(E, 'field', isSetter: true,
- declarer: B_int,
- type: int_, functionType: env.functionType(void_, [int_]));
- checkMember(E, 'method',
- declarer: B_int,
- functionType: env.functionType(void_, [int_]));
- checkMember(E, 'toString',
- declarer: B_int,
- functionType: env.functionType(dynamic_, [],
- optionalParameters: [int_]));
- }));
+ checkMember(E, 'field',
+ isGetter: true,
+ declarer: B_int,
+ type: int_,
+ functionType: env.functionType(int_, []));
+ checkMember(E, 'field',
+ isSetter: true,
+ declarer: B_int,
+ type: int_,
+ functionType: env.functionType(void_, [int_]));
+ checkMember(E, 'method',
+ declarer: B_int, functionType: env.functionType(void_, [int_]));
+ checkMember(E, 'toString',
+ declarer: B_int,
+ functionType:
+ env.functionType(dynamic_, [], optionalParameters: [int_]));
+ }));
}
void testInterfaceMembers() {
@@ -413,102 +450,99 @@
}
abstract class D implements A, B, C {}
""").then((env) {
+ DynamicType dynamic_ = env['dynamic'];
+ VoidType void_ = env['void'];
+ InterfaceType num_ = env['num'];
+ InterfaceType int_ = env['int'];
- DynamicType dynamic_ = env['dynamic'];
- VoidType void_ = env['void'];
- InterfaceType num_ = env['num'];
- InterfaceType int_ = env['int'];
+ InterfaceType A = env['A'];
+ InterfaceType B = env['B'];
+ InterfaceType C = env['C'];
+ InterfaceType D = env['D'];
- InterfaceType A = env['A'];
- InterfaceType B = env['B'];
- InterfaceType C = env['C'];
- InterfaceType D = env['D'];
+ // Ensure that members have been computed on all classes.
+ MembersCreator.computeAllClassMembers(env.resolution, D.element);
- // Ensure that members have been computed on all classes.
- MembersCreator.computeAllClassMembers(env.resolution, D.element);
+ // A: num method1()
+ // B: int method1()
+ // D: dynamic method1() -- synthesized from A and B.
+ checkMember(D, 'method1',
+ synthesizedFrom: [A, B],
+ functionType: env.functionType(dynamic_, []),
+ checkType: NO_CLASS_MEMBER);
- // A: num method1()
- // B: int method1()
- // D: dynamic method1() -- synthesized from A and B.
- checkMember(D, 'method1',
- synthesizedFrom: [A, B],
- functionType: env.functionType(dynamic_ , []),
- checkType: NO_CLASS_MEMBER);
+ // A: void method2()
+ // B: int method2()
+ // D: int method2() -- inherited from B
+ checkMember(D, 'method2', inheritedFrom: B, checkType: NO_CLASS_MEMBER);
- // A: void method2()
- // B: int method2()
- // D: int method2() -- inherited from B
- checkMember(D, 'method2', inheritedFrom: B, checkType: NO_CLASS_MEMBER);
+ // A: void method3()
+ // B: num method3()
+ // C: int method3()
+ // D: dynamic method3() -- synthesized from A, B, and C.
+ checkMember(D, 'method3',
+ synthesizedFrom: [A, B, C],
+ functionType: env.functionType(dynamic_, []),
+ checkType: NO_CLASS_MEMBER);
- // A: void method3()
- // B: num method3()
- // C: int method3()
- // D: dynamic method3() -- synthesized from A, B, and C.
- checkMember(D, 'method3',
- synthesizedFrom: [A, B, C],
- functionType: env.functionType(dynamic_ , []),
- checkType: NO_CLASS_MEMBER);
+ // A: void method4()
+ // B: num method4()
+ // C: num method4()
+ // D: num method4() -- synthesized from B and C.
+ checkMember(D, 'method4',
+ synthesizedFrom: [B, C],
+ functionType: env.functionType(num_, []),
+ checkType: NO_CLASS_MEMBER);
- // A: void method4()
- // B: num method4()
- // C: num method4()
- // D: num method4() -- synthesized from B and C.
- checkMember(D, 'method4',
- synthesizedFrom: [B, C],
- functionType: env.functionType(num_, []),
- checkType: NO_CLASS_MEMBER);
+ // A: method5(a)
+ // B: method5([a])
+ // D: method5([a]) -- inherited from B
+ checkMember(D, 'method5', inheritedFrom: B, checkType: NO_CLASS_MEMBER);
- // A: method5(a)
- // B: method5([a])
- // D: method5([a]) -- inherited from B
- checkMember(D, 'method5', inheritedFrom: B, checkType: NO_CLASS_MEMBER);
+ // A: method6(a)
+ // B: method6([a, b])
+ // D: method6([a, b]) -- inherited from B
+ checkMember(D, 'method6', inheritedFrom: B, checkType: NO_CLASS_MEMBER);
- // A: method6(a)
- // B: method6([a, b])
- // D: method6([a, b]) -- inherited from B
- checkMember(D, 'method6', inheritedFrom: B, checkType: NO_CLASS_MEMBER);
+ // A: method7(a)
+ // B: method7(a, [b])
+ // D: method7(a, [b]) -- inherited from B
+ checkMember(D, 'method7', inheritedFrom: B, checkType: NO_CLASS_MEMBER);
- // A: method7(a)
- // B: method7(a, [b])
- // D: method7(a, [b]) -- inherited from B
- checkMember(D, 'method7', inheritedFrom: B, checkType: NO_CLASS_MEMBER);
+ // A: method8(a, b)
+ // B: method8([a])
+ // D: method8([a, b]) -- synthesized from A and B.
+ checkMember(D, 'method8',
+ synthesizedFrom: [A, B],
+ functionType: env.functionType(dynamic_, [],
+ optionalParameters: [dynamic_, dynamic_]),
+ checkType: NO_CLASS_MEMBER);
- // A: method8(a, b)
- // B: method8([a])
- // D: method8([a, b]) -- synthesized from A and B.
- checkMember(D, 'method8',
- synthesizedFrom: [A, B],
- functionType: env.functionType(
- dynamic_, [], optionalParameters: [dynamic_, dynamic_]),
- checkType: NO_CLASS_MEMBER);
+ // A: method9(a, b, c)
+ // B: method9(a, [b])
+ // D: method9(a, [b, c]) -- synthesized from A and B.
+ checkMember(D, 'method9',
+ synthesizedFrom: [A, B],
+ functionType: env.functionType(dynamic_, [dynamic_],
+ optionalParameters: [dynamic_, dynamic_]),
+ checkType: NO_CLASS_MEMBER);
- // A: method9(a, b, c)
- // B: method9(a, [b])
- // D: method9(a, [b, c]) -- synthesized from A and B.
- checkMember(D, 'method9',
- synthesizedFrom: [A, B],
- functionType: env.functionType(
- dynamic_, [dynamic_], optionalParameters: [dynamic_, dynamic_]),
- checkType: NO_CLASS_MEMBER);
+ // A: method10(a, {b, c})
+ // B: method10(a, {c, d})
+ // D: method10(a, {b, c, d}) -- synthesized from A and B.
+ checkMember(D, 'method10',
+ synthesizedFrom: [A, B],
+ functionType: env.functionType(dynamic_, [dynamic_],
+ namedParameters: {'b': dynamic_, 'c': dynamic_, 'd': dynamic_}),
+ checkType: NO_CLASS_MEMBER);
- // A: method10(a, {b, c})
- // B: method10(a, {c, d})
- // D: method10(a, {b, c, d}) -- synthesized from A and B.
- checkMember(D, 'method10',
- synthesizedFrom: [A, B],
- functionType: env.functionType(dynamic_, [dynamic_],
- namedParameters: {'b': dynamic_,
- 'c': dynamic_,
- 'd': dynamic_}),
- checkType: NO_CLASS_MEMBER);
-
- // A: method11(a, {b, c})
- // B: method11(a, b, {c, d})
- // D: method11(a, [b], {c, d}) -- synthesized from A and B.
- // TODO(johnniwinther): Change to check synthesized member when function
- // types with both optional and named parameters are supported.
- Expect.isNull(getMember(D, 'method11'));
- /*checkMember(D, 'method11',
+ // A: method11(a, {b, c})
+ // B: method11(a, b, {c, d})
+ // D: method11(a, [b], {c, d}) -- synthesized from A and B.
+ // TODO(johnniwinther): Change to check synthesized member when function
+ // types with both optional and named parameters are supported.
+ Expect.isNull(getMember(D, 'method11'));
+ /*checkMember(D, 'method11',
synthesizedFrom: [A, B],
functionType: env.functionType(dynamic_, [dynamic_],
optionalParameters: [dynamic_],
@@ -516,58 +550,62 @@
'd': dynamic_,}),
checkType: NO_CLASS_MEMBER);*/
- // A: num get getter1
- // B: num get getter1
- // D: num get getter1 -- synthesized from A and B.
- checkMember(D, 'getter1',
- isGetter: true,
- synthesizedFrom: [A, B], type: num_,
- functionType: env.functionType(num_ , []),
- checkType: NO_CLASS_MEMBER);
+ // A: num get getter1
+ // B: num get getter1
+ // D: num get getter1 -- synthesized from A and B.
+ checkMember(D, 'getter1',
+ isGetter: true,
+ synthesizedFrom: [A, B],
+ type: num_,
+ functionType: env.functionType(num_, []),
+ checkType: NO_CLASS_MEMBER);
- // A: num get getter2
- // B: int get getter2
- // D: dynamic get getter2 -- synthesized from A and B.
- checkMember(D, 'getter2',
- isGetter: true,
- synthesizedFrom: [A, B], type: dynamic_,
- functionType: env.functionType(dynamic_ , []),
- checkType: NO_CLASS_MEMBER);
+ // A: num get getter2
+ // B: int get getter2
+ // D: dynamic get getter2 -- synthesized from A and B.
+ checkMember(D, 'getter2',
+ isGetter: true,
+ synthesizedFrom: [A, B],
+ type: dynamic_,
+ functionType: env.functionType(dynamic_, []),
+ checkType: NO_CLASS_MEMBER);
- // A: void set setter1(num _)
- // B: void set setter1(num _)
- // D: void set setter1(num _) -- synthesized from A and B.
- checkMember(D, 'setter1',
- isSetter: true,
- synthesizedFrom: [A, B], type: num_,
- functionType: env.functionType(void_ , [num_]),
- checkType: NO_CLASS_MEMBER);
+ // A: void set setter1(num _)
+ // B: void set setter1(num _)
+ // D: void set setter1(num _) -- synthesized from A and B.
+ checkMember(D, 'setter1',
+ isSetter: true,
+ synthesizedFrom: [A, B],
+ type: num_,
+ functionType: env.functionType(void_, [num_]),
+ checkType: NO_CLASS_MEMBER);
- // A: void set setter2(num _)
- // B: set setter2(num _)
- // D: dynamic set setter2(dynamic _) -- synthesized from A and B.
- checkMember(D, 'setter2',
- isSetter: true,
- synthesizedFrom: [A, B], type: dynamic_,
- functionType: env.functionType(dynamic_ , [dynamic_]),
- checkType: NO_CLASS_MEMBER);
+ // A: void set setter2(num _)
+ // B: set setter2(num _)
+ // D: dynamic set setter2(dynamic _) -- synthesized from A and B.
+ checkMember(D, 'setter2',
+ isSetter: true,
+ synthesizedFrom: [A, B],
+ type: dynamic_,
+ functionType: env.functionType(dynamic_, [dynamic_]),
+ checkType: NO_CLASS_MEMBER);
- // A: void set setter3(num _)
- // B: void set setter3(int _)
- // D: dynamic set setter3(dynamic _) -- synthesized from A and B.
- checkMember(D, 'setter3',
- isSetter: true,
- synthesizedFrom: [A, B], type: dynamic_,
- functionType: env.functionType(dynamic_ , [dynamic_]),
- checkType: NO_CLASS_MEMBER);
+ // A: void set setter3(num _)
+ // B: void set setter3(int _)
+ // D: dynamic set setter3(dynamic _) -- synthesized from A and B.
+ checkMember(D, 'setter3',
+ isSetter: true,
+ synthesizedFrom: [A, B],
+ type: dynamic_,
+ functionType: env.functionType(dynamic_, [dynamic_]),
+ checkType: NO_CLASS_MEMBER);
- // A: get getterAndMethod
- // B: getterAndMethod()
- // D: nothing inherited
- checkMember(D, 'getterAndMethod',
- erroneousFrom: [A, B],
- checkType: NO_CLASS_MEMBER);
- }));
+ // A: get getterAndMethod
+ // B: getterAndMethod()
+ // D: nothing inherited
+ checkMember(D, 'getterAndMethod',
+ erroneousFrom: [A, B], checkType: NO_CLASS_MEMBER);
+ }));
}
void testClassVsInterfaceMembers() {
@@ -582,47 +620,45 @@
}
abstract class C extends A implements B {}
""").then((env) {
+ DynamicType dynamic_ = env['dynamic'];
+ VoidType void_ = env['void'];
+ InterfaceType num_ = env['num'];
+ InterfaceType int_ = env['int'];
- DynamicType dynamic_ = env['dynamic'];
- VoidType void_ = env['void'];
- InterfaceType num_ = env['num'];
- InterfaceType int_ = env['int'];
+ InterfaceType A = env['A'];
+ InterfaceType B = env['B'];
+ InterfaceType C = env['C'];
- InterfaceType A = env['A'];
- InterfaceType B = env['B'];
- InterfaceType C = env['C'];
+ // Ensure that members have been computed on all classes.
+ MembersCreator.computeAllClassMembers(env.resolution, C.element);
- // Ensure that members have been computed on all classes.
- MembersCreator.computeAllClassMembers(env.resolution, C.element);
+ // A: method1()
+ // B: method1()
+ // C class: method1() -- inherited from A.
+ // C interface: dynamic method1() -- synthesized from A and B.
+ MemberSignature interfaceMember = checkMember(C, 'method1',
+ checkType: CHECK_INTERFACE,
+ synthesizedFrom: [A, B],
+ functionType: env.functionType(dynamic_, []));
+ MemberSignature classMember =
+ checkMember(C, 'method1', checkType: CHECK_CLASS, inheritedFrom: A);
+ Expect.notEquals(interfaceMember, classMember);
- // A: method1()
- // B: method1()
- // C class: method1() -- inherited from A.
- // C interface: dynamic method1() -- synthesized from A and B.
- MemberSignature interfaceMember =
- checkMember(C, 'method1', checkType: CHECK_INTERFACE,
- synthesizedFrom: [A, B],
- functionType: env.functionType(dynamic_ , []));
- MemberSignature classMember =
- checkMember(C, 'method1', checkType: CHECK_CLASS, inheritedFrom: A);
- Expect.notEquals(interfaceMember, classMember);
-
- // A: method2()
- // B: method2(a)
- // C class: method2() -- inherited from A.
- // C interface: dynamic method2([a]) -- synthesized from A and B.
- interfaceMember =
- checkMember(C, 'method2', checkType: CHECK_INTERFACE,
- synthesizedFrom: [A, B],
- functionType: env.functionType(dynamic_ , [],
- optionalParameters: [dynamic_]));
- classMember =
- checkMember(C, 'method2', checkType: CHECK_CLASS, inheritedFrom: A);
- Expect.notEquals(interfaceMember, classMember);
- }));
+ // A: method2()
+ // B: method2(a)
+ // C class: method2() -- inherited from A.
+ // C interface: dynamic method2([a]) -- synthesized from A and B.
+ interfaceMember = checkMember(C, 'method2',
+ checkType: CHECK_INTERFACE,
+ synthesizedFrom: [A, B],
+ functionType:
+ env.functionType(dynamic_, [], optionalParameters: [dynamic_]));
+ classMember =
+ checkMember(C, 'method2', checkType: CHECK_CLASS, inheritedFrom: A);
+ Expect.notEquals(interfaceMember, classMember);
+ }));
}
-
void testMixinMembers() {
asyncTest(() => TypeEnvironment.create(r"""
class A<T> {
@@ -638,71 +674,67 @@
}
abstract class C<U, V> extends Object with A<U> implements B<V> {}
""").then((env) {
+ DynamicType dynamic_ = env['dynamic'];
+ VoidType void_ = env['void'];
+ InterfaceType num_ = env['num'];
+ InterfaceType int_ = env['int'];
- DynamicType dynamic_ = env['dynamic'];
- VoidType void_ = env['void'];
- InterfaceType num_ = env['num'];
- InterfaceType int_ = env['int'];
+ ClassElement A = env.getElement('A');
+ ClassElement B = env.getElement('B');
+ ClassElement C = env.getElement('C');
+ InterfaceType C_this = C.thisType;
+ TypeVariableType C_U = C_this.typeArguments[0];
+ TypeVariableType C_V = C_this.typeArguments[1];
+ InterfaceType A_U = instantiate(A, [C_U]);
+ InterfaceType B_V = instantiate(B, [C_V]);
- ClassElement A = env.getElement('A');
- ClassElement B = env.getElement('B');
- ClassElement C = env.getElement('C');
- InterfaceType C_this = C.thisType;
- TypeVariableType C_U = C_this.typeArguments[0];
- TypeVariableType C_V = C_this.typeArguments[1];
- InterfaceType A_U = instantiate(A, [C_U]);
- InterfaceType B_V = instantiate(B, [C_V]);
+ // Ensure that members have been computed on all classes.
+ MembersCreator.computeAllClassMembers(env.resolution, C);
- // Ensure that members have been computed on all classes.
- MembersCreator.computeAllClassMembers(env.resolution, C);
+ // A: method1()
+ // B: method1()
+ // C class: method1() -- inherited from A.
+ // C interface: dynamic method1() -- synthesized from A and B.
+ MemberSignature interfaceMember = checkMember(C_this, 'method1',
+ checkType: CHECK_INTERFACE,
+ synthesizedFrom: [A_U, B_V],
+ functionType: env.functionType(dynamic_, []));
+ MemberSignature classMember = checkMember(C_this, 'method1',
+ checkType: CHECK_CLASS, inheritedFrom: A_U);
+ Expect.notEquals(interfaceMember, classMember);
- // A: method1()
- // B: method1()
- // C class: method1() -- inherited from A.
- // C interface: dynamic method1() -- synthesized from A and B.
- MemberSignature interfaceMember =
- checkMember(C_this, 'method1', checkType: CHECK_INTERFACE,
- synthesizedFrom: [A_U, B_V],
- functionType: env.functionType(dynamic_ , []));
- MemberSignature classMember =
- checkMember(C_this, 'method1', checkType: CHECK_CLASS,
- inheritedFrom: A_U);
- Expect.notEquals(interfaceMember, classMember);
+ // A: method2()
+ // B: method2(a)
+ // C class: method2() -- inherited from A.
+ // C interface: dynamic method2([a]) -- synthesized from A and B.
+ interfaceMember = checkMember(C_this, 'method2',
+ checkType: CHECK_INTERFACE,
+ synthesizedFrom: [A_U, B_V],
+ functionType:
+ env.functionType(dynamic_, [], optionalParameters: [dynamic_]));
+ classMember = checkMember(C_this, 'method2',
+ checkType: CHECK_CLASS, inheritedFrom: A_U);
+ Expect.notEquals(interfaceMember, classMember);
- // A: method2()
- // B: method2(a)
- // C class: method2() -- inherited from A.
- // C interface: dynamic method2([a]) -- synthesized from A and B.
- interfaceMember =
- checkMember(C_this, 'method2', checkType: CHECK_INTERFACE,
- synthesizedFrom: [A_U, B_V],
- functionType: env.functionType(dynamic_ , [],
- optionalParameters: [dynamic_]));
- classMember =
- checkMember(C_this, 'method2', checkType: CHECK_CLASS,
- inheritedFrom: A_U);
- Expect.notEquals(interfaceMember, classMember);
+ // A: method3(U a)
+ // B: method3(V a)
+ // C class: method3(U a) -- inherited from A.
+ // C interface: dynamic method3(a) -- synthesized from A and B.
+ interfaceMember = checkMember(C_this, 'method3',
+ checkType: CHECK_INTERFACE,
+ synthesizedFrom: [A_U, B_V],
+ functionType: env.functionType(dynamic_, [dynamic_]));
+ classMember = checkMember(C_this, 'method3',
+ checkType: CHECK_CLASS, inheritedFrom: A_U);
+ Expect.notEquals(interfaceMember, classMember);
- // A: method3(U a)
- // B: method3(V a)
- // C class: method3(U a) -- inherited from A.
- // C interface: dynamic method3(a) -- synthesized from A and B.
- interfaceMember =
- checkMember(C_this, 'method3', checkType: CHECK_INTERFACE,
- synthesizedFrom: [A_U, B_V],
- functionType: env.functionType(dynamic_ , [dynamic_]));
- classMember =
- checkMember(C_this, 'method3', checkType: CHECK_CLASS,
- inheritedFrom: A_U);
- Expect.notEquals(interfaceMember, classMember);
-
- // A: method4(U a)
- // B: --
- // C class: method4(U a) -- inherited from A.
- // C interface: method4(U a) -- inherited from A.
- checkMember(C_this, 'method4', checkType: ALSO_CLASS_MEMBER,
- inheritedFrom: A_U);
- }));
+ // A: method4(U a)
+ // B: --
+ // C class: method4(U a) -- inherited from A.
+ // C interface: method4(U a) -- inherited from A.
+ checkMember(C_this, 'method4',
+ checkType: ALSO_CLASS_MEMBER, inheritedFrom: A_U);
+ }));
}
void testMixinMembersWithoutImplements() {
@@ -714,21 +746,21 @@
}
abstract class C extends Object with B {}
""").then((env) {
+ DynamicType dynamic_ = env['dynamic'];
+ VoidType void_ = env['void'];
+ InterfaceType num_ = env['num'];
+ InterfaceType int_ = env['int'];
- DynamicType dynamic_ = env['dynamic'];
- VoidType void_ = env['void'];
- InterfaceType num_ = env['num'];
- InterfaceType int_ = env['int'];
+ InterfaceType A = env['A'];
+ InterfaceType B = env['B'];
+ InterfaceType C = env['C'];
- InterfaceType A = env['A'];
- InterfaceType B = env['B'];
- InterfaceType C = env['C'];
+ // Ensure that members have been computed on all classes.
+ MembersCreator.computeAllClassMembers(env.resolution, C.element);
- // Ensure that members have been computed on all classes.
- MembersCreator.computeAllClassMembers(env.resolution, C.element);
-
- checkMember(C, 'm', checkType: NO_CLASS_MEMBER,
- inheritedFrom: A,
- functionType: env.functionType(dynamic_ , []));
- }));
-}
\ No newline at end of file
+ checkMember(C, 'm',
+ checkType: NO_CLASS_MEMBER,
+ inheritedFrom: A,
+ functionType: env.functionType(dynamic_, []));
+ }));
+}
diff --git a/tests/compiler/dart2js/memory_compiler.dart b/tests/compiler/dart2js/memory_compiler.dart
index baa0102..240da71 100644
--- a/tests/compiler/dart2js/memory_compiler.dart
+++ b/tests/compiler/dart2js/memory_compiler.dart
@@ -6,28 +6,23 @@
import 'dart:async';
-import 'package:compiler/compiler.dart' show
- DiagnosticHandler;
-import 'package:compiler/compiler_new.dart' show
- CompilationResult,
- CompilerDiagnostics,
- CompilerOutput,
- Diagnostic,
- PackagesDiscoveryProvider;
-import 'package:compiler/src/diagnostics/messages.dart' show
- Message;
-import 'package:compiler/src/null_compiler_output.dart' show
- NullCompilerOutput;
-import 'package:compiler/src/library_loader.dart' show
- LoadedLibraries;
-import 'package:compiler/src/options.dart' show
- CompilerOptions;
+import 'package:compiler/compiler.dart' show DiagnosticHandler;
+import 'package:compiler/compiler_new.dart'
+ show
+ CompilationResult,
+ CompilerDiagnostics,
+ CompilerOutput,
+ Diagnostic,
+ PackagesDiscoveryProvider;
+import 'package:compiler/src/diagnostics/messages.dart' show Message;
+import 'package:compiler/src/null_compiler_output.dart' show NullCompilerOutput;
+import 'package:compiler/src/library_loader.dart' show LoadedLibraries;
+import 'package:compiler/src/options.dart' show CompilerOptions;
import 'memory_source_file_helper.dart';
export 'output_collector.dart';
-export 'package:compiler/compiler_new.dart' show
- CompilationResult;
+export 'package:compiler/compiler_new.dart' show CompilationResult;
export 'diagnostic_helper.dart';
class MultiDiagnostics implements CompilerDiagnostics {
@@ -36,8 +31,8 @@
const MultiDiagnostics([this.diagnosticsList = const []]);
@override
- void report(Message message, Uri uri, int begin, int end,
- String text, Diagnostic kind) {
+ void report(Message message, Uri uri, int begin, int end, String text,
+ Diagnostic kind) {
for (CompilerDiagnostics diagnostics in diagnosticsList) {
diagnostics.report(message, uri, begin, end, text, kind);
}
@@ -45,17 +40,15 @@
}
CompilerDiagnostics createCompilerDiagnostics(
- CompilerDiagnostics diagnostics,
- SourceFileProvider provider,
- {bool showDiagnostics: true,
- bool verbose: false}) {
+ CompilerDiagnostics diagnostics, SourceFileProvider provider,
+ {bool showDiagnostics: true, bool verbose: false}) {
CompilerDiagnostics handler = diagnostics;
if (showDiagnostics) {
if (diagnostics == null) {
handler = new FormattingDiagnosticHandler(provider)..verbose = verbose;
} else {
- var formattingHandler =
- new FormattingDiagnosticHandler(provider)..verbose = verbose;
+ var formattingHandler = new FormattingDiagnosticHandler(provider)
+ ..verbose = verbose;
handler = new MultiDiagnostics([diagnostics, formattingHandler]);
}
} else if (diagnostics == null) {
@@ -69,18 +62,18 @@
Future<CompilationResult> runCompiler(
{Map<String, String> memorySourceFiles: const <String, String>{},
- Uri entryPoint,
- List<Uri> entryPoints,
- List<Uri> resolutionInputs,
- CompilerDiagnostics diagnosticHandler,
- CompilerOutput outputProvider,
- List<String> options: const <String>[],
- CompilerImpl cachedCompiler,
- bool showDiagnostics: true,
- Uri packageRoot,
- Uri packageConfig,
- PackagesDiscoveryProvider packagesDiscoveryProvider,
- void beforeRun(CompilerImpl compiler)}) async {
+ Uri entryPoint,
+ List<Uri> entryPoints,
+ List<Uri> resolutionInputs,
+ CompilerDiagnostics diagnosticHandler,
+ CompilerOutput outputProvider,
+ List<String> options: const <String>[],
+ CompilerImpl cachedCompiler,
+ bool showDiagnostics: true,
+ Uri packageRoot,
+ Uri packageConfig,
+ PackagesDiscoveryProvider packagesDiscoveryProvider,
+ void beforeRun(CompilerImpl compiler)}) async {
if (entryPoint == null) {
entryPoint = Uri.parse('memory:main.dart');
}
@@ -106,16 +99,16 @@
CompilerImpl compilerFor(
{Uri entryPoint,
- List<Uri> resolutionInputs,
- Map<String, String> memorySourceFiles: const <String, String>{},
- CompilerDiagnostics diagnosticHandler,
- CompilerOutput outputProvider,
- List<String> options: const <String>[],
- CompilerImpl cachedCompiler,
- bool showDiagnostics: true,
- Uri packageRoot,
- Uri packageConfig,
- PackagesDiscoveryProvider packagesDiscoveryProvider}) {
+ List<Uri> resolutionInputs,
+ Map<String, String> memorySourceFiles: const <String, String>{},
+ CompilerDiagnostics diagnosticHandler,
+ CompilerOutput outputProvider,
+ List<String> options: const <String>[],
+ CompilerImpl cachedCompiler,
+ bool showDiagnostics: true,
+ Uri packageRoot,
+ Uri packageConfig,
+ PackagesDiscoveryProvider packagesDiscoveryProvider}) {
Uri libraryRoot = Uri.base.resolve('sdk/');
if (packageRoot == null &&
packageConfig == null &&
@@ -124,6 +117,10 @@
packageRoot = Uri.base.resolve(Platform.packageRoot);
} else if (Platform.packageConfig != null) {
packageConfig = Uri.base.resolve(Platform.packageConfig);
+ } else {
+ // The tests are run with the base directory as the SDK root
+ // so just use the .packages file there.
+ packageConfig = Uri.base.resolve('.packages');
}
}
@@ -139,8 +136,7 @@
provider = expando[cachedCompiler.provider];
provider.memorySourceFiles = memorySourceFiles;
}
- diagnosticHandler = createCompilerDiagnostics(
- diagnosticHandler, provider,
+ diagnosticHandler = createCompilerDiagnostics(diagnosticHandler, provider,
showDiagnostics: showDiagnostics,
verbose: options.contains('-v') || options.contains('--verbose'));
@@ -183,8 +179,8 @@
// this call.
compiler.onLibrariesLoaded(new MemoryLoadedLibraries(copiedLibraries));
- compiler.backend.constantCompilerTask.copyConstantValues(
- cachedCompiler.backend.constantCompilerTask);
+ compiler.backend.constantCompilerTask
+ .copyConstantValues(cachedCompiler.backend.constantCompilerTask);
Iterable cachedTreeElements =
cachedCompiler.enqueuer.resolution.processedElements;
@@ -237,10 +233,8 @@
Uri get rootUri => null;
}
-
DiagnosticHandler createDiagnosticHandler(DiagnosticHandler diagnosticHandler,
- SourceFileProvider provider,
- bool showDiagnostics) {
+ SourceFileProvider provider, bool showDiagnostics) {
var handler = diagnosticHandler;
if (showDiagnostics) {
if (diagnosticHandler == null) {
diff --git a/tests/compiler/dart2js/memory_source_file_helper.dart b/tests/compiler/dart2js/memory_source_file_helper.dart
index c6b3b3c..a198aef 100644
--- a/tests/compiler/dart2js/memory_source_file_helper.dart
+++ b/tests/compiler/dart2js/memory_source_file_helper.dart
@@ -7,20 +7,17 @@
import 'dart:async' show Future;
export 'dart:io' show Platform;
-export 'package:compiler/src/apiimpl.dart'
- show CompilerImpl;
+export 'package:compiler/src/apiimpl.dart' show CompilerImpl;
-export 'package:compiler/src/filenames.dart'
- show currentDirectory;
+export 'package:compiler/src/filenames.dart' show currentDirectory;
import 'package:compiler/src/io/source_file.dart'
- show StringSourceFile, SourceFile;
+ show StringSourceFile, SourceFile;
-import 'package:compiler/src/source_file_provider.dart'
- show SourceFileProvider;
+import 'package:compiler/src/source_file_provider.dart' show SourceFileProvider;
export 'package:compiler/src/source_file_provider.dart'
- show SourceFileProvider, FormattingDiagnosticHandler;
+ show SourceFileProvider, FormattingDiagnosticHandler;
class MemorySourceFileProvider extends SourceFileProvider {
Map<String, String> memorySourceFiles;
diff --git a/tests/compiler/dart2js/message_kind_helper.dart b/tests/compiler/dart2js/message_kind_helper.dart
index 31094e4..03252d1 100644
--- a/tests/compiler/dart2js/message_kind_helper.dart
+++ b/tests/compiler/dart2js/message_kind_helper.dart
@@ -8,13 +8,10 @@
import 'dart:async';
import 'package:compiler/src/commandline_options.dart';
-import 'package:compiler/src/compiler.dart' show
- Compiler;
-import 'package:compiler/src/diagnostics/messages.dart' show
- MessageKind,
- MessageTemplate;
-import 'package:compiler/compiler_new.dart' show
- Diagnostic;
+import 'package:compiler/src/compiler.dart' show Compiler;
+import 'package:compiler/src/diagnostics/messages.dart'
+ show MessageKind, MessageTemplate;
+import 'package:compiler/compiler_new.dart' show Diagnostic;
import 'memory_compiler.dart';
@@ -25,26 +22,26 @@
/// However, consider that a single concise diagnostic is easier to understand,
/// so try to change error reporting logic before adding an exception.
final Set<MessageKind> kindsWithExtraMessages = new Set<MessageKind>.from([
- // If you add something here, please file a *new* bug report.
- // See http://dartbug.com/18361:
- MessageKind.CANNOT_EXTEND_MALFORMED,
- MessageKind.CANNOT_IMPLEMENT_MALFORMED,
- MessageKind.CANNOT_MIXIN,
- MessageKind.CANNOT_MIXIN_MALFORMED,
- MessageKind.CANNOT_INSTANTIATE_ENUM,
- MessageKind.CYCLIC_TYPEDEF_ONE,
- MessageKind.DUPLICATE_DEFINITION,
- MessageKind.EQUAL_MAP_ENTRY_KEY,
- MessageKind.FINAL_FUNCTION_TYPE_PARAMETER,
- MessageKind.FORMAL_DECLARED_CONST,
- MessageKind.FORMAL_DECLARED_STATIC,
- MessageKind.FUNCTION_TYPE_FORMAL_WITH_DEFAULT,
- MessageKind.HIDDEN_IMPLICIT_IMPORT,
- MessageKind.HIDDEN_IMPORT,
- MessageKind.INHERIT_GETTER_AND_METHOD,
- MessageKind.UNIMPLEMENTED_METHOD,
- MessageKind.UNIMPLEMENTED_METHOD_ONE,
- MessageKind.VAR_FUNCTION_TYPE_PARAMETER,
+ // If you add something here, please file a *new* bug report.
+ // See http://dartbug.com/18361:
+ MessageKind.CANNOT_EXTEND_MALFORMED,
+ MessageKind.CANNOT_IMPLEMENT_MALFORMED,
+ MessageKind.CANNOT_MIXIN,
+ MessageKind.CANNOT_MIXIN_MALFORMED,
+ MessageKind.CANNOT_INSTANTIATE_ENUM,
+ MessageKind.CYCLIC_TYPEDEF_ONE,
+ MessageKind.DUPLICATE_DEFINITION,
+ MessageKind.EQUAL_MAP_ENTRY_KEY,
+ MessageKind.FINAL_FUNCTION_TYPE_PARAMETER,
+ MessageKind.FORMAL_DECLARED_CONST,
+ MessageKind.FORMAL_DECLARED_STATIC,
+ MessageKind.FUNCTION_TYPE_FORMAL_WITH_DEFAULT,
+ MessageKind.HIDDEN_IMPLICIT_IMPORT,
+ MessageKind.HIDDEN_IMPORT,
+ MessageKind.INHERIT_GETTER_AND_METHOD,
+ MessageKind.UNIMPLEMENTED_METHOD,
+ MessageKind.UNIMPLEMENTED_METHOD_ONE,
+ MessageKind.VAR_FUNCTION_TYPE_PARAMETER,
]);
/// Most messages can be tested without causing a fatal error. Add an exception
@@ -52,7 +49,7 @@
/// Try to avoid adding exceptions here; a fatal error causes the compiler to
/// stop before analyzing all input, and it isn't safe to reuse it.
final Set<MessageKind> kindsWithPendingClasses = new Set<MessageKind>.from([
- // If you add something here, please file a *new* bug report.
+ // If you add something here, please file a *new* bug report.
]);
Future<Compiler> check(MessageTemplate template, Compiler cachedCompiler) {
@@ -62,31 +59,33 @@
if (example is String) {
example = {'main.dart': example};
} else {
- Expect.isTrue(example is Map,
- "Example must be either a String or a Map.");
+ Expect.isTrue(
+ example is Map, "Example must be either a String or a Map.");
Expect.isTrue(example.containsKey('main.dart'),
- "Example map must contain a 'main.dart' entry.");
+ "Example map must contain a 'main.dart' entry.");
}
DiagnosticCollector collector = new DiagnosticCollector();
Compiler compiler = compilerFor(
memorySourceFiles: example,
diagnosticHandler: collector,
- options: [Flags.analyzeOnly,
- Flags.enableExperimentalMirrors]..addAll(template.options),
+ options: [Flags.analyzeOnly, Flags.enableExperimentalMirrors]
+ ..addAll(template.options),
cachedCompiler: cachedCompiler);
return compiler.run(Uri.parse('memory:main.dart')).then((_) {
- Iterable<CollectedMessage> messages = collector.filterMessagesByKinds(
- [Diagnostic.ERROR,
- Diagnostic.WARNING,
- Diagnostic.HINT,
- Diagnostic.CRASH]);
+ Iterable<CollectedMessage> messages = collector.filterMessagesByKinds([
+ Diagnostic.ERROR,
+ Diagnostic.WARNING,
+ Diagnostic.HINT,
+ Diagnostic.CRASH
+ ]);
Expect.isFalse(messages.isEmpty, 'No messages in """$example"""');
String expectedText = !template.hasHowToFix
- ? template.template : '${template.template}\n${template.howToFix}';
+ ? template.template
+ : '${template.template}\n${template.howToFix}';
String pattern = expectedText.replaceAllMapped(
new RegExp(ESCAPE_REGEXP), (m) => '\\${m[0]}');
pattern = pattern.replaceAll(new RegExp(r'#\\\{[^}]*\\\}'), '.*');
@@ -110,7 +109,8 @@
unexpectedMessages.add(message);
}
}
- Expect.isTrue(messageFound,
+ Expect.isTrue(
+ messageFound,
'${template.kind}} does not match any in\n '
'${messages.join('\n ')}');
var reporter = compiler.reporter;
@@ -129,18 +129,16 @@
bool pendingStuff = false;
for (var e in compiler.resolver.pendingClassesToBePostProcessed) {
pendingStuff = true;
- compiler.reporter.reportInfo(
- e, MessageKind.GENERIC,
+ compiler.reporter.reportInfo(e, MessageKind.GENERIC,
{'text': 'Pending class to be post-processed.'});
}
for (var e in compiler.resolver.pendingClassesToBeResolved) {
pendingStuff = true;
compiler.reporter.reportInfo(
- e, MessageKind.GENERIC,
- {'text': 'Pending class to be resolved.'});
+ e, MessageKind.GENERIC, {'text': 'Pending class to be resolved.'});
}
- Expect.isTrue(!pendingStuff ||
- kindsWithPendingClasses.contains(template));
+ Expect
+ .isTrue(!pendingStuff || kindsWithPendingClasses.contains(template));
if (!pendingStuff) {
// If there is pending stuff, or the compiler was cancelled, we
diff --git a/tests/compiler/dart2js/message_kind_test.dart b/tests/compiler/dart2js/message_kind_test.dart
index 5ba3ec6..c4b4537 100644
--- a/tests/compiler/dart2js/message_kind_test.dart
+++ b/tests/compiler/dart2js/message_kind_test.dart
@@ -5,9 +5,8 @@
import 'package:expect/expect.dart';
import 'dart:async';
import "package:async_helper/async_helper.dart";
-import 'package:compiler/src/diagnostics/messages.dart' show
- MessageKind,
- MessageTemplate;
+import 'package:compiler/src/diagnostics/messages.dart'
+ show MessageKind, MessageTemplate;
import 'message_kind_helper.dart';
@@ -23,30 +22,34 @@
if (!arguments.isEmpty && !arguments.contains(name)) continue;
if (name == 'GENERIC' // Shouldn't be used.
// We can't provoke a crash.
- || name == 'COMPILER_CRASHED'
- || name == 'PLEASE_REPORT_THE_CRASH'
+ ||
+ name == 'COMPILER_CRASHED' ||
+ name == 'PLEASE_REPORT_THE_CRASH'
// We cannot provide examples for patch errors.
- || name.startsWith('PATCH_')
- || name == 'LIBRARY_NOT_SUPPORTED'
+ ||
+ name.startsWith('PATCH_') ||
+ name == 'LIBRARY_NOT_SUPPORTED'
// TODO(johnniwinther): Remove these when [Compiler.reportUnusedCode] is
// reenabled.
- || name == 'UNUSED_METHOD'
- || name == 'UNUSED_CLASS'
- || name == 'UNUSED_TYPEDEF') continue;
+ ||
+ name == 'UNUSED_METHOD' ||
+ name == 'UNUSED_CLASS' ||
+ name == 'UNUSED_TYPEDEF') continue;
if (template.examples != null) {
examples.add(template);
} else {
print("No example in '$name'");
}
- };
+ }
+ ;
var cachedCompiler;
asyncTest(() => Future.forEach(examples, (MessageTemplate template) {
- print("Checking '${template.kind}'.");
- Stopwatch sw = new Stopwatch()..start();
- return check(template, cachedCompiler).then((var compiler) {
- cachedCompiler = compiler;
- sw.stop();
- print("Checked '${template.kind}' in ${sw.elapsedMilliseconds}ms.");
- });
- }));
+ print("Checking '${template.kind}'.");
+ Stopwatch sw = new Stopwatch()..start();
+ return check(template, cachedCompiler).then((var compiler) {
+ cachedCompiler = compiler;
+ sw.stop();
+ print("Checked '${template.kind}' in ${sw.elapsedMilliseconds}ms.");
+ });
+ }));
}
diff --git a/tests/compiler/dart2js/message_span_test.dart b/tests/compiler/dart2js/message_span_test.dart
index 655b814..57dbddb 100644
--- a/tests/compiler/dart2js/message_span_test.dart
+++ b/tests/compiler/dart2js/message_span_test.dart
@@ -11,7 +11,8 @@
import 'memory_source_file_helper.dart';
const List<Test> TESTS = const <Test>[
- const Test('''
+ const Test(
+ '''
class A { A(b); }
class B extends A {
a() {}
@@ -23,12 +24,13 @@
var members;
}
main() => new B();''',
- const {
- MessageKind.NO_MATCHING_CONSTRUCTOR_FOR_IMPLICIT: '''
+ const {
+ MessageKind.NO_MATCHING_CONSTRUCTOR_FOR_IMPLICIT: '''
class B extends A {
-^^^^^^^^^^^^^^^^^'''}),
-
- const Test('''
+^^^^^^^^^^^^^^^^^'''
+ }),
+ const Test(
+ '''
class I {}
class A { A(b); }
class B extends A implements I {
@@ -41,12 +43,13 @@
var members;
}
main() => new B();''',
- const {
- MessageKind.NO_MATCHING_CONSTRUCTOR_FOR_IMPLICIT: '''
+ const {
+ MessageKind.NO_MATCHING_CONSTRUCTOR_FOR_IMPLICIT: '''
class B extends A implements I {
-^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^'''}),
-
- const Test('''
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^'''
+ }),
+ const Test(
+ '''
class M<T> {}
class A { A(b); }
class B extends A with M<int> {
@@ -59,12 +62,13 @@
var members;
}
main() => new B();''',
- const {
- MessageKind.NO_MATCHING_CONSTRUCTOR_FOR_IMPLICIT: '''
+ const {
+ MessageKind.NO_MATCHING_CONSTRUCTOR_FOR_IMPLICIT: '''
class B extends A with M<int> {
-^^^^^^^^^^^^^^^^^^^^^^^^^^^^^'''}),
-
- const Test('''
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^'''
+ }),
+ const Test(
+ '''
class A { A(b); }
class B
extends A {
@@ -77,25 +81,27 @@
var members;
}
main() => new B();''',
- const {
- MessageKind.NO_MATCHING_CONSTRUCTOR_FOR_IMPLICIT: '''
+ const {
+ MessageKind.NO_MATCHING_CONSTRUCTOR_FOR_IMPLICIT: '''
class B
extends A {
-'''}),
-
- const Test('''
+'''
+ }),
+ const Test(
+ '''
void foo(int a) {
// a
// non-empty
// body
}
main() => foo('');''',
- const {
- MessageKind.THIS_IS_THE_METHOD: '''
+ const {
+ MessageKind.THIS_IS_THE_METHOD: '''
void foo(int a) {
-^^^^^^^^^^^^^^^'''}),
-
- const Test('''
+^^^^^^^^^^^^^^^'''
+ }),
+ const Test(
+ '''
void foo(int a,
int b) {
// a
@@ -103,13 +109,14 @@
// body
}
main() => foo('', 0);''',
- const {
- MessageKind.THIS_IS_THE_METHOD: '''
+ const {
+ MessageKind.THIS_IS_THE_METHOD: '''
void foo(int a,
int b) {
-'''}),
-
- const Test('''
+'''
+ }),
+ const Test(
+ '''
class A {
int foo() {
// a
@@ -126,13 +133,14 @@
}
}
main() => new B();''',
- const {
- MessageKind.CANNOT_OVERRIDE_METHOD_WITH_GETTER: '''
+ const {
+ MessageKind.CANNOT_OVERRIDE_METHOD_WITH_GETTER: '''
int get foo {
^^^^^^^^^^^''',
- MessageKind.CANNOT_OVERRIDE_METHOD_WITH_GETTER_CONT: '''
+ MessageKind.CANNOT_OVERRIDE_METHOD_WITH_GETTER_CONT: '''
int foo() {
- ^^^^^^^^^'''}),
+ ^^^^^^^^^'''
+ }),
];
class Test {
@@ -165,9 +173,11 @@
String locationMessage =
sourceFile.getLocationMessage(MARKER, message.begin, message.end);
// Remove `filename:line:column:` and message.
- String strippedLocationMessage = locationMessage.substring(
- locationMessage.indexOf(MARKER) + MARKER.length + 1);
- Expect.equals(expectedSpanText, strippedLocationMessage,
+ String strippedLocationMessage = locationMessage
+ .substring(locationMessage.indexOf(MARKER) + MARKER.length + 1);
+ Expect.equals(
+ expectedSpanText,
+ strippedLocationMessage,
"Unexpected span for ${message.messageKind} in\n${test.code}"
"\nExpected:${expectedSpanText.codeUnits}"
"\nActual :${strippedLocationMessage.codeUnits}");
@@ -179,4 +189,4 @@
});
}
});
-}
\ No newline at end of file
+}
diff --git a/tests/compiler/dart2js/metadata_test.dart b/tests/compiler/dart2js/metadata_test.dart
index 9255a75..ef2994c 100644
--- a/tests/compiler/dart2js/metadata_test.dart
+++ b/tests/compiler/dart2js/metadata_test.dart
@@ -3,24 +3,21 @@
// BSD-style license that can be found in the LICENSE file.
import 'package:async_helper/async_helper.dart';
-import 'package:compiler/src/constants/values.dart'
- show PrimitiveConstantValue;
+import 'package:compiler/src/constants/values.dart' show PrimitiveConstantValue;
import 'package:expect/expect.dart';
import 'compiler_helper.dart';
-import 'package:compiler/src/parser/partial_elements.dart' show
- PartialMetadataAnnotation;
-import 'package:compiler/src/diagnostics/diagnostic_listener.dart' show
- DiagnosticReporter;
+import 'package:compiler/src/parser/partial_elements.dart'
+ show PartialMetadataAnnotation;
+import 'package:compiler/src/diagnostics/diagnostic_listener.dart'
+ show DiagnosticReporter;
-void checkPosition(Spannable spannable,
- Node node,
- String source,
- DiagnosticReporter reporter) {
+void checkPosition(Spannable spannable, Node node, String source,
+ DiagnosticReporter reporter) {
SourceSpan span = reporter.spanFromSpannable(spannable);
- Expect.isTrue(span.begin < span.end,
- 'begin = ${span.begin}; end = ${span.end}');
- Expect.isTrue(span.end < source.length,
- 'end = ${span.end}; length = ${source.length}');
+ Expect.isTrue(
+ span.begin < span.end, 'begin = ${span.begin}; end = ${span.end}');
+ Expect.isTrue(
+ span.end < source.length, 'end = ${span.end}; length = ${source.length}');
String yield = source.substring(span.begin, span.end);
// TODO(ahe): The node does not include "@". Fix that.
@@ -28,7 +25,7 @@
}
void checkAnnotation(String name, String declaration,
- {bool isTopLevelOnly: false}) {
+ {bool isTopLevelOnly: false}) {
// Ensure that a compile-time constant can be resolved from an
// annotation.
var source1 = """const native = 'xyz';
@@ -38,8 +35,8 @@
compileAndCheck(source1, name, (compiler, element) {
compiler.enqueuer.resolution.queueIsClosed = false;
- Expect.equals(1, element.metadata.length,
- 'Unexpected metadata count on $element.');
+ Expect.equals(
+ 1, element.metadata.length, 'Unexpected metadata count on $element.');
PartialMetadataAnnotation annotation = element.metadata.first;
annotation.ensureResolved(compiler.resolution);
PrimitiveConstantValue value =
@@ -64,8 +61,8 @@
PartialMetadataAnnotation annotation2 = element.metadata.elementAt(1);
annotation1.ensureResolved(compiler.resolution);
annotation2.ensureResolved(compiler.resolution);
- Expect.isFalse(identical(annotation1, annotation2),
- 'expected unique instances');
+ Expect.isFalse(
+ identical(annotation1, annotation2), 'expected unique instances');
Expect.notEquals(annotation1, annotation2, 'expected unequal instances');
PrimitiveConstantValue value1 =
compiler.constants.getConstantValue(annotation1.constant);
@@ -129,8 +126,8 @@
PartialMetadataAnnotation annotation2 = element.metadata.elementAt(1);
annotation1.ensureResolved(compiler.resolution);
annotation2.ensureResolved(compiler.resolution);
- Expect.isFalse(identical(annotation1, annotation2),
- 'expected unique instances');
+ Expect.isFalse(
+ identical(annotation1, annotation2), 'expected unique instances');
Expect.notEquals(annotation1, annotation2, 'expected unequal instances');
PrimitiveConstantValue value1 =
compiler.constants.getConstantValue(annotation1.constant);
@@ -161,8 +158,7 @@
}
void testLibraryTags() {
- void compileAndCheckLibrary(
- String source,
+ void compileAndCheckLibrary(String source,
List<MetadataAnnotation> extractMetadata(LibraryElement element)) {
Uri partUri = new Uri(scheme: 'source', path: 'part.dart');
String partSource = '@native part of foo;';
@@ -173,26 +169,26 @@
Uri uri = new Uri(scheme: 'source', path: 'main.dart');
var compiler = compilerFor(source, uri)
- ..registerSource(partUri, partSource)
- ..registerSource(libUri, libSource);
+ ..registerSource(partUri, partSource)
+ ..registerSource(libUri, libSource);
asyncTest(() => compiler.run(uri).then((_) {
- compiler.enqueuer.resolution.queueIsClosed = false;
- LibraryElement element = compiler.libraryLoader.lookupLibrary(uri);
- Expect.isNotNull(element, 'Cannot find $uri');
+ compiler.enqueuer.resolution.queueIsClosed = false;
+ LibraryElement element = compiler.libraryLoader.lookupLibrary(uri);
+ Expect.isNotNull(element, 'Cannot find $uri');
- List<MetadataAnnotation> metadata = extractMetadata(element);
- Expect.equals(1, metadata.length);
+ List<MetadataAnnotation> metadata = extractMetadata(element);
+ Expect.equals(1, metadata.length);
- PartialMetadataAnnotation annotation = metadata.first;
- annotation.ensureResolved(compiler.resolution);
- PrimitiveConstantValue value =
- compiler.constants.getConstantValue(annotation.constant);
- Expect.stringEquals('xyz', value.primitiveValue.slowToString());
+ PartialMetadataAnnotation annotation = metadata.first;
+ annotation.ensureResolved(compiler.resolution);
+ PrimitiveConstantValue value =
+ compiler.constants.getConstantValue(annotation.constant);
+ Expect.stringEquals('xyz', value.primitiveValue.slowToString());
- checkPosition(
- annotation, annotation.cachedNode, source, compiler.reporter);
- }));
+ checkPosition(
+ annotation, annotation.cachedNode, source, compiler.reporter);
+ }));
}
var source;
@@ -225,8 +221,8 @@
part 'part.dart';
const native = 'xyz';
main() {}""";
- compileAndCheckLibrary(source,
- (e) => e.compilationUnits.first.partTag.metadata);
+ compileAndCheckLibrary(
+ source, (e) => e.compilationUnits.first.partTag.metadata);
}
void main() {
diff --git a/tests/compiler/dart2js/minify_many_locals_test.dart b/tests/compiler/dart2js/minify_many_locals_test.dart
index 4a854e7..a44002f 100644
--- a/tests/compiler/dart2js/minify_many_locals_test.dart
+++ b/tests/compiler/dart2js/minify_many_locals_test.dart
@@ -26,27 +26,27 @@
buffer.write("$NUMBER_OF_PARAMETERS; return i; }");
String code = buffer.toString();
- asyncTest(() => compile(code, entry: 'foo', minify: true)
- .then((String generated) {
- RegExp re = new RegExp(r"\(a,b,c");
- Expect.isTrue(re.hasMatch(generated));
+ asyncTest(
+ () => compile(code, entry: 'foo', minify: true).then((String generated) {
+ RegExp re = new RegExp(r"\(a,b,c");
+ Expect.isTrue(re.hasMatch(generated));
- re = new RegExp(r"x,y,z,a0,a1,a2");
- Expect.isTrue(re.hasMatch(generated));
+ re = new RegExp(r"x,y,z,a0,a1,a2");
+ Expect.isTrue(re.hasMatch(generated));
- re = new RegExp(r"y,z,a0,a1,a2,a3,a4,a5,a6");
- Expect.isTrue(re.hasMatch(generated));
+ re = new RegExp(r"y,z,a0,a1,a2,a3,a4,a5,a6");
+ Expect.isTrue(re.hasMatch(generated));
- re = new RegExp(r"g8,g9,h0,h1");
- Expect.isTrue(re.hasMatch(generated));
+ re = new RegExp(r"g8,g9,h0,h1");
+ Expect.isTrue(re.hasMatch(generated));
- re = new RegExp(r"z8,z9,aa0,aa1,aa2");
- Expect.isTrue(re.hasMatch(generated));
+ re = new RegExp(r"z8,z9,aa0,aa1,aa2");
+ Expect.isTrue(re.hasMatch(generated));
- re = new RegExp(r"aa9,ab0,ab1");
- Expect.isTrue(re.hasMatch(generated));
+ re = new RegExp(r"aa9,ab0,ab1");
+ Expect.isTrue(re.hasMatch(generated));
- re = new RegExp(r"az9,ba0,ba1");
- Expect.isTrue(re.hasMatch(generated));
- }));
+ re = new RegExp(r"az9,ba0,ba1");
+ Expect.isTrue(re.hasMatch(generated));
+ }));
}
diff --git a/tests/compiler/dart2js/minimal_resolution_test.dart b/tests/compiler/dart2js/minimal_resolution_test.dart
index 8c35948..4304afa 100644
--- a/tests/compiler/dart2js/minimal_resolution_test.dart
+++ b/tests/compiler/dart2js/minimal_resolution_test.dart
@@ -39,16 +39,17 @@
memorySourceFiles: {'main.dart': code}, options: ['--analyze-only']);
Expect.isTrue(result.isSuccess);
Compiler compiler = result.compiler;
- Expect.equals(proxyConstantComputed,
+ Expect.equals(
+ proxyConstantComputed,
compiler.resolution.wasProxyConstantComputedTestingOnly,
"Unexpected computation of proxy constant.");
checkInstantiated(
- compiler, compiler.commonElements.coreLibrary.find('_Proxy'),
+ compiler,
+ compiler.commonElements.coreLibrary.find('_Proxy'),
proxyConstantComputed);
- checkInstantiated(
- compiler, compiler.commonElements.coreLibrary.find('Deprecated'),
- deprecatedClass);
+ checkInstantiated(compiler,
+ compiler.commonElements.coreLibrary.find('Deprecated'), deprecatedClass);
LibraryElement jsHelperLibrary =
compiler.libraryLoader.lookupLibrary(BackendHelpers.DART_JS_HELPER);
diff --git a/tests/compiler/dart2js/mirror_final_field_inferrer2_test.dart b/tests/compiler/dart2js/mirror_final_field_inferrer2_test.dart
index 09de1ab..4f109a4 100644
--- a/tests/compiler/dart2js/mirror_final_field_inferrer2_test.dart
+++ b/tests/compiler/dart2js/mirror_final_field_inferrer2_test.dart
@@ -10,7 +10,7 @@
import 'compiler_helper.dart' show findElement;
import 'type_mask_test_helper.dart';
-const MEMORY_SOURCE_FILES = const <String, String> {
+const MEMORY_SOURCE_FILES = const <String, String>{
'main.dart': """
import 'dart:mirrors';
@@ -31,7 +31,6 @@
var commonMasks = compiler.commonMasks;
var typesInferrer = compiler.globalInference.typesInferrer;
Expect.equals(commonMasks.uint31Type,
- simplify(typesInferrer.getTypeOfElement(element), compiler),
- 'field');
+ simplify(typesInferrer.getTypeOfElement(element), compiler), 'field');
});
}
diff --git a/tests/compiler/dart2js/mirror_final_field_inferrer_test.dart b/tests/compiler/dart2js/mirror_final_field_inferrer_test.dart
index 7663d51..31b555d 100644
--- a/tests/compiler/dart2js/mirror_final_field_inferrer_test.dart
+++ b/tests/compiler/dart2js/mirror_final_field_inferrer_test.dart
@@ -10,7 +10,7 @@
import 'compiler_helper.dart' show findElement;
import 'type_mask_test_helper.dart';
-const MEMORY_SOURCE_FILES = const <String, String> {
+const MEMORY_SOURCE_FILES = const <String, String>{
'main.dart': """
@MirrorsUsed(targets: 'field')
import 'dart:mirrors';
@@ -31,7 +31,6 @@
var commonMasks = compiler.commonMasks;
var typesInferrer = compiler.globalInference.typesInferrer;
Expect.equals(commonMasks.uint31Type,
- simplify(typesInferrer.getTypeOfElement(element), compiler),
- 'field');
+ simplify(typesInferrer.getTypeOfElement(element), compiler), 'field');
});
}
diff --git a/tests/compiler/dart2js/mirror_private_name_inheritance_test.dart b/tests/compiler/dart2js/mirror_private_name_inheritance_test.dart
index 8626b55..6209b4f 100644
--- a/tests/compiler/dart2js/mirror_private_name_inheritance_test.dart
+++ b/tests/compiler/dart2js/mirror_private_name_inheritance_test.dart
@@ -9,7 +9,7 @@
import 'memory_compiler.dart' show runCompiler;
import 'compiler_helper.dart' show findElement;
-const MEMORY_SOURCE_FILES = const <String, String> {
+const MEMORY_SOURCE_FILES = const <String, String>{
'main.dart': """
@MirrorsUsed(targets: 'Super')
import 'dart:mirrors';
@@ -40,7 +40,8 @@
var result = await runCompiler(memorySourceFiles: MEMORY_SOURCE_FILES);
var compiler = result.compiler;
- var superclass = findElement(compiler, 'Super', Uri.parse('memory:lib.dart'));
+ var superclass =
+ findElement(compiler, 'Super', Uri.parse('memory:lib.dart'));
var subclass = findElement(compiler, 'Subclass');
var oracle = compiler.backend.isAccessibleByReflection;
print(superclass.lookupMember('_private'));
diff --git a/tests/compiler/dart2js/mirror_tree_shaking_test.dart b/tests/compiler/dart2js/mirror_tree_shaking_test.dart
index 34f2b69..3618c816 100644
--- a/tests/compiler/dart2js/mirror_tree_shaking_test.dart
+++ b/tests/compiler/dart2js/mirror_tree_shaking_test.dart
@@ -6,8 +6,7 @@
import 'package:async_helper/async_helper.dart';
import 'package:compiler/src/compiler.dart';
-import 'package:compiler/src/js_backend/js_backend.dart'
- show JavaScriptBackend;
+import 'package:compiler/src/js_backend/js_backend.dart' show JavaScriptBackend;
import 'package:expect/expect.dart';
import 'memory_compiler.dart';
@@ -15,7 +14,7 @@
DiagnosticCollector collector = new DiagnosticCollector();
asyncTest(() async {
CompilationResult result = await runCompiler(
- memorySourceFiles: MEMORY_SOURCE_FILES, diagnosticHandler: collector);
+ memorySourceFiles: MEMORY_SOURCE_FILES, diagnosticHandler: collector);
Compiler compiler = result.compiler;
Expect.isTrue(collector.errors.isEmpty);
Expect.isTrue(collector.infos.isEmpty);
diff --git a/tests/compiler/dart2js/mirrors_used_test.dart b/tests/compiler/dart2js/mirrors_used_test.dart
index 629db24..1befda9 100644
--- a/tests/compiler/dart2js/mirrors_used_test.dart
+++ b/tests/compiler/dart2js/mirrors_used_test.dart
@@ -9,28 +9,22 @@
import 'package:expect/expect.dart';
import "package:async_helper/async_helper.dart";
-import 'memory_compiler.dart' show
- runCompiler;
+import 'memory_compiler.dart' show runCompiler;
-import 'package:compiler/src/apiimpl.dart' show
- CompilerImpl;
+import 'package:compiler/src/apiimpl.dart' show CompilerImpl;
-import 'package:compiler/src/constants/values.dart' show
- ConstantValue,
- TypeConstantValue;
+import 'package:compiler/src/constants/values.dart'
+ show ConstantValue, TypeConstantValue;
-import 'package:compiler/src/elements/elements.dart' show
- Element,
- Elements;
+import 'package:compiler/src/elements/elements.dart' show Element, Elements;
-import 'package:compiler/src/js_backend/js_backend.dart' show
- JavaScriptBackend;
+import 'package:compiler/src/js_backend/js_backend.dart' show JavaScriptBackend;
-import 'package:compiler/src/js_emitter/full_emitter/emitter.dart'
- as full show Emitter;
+import 'package:compiler/src/js_emitter/full_emitter/emitter.dart' as full
+ show Emitter;
-import 'package:compiler/src/old_to_new_api.dart' show
- LegacyCompilerDiagnostics;
+import 'package:compiler/src/old_to_new_api.dart'
+ show LegacyCompilerDiagnostics;
void expectOnlyVerboseInfo(Uri uri, int begin, int end, String message, kind) {
if (kind.name == 'verbose info') {
@@ -52,9 +46,9 @@
void main() {
asyncTest(() async {
var result = await runCompiler(
- memorySourceFiles: MEMORY_SOURCE_FILES,
- diagnosticHandler: new LegacyCompilerDiagnostics(expectOnlyVerboseInfo),
- options: ['--enable-experimental-mirrors']);
+ memorySourceFiles: MEMORY_SOURCE_FILES,
+ diagnosticHandler: new LegacyCompilerDiagnostics(expectOnlyVerboseInfo),
+ options: ['--enable-experimental-mirrors']);
CompilerImpl compiler = result.compiler;
print('');
List generatedCode =
@@ -77,25 +71,27 @@
// The following names should be retained:
List expectedNames = [
- 'Foo', // The name of class Foo.
- r'Foo$', // The name of class Foo's constructor.
- r'get$field']; // The (getter) name of Foo.field.
+ 'Foo', // The name of class Foo.
+ r'Foo$', // The name of class Foo's constructor.
+ r'get$field'
+ ]; // The (getter) name of Foo.field.
// TODO(ahe): Check for the following names, currently they are not being
// recorded correctly, but are being emitted.
[
- 'Foo_staticMethod', // The name of Foo.staticMethod.
- r'instanceMethod$0']; // The name of Foo.instanceMethod.
+ 'Foo_staticMethod', // The name of Foo.staticMethod.
+ r'instanceMethod$0'
+ ]; // The name of Foo.instanceMethod.
// We always include the names of some native classes.
List<Element> nativeClasses = [
- compiler.coreClasses.intClass,
- compiler.coreClasses.doubleClass,
- compiler.coreClasses.numClass,
- compiler.coreClasses.stringClass,
- compiler.coreClasses.boolClass,
- compiler.coreClasses.nullClass,
- compiler.coreClasses.listClass
- ];
+ compiler.coreClasses.intClass,
+ compiler.coreClasses.doubleClass,
+ compiler.coreClasses.numClass,
+ compiler.coreClasses.stringClass,
+ compiler.coreClasses.boolClass,
+ compiler.coreClasses.nullClass,
+ compiler.coreClasses.listClass
+ ];
JavaScriptBackend backend = compiler.backend;
Iterable<String> nativeNames = nativeClasses.map(backend.namer.className);
expectedNames = expectedNames.map(backend.namer.asName).toList();
@@ -105,9 +101,9 @@
// emitter is the full emitter.
full.Emitter fullEmitter = backend.emitter.emitter;
Set recordedNames = new Set()
- ..addAll(fullEmitter.recordedMangledNames)
- ..addAll(fullEmitter.mangledFieldNames.keys)
- ..addAll(fullEmitter.mangledGlobalFieldNames.keys);
+ ..addAll(fullEmitter.recordedMangledNames)
+ ..addAll(fullEmitter.mangledFieldNames.keys)
+ ..addAll(fullEmitter.mangledGlobalFieldNames.keys);
Expect.setEquals(new Set.from(expectedNames), recordedNames);
for (var library in compiler.libraryLoader.libraries) {
@@ -131,12 +127,12 @@
Set<ConstantValue> compiledConstants = backend.constants.compiledConstants;
// Make sure that most of the metadata constants aren't included in the
// generated code.
- backend.processMetadata(
- compiler.enqueuer.resolution.processedElements, (metadata) {
+ backend.processMetadata(compiler.enqueuer.resolution.processedElements,
+ (metadata) {
ConstantValue constant =
backend.constants.getConstantValueForMetadata(metadata);
- Expect.isFalse(compiledConstants.contains(constant),
- constant.toStructuredText());
+ Expect.isFalse(
+ compiledConstants.contains(constant), constant.toStructuredText());
metadataCount++;
});
@@ -153,13 +149,12 @@
fooConstantCount++;
}
}
- Expect.equals(
- 1, fooConstantCount,
+ Expect.equals(1, fooConstantCount,
"The type literal 'Foo' is duplicated or missing.");
});
}
-const MEMORY_SOURCE_FILES = const <String, String> {
+const MEMORY_SOURCE_FILES = const <String, String>{
'main.dart': """
// The repeated constant value for symbols and targets used to crash dart2js in
// host-checked mode, and could potentially lead to other problems.
diff --git a/tests/compiler/dart2js/missing_file_test.dart b/tests/compiler/dart2js/missing_file_test.dart
index 457a4f0..96ccf03 100644
--- a/tests/compiler/dart2js/missing_file_test.dart
+++ b/tests/compiler/dart2js/missing_file_test.dart
@@ -17,21 +17,17 @@
import 'foo.dart';
main() {}
''',
-
-'bar.dart': '''
+ 'bar.dart': '''
import 'dart:foo';
main() {}
''',
-
-'baz.dart': '''
+ 'baz.dart': '''
import 'dart:io';
main() {}
''',
};
-Future runTest(Uri main,
- {MessageKind error,
- MessageKind info}) async {
+Future runTest(Uri main, {MessageKind error, MessageKind info}) async {
print("----\nentry-point: $main\n");
DiagnosticCollector diagnostics = new DiagnosticCollector();
@@ -57,29 +53,22 @@
void main() {
asyncTest(() async {
- await runTest(
- Uri.parse('memory:main.dart'),
+ await runTest(Uri.parse('memory:main.dart'),
error: MessageKind.READ_SCRIPT_ERROR);
- await runTest(
- Uri.parse('memory:foo.dart'),
+ await runTest(Uri.parse('memory:foo.dart'),
error: MessageKind.READ_SELF_ERROR);
- await runTest(
- Uri.parse('dart:foo'),
- error: MessageKind.LIBRARY_NOT_FOUND);
+ await runTest(Uri.parse('dart:foo'), error: MessageKind.LIBRARY_NOT_FOUND);
- await runTest(
- Uri.parse('dart:io'),
+ await runTest(Uri.parse('dart:io'),
error: MessageKind.LIBRARY_NOT_SUPPORTED,
info: MessageKind.DISALLOWED_LIBRARY_IMPORT);
- await runTest(
- Uri.parse('memory:bar.dart'),
+ await runTest(Uri.parse('memory:bar.dart'),
error: MessageKind.LIBRARY_NOT_FOUND);
- await runTest(
- Uri.parse('memory:baz.dart'),
+ await runTest(Uri.parse('memory:baz.dart'),
error: MessageKind.LIBRARY_NOT_SUPPORTED,
info: MessageKind.DISALLOWED_LIBRARY_IMPORT);
});
diff --git a/tests/compiler/dart2js/mixin_constructor_default_parameter_values_test.dart b/tests/compiler/dart2js/mixin_constructor_default_parameter_values_test.dart
index a3924a8..4ff2338 100644
--- a/tests/compiler/dart2js/mixin_constructor_default_parameter_values_test.dart
+++ b/tests/compiler/dart2js/mixin_constructor_default_parameter_values_test.dart
@@ -43,4 +43,3 @@
main() {
asyncTest(() => runCompiler(memorySourceFiles: MEMORY_SOURCE_FILES));
}
-
diff --git a/tests/compiler/dart2js/mixin_language_test.dart b/tests/compiler/dart2js/mixin_language_test.dart
index 11f708b..97299f6 100644
--- a/tests/compiler/dart2js/mixin_language_test.dart
+++ b/tests/compiler/dart2js/mixin_language_test.dart
@@ -13,7 +13,7 @@
/// can contain a list of line numbers for keys 'missing' and 'unexpected' for
/// the warnings of each category.
const Map<String, dynamic> TESTS = const {
- 'language/typevariable_substitution2_test.dart': null,
+ 'language/typevariable_substitution2_test.dart': null,
};
void main(List<String> arguments) {
diff --git a/tests/compiler/dart2js/mixin_typevariable_test.dart b/tests/compiler/dart2js/mixin_typevariable_test.dart
index 27fe4bb..c57a6bb 100644
--- a/tests/compiler/dart2js/mixin_typevariable_test.dart
+++ b/tests/compiler/dart2js/mixin_typevariable_test.dart
@@ -8,8 +8,7 @@
import "package:async_helper/async_helper.dart";
import 'type_test_helper.dart';
import 'package:compiler/src/dart_types.dart';
-import "package:compiler/src/elements/elements.dart"
- show Element, ClassElement;
+import "package:compiler/src/elements/elements.dart" show Element, ClassElement;
void main() {
testMixinSupertypes();
@@ -17,7 +16,9 @@
}
void testMixinSupertypes() {
- asyncTest(() => TypeEnvironment.create(r"""
+ asyncTest(() => TypeEnvironment
+ .create(
+ r"""
class S<S_T> {}
class M1<M1_T> {}
class M2<M2_T> {}
@@ -25,55 +26,58 @@
class C1<C1_T> extends S<C1_T> with M1<C1_T>, M2<C1_T>, M3<C1_T> {}
class C2<C2_T> = S<C2_T> with M1<C2_T>, M2<C2_T>, M3<C2_T>;
- """, expectNoWarningsOrErrors: true).then((env) {
+ """,
+ expectNoWarningsOrErrors: true)
+ .then((env) {
+ ClassElement Object = env.getElement('Object');
+ ClassElement S = env.getElement('S');
+ ClassElement M1 = env.getElement('M1');
+ ClassElement M2 = env.getElement('M2');
+ ClassElement M3 = env.getElement('M3');
+ ClassElement C1 = env.getElement('C1');
+ ClassElement C2 = env.getElement('C2');
- ClassElement Object = env.getElement('Object');
- ClassElement S = env.getElement('S');
- ClassElement M1 = env.getElement('M1');
- ClassElement M2 = env.getElement('M2');
- ClassElement M3 = env.getElement('M3');
- ClassElement C1 = env.getElement('C1');
- ClassElement C2 = env.getElement('C2');
+ ClassElement C1_S_M1_M2_M3 = C1.superclass;
+ ClassElement C1_S_M1_M2 = C1_S_M1_M2_M3.superclass;
+ ClassElement C1_S_M1 = C1_S_M1_M2.superclass;
- ClassElement C1_S_M1_M2_M3 = C1.superclass;
- ClassElement C1_S_M1_M2 = C1_S_M1_M2_M3.superclass;
- ClassElement C1_S_M1 = C1_S_M1_M2.superclass;
+ ClassElement C2_S_M1_M2 = C2.superclass;
+ ClassElement C2_S_M1 = C2_S_M1_M2.superclass;
- ClassElement C2_S_M1_M2 = C2.superclass;
- ClassElement C2_S_M1 = C2_S_M1_M2.superclass;
-
- void testSupertypes(ClassElement element) {
- if (element != Object) {
- Expect.isTrue(element.typeVariables.length == 1);
- Expect.equals(element,
- element.typeVariables.first.element.enclosingElement);
- }
- for (InterfaceType supertype in element.allSupertypesAndSelf.types) {
- if (!supertype.typeArguments.isEmpty) {
- Expect.listEquals(element.typeVariables, supertype.typeArguments,
- "Type argument mismatch on supertype $supertype of $element.");
- } else {
- Expect.equals(Object, supertype.element);
+ void testSupertypes(ClassElement element) {
+ if (element != Object) {
+ Expect.isTrue(element.typeVariables.length == 1);
+ Expect.equals(
+ element, element.typeVariables.first.element.enclosingElement);
+ }
+ for (InterfaceType supertype in element.allSupertypesAndSelf.types) {
+ if (!supertype.typeArguments.isEmpty) {
+ Expect.listEquals(element.typeVariables, supertype.typeArguments,
+ "Type argument mismatch on supertype $supertype of $element.");
+ } else {
+ Expect.equals(Object, supertype.element);
+ }
+ }
}
- }
- }
- testSupertypes(Object);
- testSupertypes(S);
- testSupertypes(M1);
- testSupertypes(M2);
- testSupertypes(C1_S_M1);
- testSupertypes(C1_S_M1_M2);
- testSupertypes(C1_S_M1_M2_M3);
- testSupertypes(C1);
- testSupertypes(C2_S_M1);
- testSupertypes(C2_S_M1_M2);
- testSupertypes(C2);
- }));
+ testSupertypes(Object);
+ testSupertypes(S);
+ testSupertypes(M1);
+ testSupertypes(M2);
+ testSupertypes(C1_S_M1);
+ testSupertypes(C1_S_M1_M2);
+ testSupertypes(C1_S_M1_M2_M3);
+ testSupertypes(C1);
+ testSupertypes(C2_S_M1);
+ testSupertypes(C2_S_M1_M2);
+ testSupertypes(C2);
+ }));
}
void testNonTrivialSubstitutions() {
- asyncTest(() => TypeEnvironment.create(r"""
+ asyncTest(() => TypeEnvironment
+ .create(
+ r"""
class _ {}
class A<A_T> {}
class B<B_T, B_S> {}
@@ -89,70 +93,134 @@
class F1<F1_T> extends A<_> with B<_, B<F1_T, _>> {}
class F2<F2_T> = A<_> with B<_, B<F2_T, _>>;
- """, expectNoWarningsOrErrors: true).then((env) {
- DartType _dynamic = env['dynamic'];
- DartType _ = env['_'];
+ """,
+ expectNoWarningsOrErrors: true)
+ .then((env) {
+ DartType _dynamic = env['dynamic'];
+ DartType _ = env['_'];
- ClassElement Object = env.getElement('Object');
- ClassElement A = env.getElement('A');
- ClassElement B = env.getElement('B');
- ClassElement C1 = env.getElement('C1');
- ClassElement C2 = env.getElement('C2');
- ClassElement D1 = env.getElement('D1');
- ClassElement D2 = env.getElement('D2');
- ClassElement E1 = env.getElement('E1');
- ClassElement E2 = env.getElement('E2');
- ClassElement F1 = env.getElement('F1');
- ClassElement F2 = env.getElement('F2');
+ ClassElement Object = env.getElement('Object');
+ ClassElement A = env.getElement('A');
+ ClassElement B = env.getElement('B');
+ ClassElement C1 = env.getElement('C1');
+ ClassElement C2 = env.getElement('C2');
+ ClassElement D1 = env.getElement('D1');
+ ClassElement D2 = env.getElement('D2');
+ ClassElement E1 = env.getElement('E1');
+ ClassElement E2 = env.getElement('E2');
+ ClassElement F1 = env.getElement('F1');
+ ClassElement F2 = env.getElement('F2');
- ClassElement C1_A_B = C1.superclass;
- ClassElement D1_A_B = D1.superclass;
- ClassElement E1_A_B = E1.superclass;
- ClassElement F1_A_B = F1.superclass;
+ ClassElement C1_A_B = C1.superclass;
+ ClassElement D1_A_B = D1.superclass;
+ ClassElement E1_A_B = E1.superclass;
+ ClassElement F1_A_B = F1.superclass;
- void testSupertypes(ClassElement element,
- Map<ClassElement, List<DartType>> typeArguments) {
- if (element != Object) {
- Expect.isTrue(element.typeVariables.length == 1);
- Expect.equals(element,
- element.typeVariables.first.element.enclosingElement);
- }
- for (InterfaceType supertype in element.allSupertypesAndSelf.types) {
- if (typeArguments.containsKey(supertype.element)) {
- Expect.listEquals(typeArguments[supertype.element],
- supertype.typeArguments,
- "Type argument mismatch on supertype $supertype of $element.");
- } else if (!supertype.typeArguments.isEmpty) {
- Expect.listEquals(element.typeVariables, supertype.typeArguments,
- "Type argument mismatch on supertype $supertype of $element.");
- } else {
- Expect.equals(Object, supertype.element);
+ void testSupertypes(ClassElement element,
+ Map<ClassElement, List<DartType>> typeArguments) {
+ if (element != Object) {
+ Expect.isTrue(element.typeVariables.length == 1);
+ Expect.equals(
+ element, element.typeVariables.first.element.enclosingElement);
+ }
+ for (InterfaceType supertype in element.allSupertypesAndSelf.types) {
+ if (typeArguments.containsKey(supertype.element)) {
+ Expect.listEquals(
+ typeArguments[supertype.element],
+ supertype.typeArguments,
+ "Type argument mismatch on supertype $supertype of $element.");
+ } else if (!supertype.typeArguments.isEmpty) {
+ Expect.listEquals(element.typeVariables, supertype.typeArguments,
+ "Type argument mismatch on supertype $supertype of $element.");
+ } else {
+ Expect.equals(Object, supertype.element);
+ }
+ }
}
- }
- }
- testSupertypes(C1, {A: [_dynamic], B: [_dynamic, _dynamic]});
- testSupertypes(C1.superclass, {A: [_dynamic], B: [_dynamic, _dynamic]});
- testSupertypes(C2, {A: [_dynamic], B: [_dynamic, _dynamic]});
+ testSupertypes(C1, {
+ A: [_dynamic],
+ B: [_dynamic, _dynamic]
+ });
+ testSupertypes(C1.superclass, {
+ A: [_dynamic],
+ B: [_dynamic, _dynamic]
+ });
+ testSupertypes(C2, {
+ A: [_dynamic],
+ B: [_dynamic, _dynamic]
+ });
- DartType D1_T = D1.typeVariables.first;
- testSupertypes(D1, {A: [D1_T], B: [D1_T, instantiate(A, [D1_T])]});
- DartType D1_superclass_T = D1.superclass.typeVariables.first;
- testSupertypes(D1.superclass,
- {A: [D1_superclass_T],
- B: [D1_superclass_T, instantiate(A, [D1_superclass_T])]});
- DartType D2_T = D2.typeVariables.first;
- testSupertypes(D2, {A: [D2_T], B: [D2_T, instantiate(A, [D2_T])]});
+ DartType D1_T = D1.typeVariables.first;
+ testSupertypes(D1, {
+ A: [D1_T],
+ B: [
+ D1_T,
+ instantiate(A, [D1_T])
+ ]
+ });
+ DartType D1_superclass_T = D1.superclass.typeVariables.first;
+ testSupertypes(D1.superclass, {
+ A: [D1_superclass_T],
+ B: [
+ D1_superclass_T,
+ instantiate(A, [D1_superclass_T])
+ ]
+ });
+ DartType D2_T = D2.typeVariables.first;
+ testSupertypes(D2, {
+ A: [D2_T],
+ B: [
+ D2_T,
+ instantiate(A, [D2_T])
+ ]
+ });
- testSupertypes(E1, {A: [_], B: [_, instantiate(A, [_])]});
- testSupertypes(E1.superclass, {A: [_], B: [_, instantiate(A, [_])]});
- testSupertypes(E2, {A: [_], B: [_, instantiate(A, [_])]});
+ testSupertypes(E1, {
+ A: [_],
+ B: [
+ _,
+ instantiate(A, [_])
+ ]
+ });
+ testSupertypes(E1.superclass, {
+ A: [_],
+ B: [
+ _,
+ instantiate(A, [_])
+ ]
+ });
+ testSupertypes(E2, {
+ A: [_],
+ B: [
+ _,
+ instantiate(A, [_])
+ ]
+ });
- DartType F1_T = F1.typeVariables.first;
- testSupertypes(F1, {A: [_], B: [_, instantiate(B, [F1_T, _])]});
- DartType F1_superclass_T = F1.superclass.typeVariables.first;
- testSupertypes(F1.superclass, {A: [_], B: [_, instantiate(B, [F1_superclass_T, _])]});
- DartType F2_T = F2.typeVariables.first;
- testSupertypes(F2, {A: [_], B: [_, instantiate(B, [F2_T, _])]});
- }));
+ DartType F1_T = F1.typeVariables.first;
+ testSupertypes(F1, {
+ A: [_],
+ B: [
+ _,
+ instantiate(B, [F1_T, _])
+ ]
+ });
+ DartType F1_superclass_T = F1.superclass.typeVariables.first;
+ testSupertypes(F1.superclass, {
+ A: [_],
+ B: [
+ _,
+ instantiate(B, [F1_superclass_T, _])
+ ]
+ });
+ DartType F2_T = F2.typeVariables.first;
+ testSupertypes(F2, {
+ A: [_],
+ B: [
+ _,
+ instantiate(B, [F2_T, _])
+ ]
+ });
+ }));
}
diff --git a/tests/compiler/dart2js/mock_compiler.dart b/tests/compiler/dart2js/mock_compiler.dart
index 5d83c5d..7469f0c 100644
--- a/tests/compiler/dart2js/mock_compiler.dart
+++ b/tests/compiler/dart2js/mock_compiler.dart
@@ -8,8 +8,7 @@
import 'dart:collection';
import 'package:compiler/compiler.dart' as api;
-import 'package:compiler/src/common/names.dart' show
- Uris;
+import 'package:compiler/src/common/names.dart' show Uris;
import 'package:compiler/src/constants/expressions.dart';
import 'package:compiler/src/dart_types.dart' show DartType;
import 'package:compiler/src/diagnostics/diagnostic_listener.dart';
@@ -17,13 +16,12 @@
import 'package:compiler/src/diagnostics/spannable.dart';
import 'package:compiler/src/elements/elements.dart';
import 'package:compiler/src/elements/visitor.dart';
-import 'package:compiler/src/js_backend/backend_helpers.dart' show
- BackendHelpers;
-import 'package:compiler/src/js_backend/lookup_map_analysis.dart' show
- LookupMapAnalysis;
+import 'package:compiler/src/js_backend/backend_helpers.dart'
+ show BackendHelpers;
+import 'package:compiler/src/js_backend/lookup_map_analysis.dart'
+ show LookupMapAnalysis;
import 'package:compiler/src/io/source_file.dart';
-import 'package:compiler/src/options.dart' show
- CompilerOptions;
+import 'package:compiler/src/options.dart' show CompilerOptions;
import 'package:compiler/src/resolution/members.dart';
import 'package:compiler/src/resolution/registry.dart';
import 'package:compiler/src/resolution/scope.dart';
@@ -34,18 +32,14 @@
import 'package:compiler/src/old_to_new_api.dart';
import 'parser_helper.dart';
-import 'package:compiler/src/elements/modelx.dart' show
- ElementX,
- LibraryElementX,
- ErroneousElementX,
- FunctionElementX;
+import 'package:compiler/src/elements/modelx.dart'
+ show ElementX, LibraryElementX, ErroneousElementX, FunctionElementX;
import 'package:compiler/src/compiler.dart';
import 'package:compiler/src/common/tasks.dart' show Measurer;
-import 'package:compiler/src/deferred_load.dart' show
- DeferredLoadTask,
- OutputUnit;
+import 'package:compiler/src/deferred_load.dart'
+ show DeferredLoadTask, OutputUnit;
import 'mock_libraries.dart';
import 'diagnostic_helper.dart';
@@ -58,9 +52,11 @@
class MockCompiler extends Compiler {
api.DiagnosticHandler diagnosticHandler;
+
/// Expected number of warnings. If `null`, the number of warnings is
/// not checked.
final int expectedWarnings;
+
/// Expected number of errors. If `null`, the number of errors is not checked.
final int expectedErrors;
final Map<String, SourceFile> sourceFiles;
@@ -74,70 +70,68 @@
MockCompiler.internal(
{Map<String, String> coreSource,
- bool enableTypeAssertions: false,
- bool enableUserAssertions: false,
- bool enableMinification: false,
- bool disableTypeInference: false,
- bool analyzeAll: false,
- bool analyzeOnly: false,
- bool preserveComments: false,
- // Our unit tests check code generation output that is
- // affected by inlining support.
- bool disableInlining: true,
- bool trustTypeAnnotations: false,
- bool trustJSInteropTypeAnnotations: false,
- bool enableAsyncAwait: false,
- int this.expectedWarnings,
- int this.expectedErrors,
- api.CompilerOutputProvider outputProvider,
- String patchVersion,
- LibrarySourceProvider this.librariesOverride})
+ bool enableTypeAssertions: false,
+ bool enableUserAssertions: false,
+ bool enableMinification: false,
+ bool disableTypeInference: false,
+ bool analyzeAll: false,
+ bool analyzeOnly: false,
+ bool preserveComments: false,
+ // Our unit tests check code generation output that is
+ // affected by inlining support.
+ bool disableInlining: true,
+ bool trustTypeAnnotations: false,
+ bool trustJSInteropTypeAnnotations: false,
+ bool enableAsyncAwait: false,
+ int this.expectedWarnings,
+ int this.expectedErrors,
+ api.CompilerOutputProvider outputProvider,
+ String patchVersion,
+ LibrarySourceProvider this.librariesOverride})
: sourceFiles = new Map<String, SourceFile>(),
testedPatchVersion = patchVersion,
- super(options: new CompilerOptions(
- entryPoint: new Uri(scheme: 'mock'),
- libraryRoot: Uri.parse('placeholder_library_root_for_mock/'),
- enableTypeAssertions: enableTypeAssertions,
- enableUserAssertions: enableUserAssertions,
- disableInlining: disableInlining,
- enableAssertMessage: true,
- enableMinification: enableMinification,
- disableTypeInference: disableTypeInference,
- analyzeAll: analyzeAll,
- analyzeOnly: analyzeOnly,
- preserveComments: preserveComments,
- trustTypeAnnotations: trustTypeAnnotations,
- trustJSInteropTypeAnnotations: trustJSInteropTypeAnnotations,
- shownPackageWarnings: const []),
- outputProvider: new LegacyCompilerOutput(outputProvider)) {
-
+ super(
+ options: new CompilerOptions(
+ entryPoint: new Uri(scheme: 'mock'),
+ libraryRoot: Uri.parse('placeholder_library_root_for_mock/'),
+ enableTypeAssertions: enableTypeAssertions,
+ enableUserAssertions: enableUserAssertions,
+ disableInlining: disableInlining,
+ enableAssertMessage: true,
+ enableMinification: enableMinification,
+ disableTypeInference: disableTypeInference,
+ analyzeAll: analyzeAll,
+ analyzeOnly: analyzeOnly,
+ preserveComments: preserveComments,
+ trustTypeAnnotations: trustTypeAnnotations,
+ trustJSInteropTypeAnnotations: trustJSInteropTypeAnnotations,
+ shownPackageWarnings: const []),
+ outputProvider: new LegacyCompilerOutput(outputProvider)) {
deferredLoadTask = new MockDeferredLoadTask(this);
- registerSource(Uris.dart_core,
- buildLibrarySource(DEFAULT_CORE_LIBRARY, coreSource));
+ registerSource(
+ Uris.dart_core, buildLibrarySource(DEFAULT_CORE_LIBRARY, coreSource));
registerSource(PATCH_CORE, DEFAULT_PATCH_CORE_SOURCE);
registerSource(BackendHelpers.DART_JS_HELPER,
- buildLibrarySource(DEFAULT_JS_HELPER_LIBRARY));
+ buildLibrarySource(DEFAULT_JS_HELPER_LIBRARY));
registerSource(BackendHelpers.DART_FOREIGN_HELPER,
- buildLibrarySource(DEFAULT_FOREIGN_HELPER_LIBRARY));
+ buildLibrarySource(DEFAULT_FOREIGN_HELPER_LIBRARY));
registerSource(BackendHelpers.DART_INTERCEPTORS,
- buildLibrarySource(DEFAULT_INTERCEPTORS_LIBRARY));
+ buildLibrarySource(DEFAULT_INTERCEPTORS_LIBRARY));
registerSource(BackendHelpers.DART_ISOLATE_HELPER,
- buildLibrarySource(DEFAULT_ISOLATE_HELPER_LIBRARY));
+ buildLibrarySource(DEFAULT_ISOLATE_HELPER_LIBRARY));
registerSource(Uris.dart_mirrors, DEFAULT_MIRRORS_SOURCE);
- registerSource(BackendHelpers.DART_JS_MIRRORS,
- DEFAULT_JS_MIRRORS_SOURCE);
+ registerSource(BackendHelpers.DART_JS_MIRRORS, DEFAULT_JS_MIRRORS_SOURCE);
Map<String, String> asyncLibrarySource = <String, String>{};
asyncLibrarySource.addAll(DEFAULT_ASYNC_LIBRARY);
if (enableAsyncAwait) {
asyncLibrarySource.addAll(ASYNC_AWAIT_LIBRARY);
}
- registerSource(Uris.dart_async,
- buildLibrarySource(asyncLibrarySource));
+ registerSource(Uris.dart_async, buildLibrarySource(asyncLibrarySource));
registerSource(LookupMapAnalysis.PACKAGE_LOOKUP_MAP,
- buildLibrarySource(DEFAULT_LOOKUP_MAP_LIBRARY));
+ buildLibrarySource(DEFAULT_LOOKUP_MAP_LIBRARY));
}
String get patchVersion {
@@ -148,8 +142,7 @@
Future<Uri> init([String mainSource = ""]) {
Uri uri = new Uri(scheme: "mock");
registerSource(uri, mainSource);
- return libraryLoader.loadLibrary(uri)
- .then((LibraryElement library) {
+ return libraryLoader.loadLibrary(uri).then((LibraryElement library) {
mainApp = library;
// We need to make sure the Object class is resolved. When registering a
// dynamic invocation the ArgumentTypesRegistry eventually iterates over
@@ -166,11 +159,11 @@
if (expectedErrors != null &&
expectedErrors != diagnosticCollector.errors.length) {
throw "unexpected error during compilation "
- "${diagnosticCollector.errors}";
+ "${diagnosticCollector.errors}";
} else if (expectedWarnings != null &&
- expectedWarnings != diagnosticCollector.warnings.length) {
+ expectedWarnings != diagnosticCollector.warnings.length) {
throw "unexpected warnings during compilation "
- "${diagnosticCollector.warnings}";
+ "${diagnosticCollector.warnings}";
} else {
return result;
}
@@ -193,9 +186,7 @@
}
void reportDiagnostic(DiagnosticMessage message,
- List<DiagnosticMessage> infoMessages,
- api.Diagnostic kind) {
-
+ List<DiagnosticMessage> infoMessages, api.Diagnostic kind) {
void processMessage(DiagnosticMessage message, api.Diagnostic kind) {
SourceSpan span = message.sourceSpan;
Uri uri;
@@ -222,16 +213,15 @@
return resolveNodeStatement(parsedTree, new MockElement(mainApp));
}
- TreeElementMapping resolveNodeStatement(Node tree,
- ExecutableElement element) {
- ResolverVisitor visitor =
- new ResolverVisitor(
- this.resolution,
- element,
- new ResolutionRegistry(this.backend,
- new CollectingTreeElements(element)),
- scope: new MockTypeVariablesScope(
- element.enclosingElement.buildScope()));
+ TreeElementMapping resolveNodeStatement(
+ Node tree, ExecutableElement element) {
+ ResolverVisitor visitor = new ResolverVisitor(
+ this.resolution,
+ element,
+ new ResolutionRegistry(
+ this.backend, new CollectingTreeElements(element)),
+ scope:
+ new MockTypeVariablesScope(element.enclosingElement.buildScope()));
if (visitor.scope is LibraryScope ||
visitor.scope is MockTypeVariablesScope) {
visitor.scope = new MethodScope(visitor.scope, element);
@@ -243,13 +233,12 @@
resolverVisitor() {
Element mockElement = new MockElement(mainApp.entryCompilationUnit);
- ResolverVisitor visitor =
- new ResolverVisitor(
- this.resolution,
- mockElement,
- new ResolutionRegistry(
- this.backend, new CollectingTreeElements(mockElement)),
- scope: mockElement.enclosingElement.buildScope());
+ ResolverVisitor visitor = new ResolverVisitor(
+ this.resolution,
+ mockElement,
+ new ResolutionRegistry(
+ this.backend, new CollectingTreeElements(mockElement)),
+ scope: mockElement.enclosingElement.buildScope());
visitor.scope = new MethodScope(visitor.scope, mockElement);
return visitor;
}
@@ -347,7 +336,7 @@
}
api.DiagnosticHandler createHandler(MockCompiler compiler, String text,
- {bool verbose: false}) {
+ {bool verbose: false}) {
return (uri, int begin, int end, String message, kind) {
if (kind == api.Diagnostic.VERBOSE_INFO && !verbose) return;
SourceFile sourceFile;
@@ -366,8 +355,7 @@
class MockElement extends FunctionElementX {
MockElement(Element enclosingElement)
- : super('', ElementKind.FUNCTION, Modifiers.EMPTY,
- enclosingElement);
+ : super('', ElementKind.FUNCTION, Modifiers.EMPTY, enclosingElement);
get node => null;
@@ -382,17 +370,17 @@
// TODO(herhut): Disallow warnings and errors during compilation by default.
MockCompiler compilerFor(String code, Uri uri,
- {bool analyzeAll: false,
- bool analyzeOnly: false,
- Map<String, String> coreSource,
- bool disableInlining: true,
- bool minify: false,
- bool trustTypeAnnotations: false,
- bool enableTypeAssertions: false,
- bool enableUserAssertions: false,
- int expectedErrors,
- int expectedWarnings,
- api.CompilerOutputProvider outputProvider}) {
+ {bool analyzeAll: false,
+ bool analyzeOnly: false,
+ Map<String, String> coreSource,
+ bool disableInlining: true,
+ bool minify: false,
+ bool trustTypeAnnotations: false,
+ bool enableTypeAssertions: false,
+ bool enableUserAssertions: false,
+ int expectedErrors,
+ int expectedWarnings,
+ api.CompilerOutputProvider outputProvider}) {
MockCompiler compiler = new MockCompiler.internal(
analyzeAll: analyzeAll,
analyzeOnly: analyzeOnly,
diff --git a/tests/compiler/dart2js/mock_libraries.dart b/tests/compiler/dart2js/mock_libraries.dart
index 3e64f10..4ceb375 100644
--- a/tests/compiler/dart2js/mock_libraries.dart
+++ b/tests/compiler/dart2js/mock_libraries.dart
@@ -15,8 +15,7 @@
_isolate_helper:_internal/js_runtime/lib/isolate_helper.dart
""";
-String buildLibrarySource(
- Map<String, String> elementMap,
+String buildLibrarySource(Map<String, String> elementMap,
[Map<String, String> additionalElementMap = const <String, String>{}]) {
Map<String, String> map = new Map<String, String>.from(elementMap);
if (additionalElementMap != null) {
@@ -37,7 +36,7 @@
DateTime(year);
DateTime.utc(year);
}''',
- 'Deprecated': r'''
+ 'Deprecated': r'''
class Deprecated extends Object {
final String expires;
const Deprecated(this.expires);
@@ -138,8 +137,7 @@
var target;
var receiver;
}''',
- 'buildFunctionType':
- r'''buildFunctionType(returnType, parameterTypes,
+ 'buildFunctionType': r'''buildFunctionType(returnType, parameterTypes,
optionalParameterTypes) {
return new RuntimeFunctionType();
}''',
@@ -264,13 +262,12 @@
'wrapException': 'wrapException(x) { return x; }',
'badMain': 'badMain() { throw "bad main"; }',
'missingMain': 'missingMain() { throw "missing main"; }',
- 'mainHasTooManyParameters':
- 'mainHasTooManyParameters() '
+ 'mainHasTooManyParameters': 'mainHasTooManyParameters() '
'{ throw "main has too many parameters"; }',
};
-const Map<String, String> DEFAULT_FOREIGN_HELPER_LIBRARY
- = const <String, String>{
+const Map<String, String> DEFAULT_FOREIGN_HELPER_LIBRARY =
+ const <String, String>{
'JS': r'''
dynamic JS(String typeDescription, String codeTemplate,
[var arg0, var arg1, var arg2, var arg3, var arg4, var arg5, var arg6,
@@ -278,8 +275,7 @@
};
const Map<String, String> DEFAULT_INTERCEPTORS_LIBRARY = const <String, String>{
- 'findIndexForNativeSubclassType':
- 'findIndexForNativeSubclassType(type) {}',
+ 'findIndexForNativeSubclassType': 'findIndexForNativeSubclassType(type) {}',
'getDispatchProperty': 'getDispatchProperty(o) {}',
'getInterceptor': 'getInterceptor(x) {}',
'getNativeInterceptor': 'getNativeInterceptor(x) {}',
@@ -327,11 +323,10 @@
}''',
'JSMutableArray':
'class JSMutableArray extends JSArray implements JSMutableIndexable {}',
- 'JSUnmodifiableArray':
- 'class JSUnmodifiableArray extends JSArray {}',
+ 'JSUnmodifiableArray': 'class JSUnmodifiableArray extends JSArray {}',
'JSMutableIndexable':
'abstract class JSMutableIndexable extends JSIndexable {}',
- 'JSPositiveInt': 'class JSPositiveInt extends JSInt {}',
+ 'JSPositiveInt': 'class JSPositiveInt extends JSInt {}',
'JSNull': r'''
class JSNull extends Interceptor {
bool operator==(other) => identical(null, other);
@@ -409,8 +404,7 @@
const Map<String, String> DEFAULT_ASYNC_LIBRARY = const <String, String>{
'DeferredLibrary': 'class DeferredLibrary {}',
- 'Future':
- '''
+ 'Future': '''
class Future<T> {
Future.value([value]);
}
diff --git a/tests/compiler/dart2js/no_constructor_body_test.dart b/tests/compiler/dart2js/no_constructor_body_test.dart
index b059f32..495f2d9 100644
--- a/tests/compiler/dart2js/no_constructor_body_test.dart
+++ b/tests/compiler/dart2js/no_constructor_body_test.dart
@@ -19,7 +19,7 @@
main() {
asyncTest(() => compileAll(TEST).then((generated) {
- Expect.isTrue(generated.contains(
- new RegExp('A: {[ \n]*"\\^": "Object;",[ \n]*static:')));
- }));
+ Expect.isTrue(generated
+ .contains(new RegExp('A: {[ \n]*"\\^": "Object;",[ \n]*static:')));
+ }));
}
diff --git a/tests/compiler/dart2js/no_duplicate_constructor_body2_test.dart b/tests/compiler/dart2js/no_duplicate_constructor_body2_test.dart
index a306a0c..ab1aa74 100644
--- a/tests/compiler/dart2js/no_duplicate_constructor_body2_test.dart
+++ b/tests/compiler/dart2js/no_duplicate_constructor_body2_test.dart
@@ -23,8 +23,8 @@
main() {
asyncTest(() => compileAll(CODE).then((generated) {
- RegExp regexp = new RegExp(r'A\$0: function');
- Iterator<Match> matches = regexp.allMatches(generated).iterator;
- checkNumberOfMatches(matches, 1);
- }));
+ RegExp regexp = new RegExp(r'A\$0: function');
+ Iterator<Match> matches = regexp.allMatches(generated).iterator;
+ checkNumberOfMatches(matches, 1);
+ }));
}
diff --git a/tests/compiler/dart2js/no_duplicate_constructor_body_test.dart b/tests/compiler/dart2js/no_duplicate_constructor_body_test.dart
index 3005ddf..54815d2 100644
--- a/tests/compiler/dart2js/no_duplicate_constructor_body_test.dart
+++ b/tests/compiler/dart2js/no_duplicate_constructor_body_test.dart
@@ -17,8 +17,8 @@
main() {
asyncTest(() => compileAll(CODE).then((generated) {
- RegExp regexp = new RegExp(r'\A: {[ \n]*"\^": "[A-za-z]+;"');
- Iterator<Match> matches = regexp.allMatches(generated).iterator;
- checkNumberOfMatches(matches, 1);
- }));
+ RegExp regexp = new RegExp(r'\A: {[ \n]*"\^": "[A-za-z]+;"');
+ Iterator<Match> matches = regexp.allMatches(generated).iterator;
+ checkNumberOfMatches(matches, 1);
+ }));
}
diff --git a/tests/compiler/dart2js/no_duplicate_stub_test.dart b/tests/compiler/dart2js/no_duplicate_stub_test.dart
index 8ace11b..5327507 100644
--- a/tests/compiler/dart2js/no_duplicate_stub_test.dart
+++ b/tests/compiler/dart2js/no_duplicate_stub_test.dart
@@ -30,8 +30,8 @@
main() {
asyncTest(() => compileAll(TEST).then((generated) {
- RegExp regexp = new RegExp('foo\\\$1\\\$a: function');
- Iterator<Match> matches = regexp.allMatches(generated).iterator;
- checkNumberOfMatches(matches, 1);
- }));
+ RegExp regexp = new RegExp('foo\\\$1\\\$a: function');
+ Iterator<Match> matches = regexp.allMatches(generated).iterator;
+ checkNumberOfMatches(matches, 1);
+ }));
}
diff --git a/tests/compiler/dart2js/no_such_method_enabled_test.dart b/tests/compiler/dart2js/no_such_method_enabled_test.dart
index c9e651a..a000924 100644
--- a/tests/compiler/dart2js/no_such_method_enabled_test.dart
+++ b/tests/compiler/dart2js/no_such_method_enabled_test.dart
@@ -22,9 +22,8 @@
await compiler.run(uri);
Expect.isFalse(compiler.backend.enabledNoSuchMethod);
ClassElement clsA = findElement(compiler, 'A');
- Expect.isTrue(
- compiler.backend.noSuchMethodRegistry.defaultImpls.contains(
- clsA.lookupMember('noSuchMethod')));
+ Expect.isTrue(compiler.backend.noSuchMethodRegistry.defaultImpls
+ .contains(clsA.lookupMember('noSuchMethod')));
}
Future dummyImplTest2() async {
@@ -43,9 +42,8 @@
await compiler.run(uri);
Expect.isFalse(compiler.backend.enabledNoSuchMethod);
ClassElement clsA = findElement(compiler, 'A');
- Expect.isTrue(
- compiler.backend.noSuchMethodRegistry.defaultImpls.contains(
- clsA.lookupMember('noSuchMethod')));
+ Expect.isTrue(compiler.backend.noSuchMethodRegistry.defaultImpls
+ .contains(clsA.lookupMember('noSuchMethod')));
}
Future dummyImplTest3() async {
@@ -66,9 +64,8 @@
await compiler.run(uri);
Expect.isFalse(compiler.backend.enabledNoSuchMethod);
ClassElement clsA = findElement(compiler, 'A');
- Expect.isTrue(
- compiler.backend.noSuchMethodRegistry.defaultImpls.contains(
- clsA.lookupMember('noSuchMethod')));
+ Expect.isTrue(compiler.backend.noSuchMethodRegistry.defaultImpls
+ .contains(clsA.lookupMember('noSuchMethod')));
}
Future dummyImplTest4() async {
@@ -89,13 +86,11 @@
await compiler.run(uri);
Expect.isFalse(compiler.backend.enabledNoSuchMethod);
ClassElement clsA = findElement(compiler, 'A');
- Expect.isTrue(
- compiler.backend.noSuchMethodRegistry.defaultImpls.contains(
- clsA.lookupMember('noSuchMethod')));
+ Expect.isTrue(compiler.backend.noSuchMethodRegistry.defaultImpls
+ .contains(clsA.lookupMember('noSuchMethod')));
ClassElement clsB = findElement(compiler, 'B');
- Expect.isTrue(
- compiler.backend.noSuchMethodRegistry.defaultImpls.contains(
- clsB.lookupMember('noSuchMethod')));
+ Expect.isTrue(compiler.backend.noSuchMethodRegistry.defaultImpls
+ .contains(clsB.lookupMember('noSuchMethod')));
}
Future dummyImplTest5() async {
@@ -116,13 +111,11 @@
await compiler.run(uri);
Expect.isTrue(compiler.backend.enabledNoSuchMethod);
ClassElement clsA = findElement(compiler, 'A');
- Expect.isTrue(
- compiler.backend.noSuchMethodRegistry.throwingImpls.contains(
- clsA.lookupMember('noSuchMethod')));
+ Expect.isTrue(compiler.backend.noSuchMethodRegistry.throwingImpls
+ .contains(clsA.lookupMember('noSuchMethod')));
ClassElement clsB = findElement(compiler, 'B');
- Expect.isTrue(
- compiler.backend.noSuchMethodRegistry.throwingImpls.contains(
- clsB.lookupMember('noSuchMethod')));
+ Expect.isTrue(compiler.backend.noSuchMethodRegistry.throwingImpls
+ .contains(clsB.lookupMember('noSuchMethod')));
}
Future dummyImplTest6() async {
@@ -139,9 +132,8 @@
await compiler.run(uri);
Expect.isTrue(compiler.backend.enabledNoSuchMethod);
ClassElement clsA = findElement(compiler, 'A');
- Expect.isTrue(
- compiler.backend.noSuchMethodRegistry.otherImpls.contains(
- clsA.lookupMember('noSuchMethod')));
+ Expect.isTrue(compiler.backend.noSuchMethodRegistry.otherImpls
+ .contains(clsA.lookupMember('noSuchMethod')));
}
Future dummyImplTest7() async {
@@ -158,9 +150,8 @@
await compiler.run(uri);
Expect.isFalse(compiler.backend.enabledNoSuchMethod);
ClassElement clsA = findElement(compiler, 'A');
- Expect.isTrue(
- compiler.backend.noSuchMethodRegistry.defaultImpls.contains(
- clsA.lookupMember('noSuchMethod')));
+ Expect.isTrue(compiler.backend.noSuchMethodRegistry.defaultImpls
+ .contains(clsA.lookupMember('noSuchMethod')));
}
Future dummyImplTest8() async {
@@ -177,9 +168,8 @@
await compiler.run(uri);
Expect.isTrue(compiler.backend.enabledNoSuchMethod);
ClassElement clsA = findElement(compiler, 'A');
- Expect.isTrue(
- compiler.backend.noSuchMethodRegistry.otherImpls.contains(
- clsA.lookupMember('noSuchMethod')));
+ Expect.isTrue(compiler.backend.noSuchMethodRegistry.otherImpls
+ .contains(clsA.lookupMember('noSuchMethod')));
}
Future dummyImplTest9() async {
@@ -196,9 +186,8 @@
await compiler.run(uri);
Expect.isFalse(compiler.backend.enabledNoSuchMethod);
ClassElement clsA = findElement(compiler, 'A');
- Expect.isTrue(
- compiler.backend.noSuchMethodRegistry.notApplicableImpls.contains(
- clsA.lookupMember('noSuchMethod')));
+ Expect.isTrue(compiler.backend.noSuchMethodRegistry.notApplicableImpls
+ .contains(clsA.lookupMember('noSuchMethod')));
}
Future dummyImplTest10() async {
@@ -217,9 +206,8 @@
await compiler.run(uri);
Expect.isTrue(compiler.backend.enabledNoSuchMethod);
ClassElement clsA = findElement(compiler, 'A');
- Expect.isTrue(
- compiler.backend.noSuchMethodRegistry.throwingImpls.contains(
- clsA.lookupMember('noSuchMethod')));
+ Expect.isTrue(compiler.backend.noSuchMethodRegistry.throwingImpls
+ .contains(clsA.lookupMember('noSuchMethod')));
}
Future dummyImplTest11() async {
@@ -239,12 +227,10 @@
await compiler.run(uri);
Expect.isTrue(compiler.backend.enabledNoSuchMethod);
ClassElement clsA = findElement(compiler, 'A');
- Expect.isTrue(
- compiler.backend.noSuchMethodRegistry.otherImpls.contains(
- clsA.lookupMember('noSuchMethod')));
- Expect.isTrue(
- compiler.backend.noSuchMethodRegistry.complexNoReturnImpls.contains(
- clsA.lookupMember('noSuchMethod')));
+ Expect.isTrue(compiler.backend.noSuchMethodRegistry.otherImpls
+ .contains(clsA.lookupMember('noSuchMethod')));
+ Expect.isTrue(compiler.backend.noSuchMethodRegistry.complexNoReturnImpls
+ .contains(clsA.lookupMember('noSuchMethod')));
}
Future dummyImplTest12() async {
@@ -263,12 +249,10 @@
await compiler.run(uri);
Expect.isTrue(compiler.backend.enabledNoSuchMethod);
ClassElement clsA = findElement(compiler, 'A');
- Expect.isTrue(
- compiler.backend.noSuchMethodRegistry.otherImpls.contains(
- clsA.lookupMember('noSuchMethod')));
- Expect.isTrue(
- compiler.backend.noSuchMethodRegistry.complexReturningImpls.contains(
- clsA.lookupMember('noSuchMethod')));
+ Expect.isTrue(compiler.backend.noSuchMethodRegistry.otherImpls
+ .contains(clsA.lookupMember('noSuchMethod')));
+ Expect.isTrue(compiler.backend.noSuchMethodRegistry.complexReturningImpls
+ .contains(clsA.lookupMember('noSuchMethod')));
}
Future dummyImplTest13() async {
@@ -285,9 +269,8 @@
await compiler.run(uri);
Expect.isFalse(compiler.backend.enabledNoSuchMethod);
ClassElement clsA = findElement(compiler, 'A');
- Expect.isTrue(
- compiler.backend.noSuchMethodRegistry.defaultImpls.contains(
- clsA.lookupMember('noSuchMethod')));
+ Expect.isTrue(compiler.backend.noSuchMethodRegistry.defaultImpls
+ .contains(clsA.lookupMember('noSuchMethod')));
}
main() {
diff --git a/tests/compiler/dart2js/null_check_test.dart b/tests/compiler/dart2js/null_check_test.dart
index bba2b5e..5d82a62 100644
--- a/tests/compiler/dart2js/null_check_test.dart
+++ b/tests/compiler/dart2js/null_check_test.dart
@@ -18,6 +18,6 @@
main() {
asyncTest(() => compileAll(TEST1).then((generated) {
- Expect.isFalse(generated.contains('foo.length'));
- }));
+ Expect.isFalse(generated.contains('foo.length'));
+ }));
}
diff --git a/tests/compiler/dart2js/null_type_test.dart b/tests/compiler/dart2js/null_type_test.dart
index c4f7606..d64c431 100644
--- a/tests/compiler/dart2js/null_type_test.dart
+++ b/tests/compiler/dart2js/null_type_test.dart
@@ -15,6 +15,6 @@
main() {
asyncTest(() => compile(TEST_ONE, entry: 'foo', check: (String generated) {
- Expect.isFalse(generated.contains('typeof (void 0)'));
- }));
+ Expect.isFalse(generated.contains('typeof (void 0)'));
+ }));
}
diff --git a/tests/compiler/dart2js/number_output_test.dart b/tests/compiler/dart2js/number_output_test.dart
index 6f873a5..af53a59 100644
--- a/tests/compiler/dart2js/number_output_test.dart
+++ b/tests/compiler/dart2js/number_output_test.dart
@@ -8,13 +8,14 @@
import 'memory_compiler.dart';
const MEMORY_SOURCE_FILES = const {
- 'main.dart': '''
+ 'main.dart': '''
main() {
print(12300000);
print(1234567890123456789012345);
print(double.MAX_FINITE);
print(-22230000);
- }'''};
+ }'''
+};
Future test({bool minify}) async {
OutputCollector collector = new OutputCollector();
diff --git a/tests/compiler/dart2js/override_inheritance_test.dart b/tests/compiler/dart2js/override_inheritance_test.dart
index f44b871..3f8bf74 100644
--- a/tests/compiler/dart2js/override_inheritance_test.dart
+++ b/tests/compiler/dart2js/override_inheritance_test.dart
@@ -5,23 +5,22 @@
import 'dart:async';
import 'package:async_helper/async_helper.dart';
import 'compiler_helper.dart';
-import 'package:compiler/src/resolution/class_members.dart'
- show MembersCreator;
+import 'package:compiler/src/resolution/class_members.dart' show MembersCreator;
main() {
asyncTest(() => Future.wait([
- testRequiredParameters(),
- testPositionalParameters(),
- testNamedParameters(),
- testNotSubtype(),
- testGetterNotSubtype(),
- testSetterNotSubtype(),
- testGenericNotSubtype(),
- testFieldNotSubtype(),
- testMixedOverride(),
- testAbstractMethods(),
- testNoSuchMethod(),
- ]));
+ testRequiredParameters(),
+ testPositionalParameters(),
+ testNamedParameters(),
+ testNotSubtype(),
+ testGetterNotSubtype(),
+ testSetterNotSubtype(),
+ testGenericNotSubtype(),
+ testFieldNotSubtype(),
+ testMixedOverride(),
+ testAbstractMethods(),
+ testNoSuchMethod(),
+ ]));
}
Future check(String source, {errors, warnings, hints, infos}) {
@@ -35,23 +34,19 @@
toList(o) => o == null ? [] : o is List ? o : [o];
compareMessageKinds(
- source, toList(errors),
- compiler.diagnosticCollector.errors, 'error');
+ source, toList(errors), compiler.diagnosticCollector.errors, 'error');
- compareMessageKinds(
- source, toList(warnings),
+ compareMessageKinds(source, toList(warnings),
compiler.diagnosticCollector.warnings, 'warning');
if (infos != null) {
compareMessageKinds(
- source, toList(infos),
- compiler.diagnosticCollector.infos, 'info');
+ source, toList(infos), compiler.diagnosticCollector.infos, 'info');
}
if (hints != null) {
compareMessageKinds(
- source, toList(hints),
- compiler.diagnosticCollector.hints, 'hint');
+ source, toList(hints), compiler.diagnosticCollector.hints, 'hint');
}
});
}
@@ -66,7 +61,6 @@
method() => null; // testRequiredParameters:1
}
"""),
-
check("""
class A {
method(a) => null; // testRequiredParameters:2
@@ -75,7 +69,6 @@
method(b) => null; // testRequiredParameters:3
}
"""),
-
check("""
class A {
method(a, b, c, d) => null; // testRequiredParameters:3
@@ -84,36 +77,39 @@
method(b, a, d, c) => null; // testRequiredParameters:4
}
"""),
-
- check("""
+ check(
+ """
class A {
method() => null; // testRequiredParameters:5
}
class Class extends A {
method(a) => null; // testRequiredParameters:6
}
- """, warnings: MessageKind.INVALID_OVERRIDE_METHOD,
- infos: MessageKind.INVALID_OVERRIDDEN_METHOD),
-
- check("""
+ """,
+ warnings: MessageKind.INVALID_OVERRIDE_METHOD,
+ infos: MessageKind.INVALID_OVERRIDDEN_METHOD),
+ check(
+ """
class A {
method() => null; // testRequiredParameters:7
}
class Class implements A {
method(a) => null; // testRequiredParameters:8
}
- """, warnings: MessageKind.INVALID_OVERRIDE_METHOD,
- infos: MessageKind.INVALID_OVERRIDDEN_METHOD),
-
- check("""
+ """,
+ warnings: MessageKind.INVALID_OVERRIDE_METHOD,
+ infos: MessageKind.INVALID_OVERRIDDEN_METHOD),
+ check(
+ """
class A {
method(a, b, c) => null; // testRequiredParameters:9
}
class Class extends A {
method(a, b, c, d) => null; // testRequiredParameters:10
}
- """, warnings: MessageKind.INVALID_OVERRIDE_METHOD,
- infos: MessageKind.INVALID_OVERRIDDEN_METHOD),
+ """,
+ warnings: MessageKind.INVALID_OVERRIDE_METHOD,
+ infos: MessageKind.INVALID_OVERRIDDEN_METHOD),
]);
}
@@ -127,7 +123,6 @@
method([a]) => null; // testPositionalParameters:2
}
"""),
-
check("""
class A {
method([a, b]) => null; // testPositionalParameters:3
@@ -136,7 +131,6 @@
method([b, a]) => null; // testPositionalParameters:4
}
"""),
-
check("""
class A {
method([a, b, c]) => null; // testPositionalParameters:5
@@ -145,7 +139,6 @@
method([b, d, a, c]) => null; // testPositionalParameters:6
}
"""),
-
check("""
class A {
method([a]) => null; // testPositionalParameters:7
@@ -154,46 +147,50 @@
method([a]) => null; // testPositionalParameters:8
}
"""),
-
- check("""
+ check(
+ """
class A {
method(a) => null; // testPositionalParameters:9
}
class Class extends A {
method() => null; // testPositionalParameters:10
}
- """, warnings: MessageKind.INVALID_OVERRIDE_METHOD,
- infos: MessageKind.INVALID_OVERRIDDEN_METHOD),
-
- check("""
+ """,
+ warnings: MessageKind.INVALID_OVERRIDE_METHOD,
+ infos: MessageKind.INVALID_OVERRIDDEN_METHOD),
+ check(
+ """
class A {
method(a, [b]) => null; // testPositionalParameters:11
}
class Class extends A {
method(a) => null; // testPositionalParameters:12
}
- """, warnings: MessageKind.INVALID_OVERRIDE_METHOD,
- infos: MessageKind.INVALID_OVERRIDDEN_METHOD),
-
- check("""
+ """,
+ warnings: MessageKind.INVALID_OVERRIDE_METHOD,
+ infos: MessageKind.INVALID_OVERRIDDEN_METHOD),
+ check(
+ """
class A {
method(a, [b]) => null; // testPositionalParameters:13
}
class Class extends A {
method([a]) => null; // testPositionalParameters:14
}
- """, warnings: MessageKind.INVALID_OVERRIDE_METHOD,
- infos: MessageKind.INVALID_OVERRIDDEN_METHOD),
-
- check("""
+ """,
+ warnings: MessageKind.INVALID_OVERRIDE_METHOD,
+ infos: MessageKind.INVALID_OVERRIDDEN_METHOD),
+ check(
+ """
class A {
method(a, b, [c, d, e]) => null; // testPositionalParameters:15
}
class Class extends A {
method([a, b, c, d]) => null; // testPositionalParameters:16
}
- """, warnings: MessageKind.INVALID_OVERRIDE_METHOD,
- infos: MessageKind.INVALID_OVERRIDDEN_METHOD),
+ """,
+ warnings: MessageKind.INVALID_OVERRIDE_METHOD,
+ infos: MessageKind.INVALID_OVERRIDDEN_METHOD),
]);
}
@@ -207,7 +204,6 @@
method({a}) => null; // testNamedParameters:2
}
"""),
-
check("""
class A {
method({a, b}) => null; // testNamedParameters:3
@@ -216,7 +212,6 @@
method({b, a}) => null; // testNamedParameters:4
}
"""),
-
check("""
class A {
method({a, b, c}) => null; // testNamedParameters:5
@@ -225,7 +220,6 @@
method({b, c, a, d}) => null; // testNamedParameters:6
}
"""),
-
check("""
class A {
method(d, {a, b, c}) => null; // testNamedParameters:7
@@ -234,36 +228,39 @@
method(e, {b, c, a, d}) => null; // testNamedParameters:8
}
"""),
-
- check("""
+ check(
+ """
class A {
method({a}) => null; // testNamedParameters:9
}
class Class extends A {
method() => null; // testNamedParameters:10
}
- """, warnings: MessageKind.INVALID_OVERRIDE_METHOD,
- infos: MessageKind.INVALID_OVERRIDDEN_METHOD),
-
- check("""
+ """,
+ warnings: MessageKind.INVALID_OVERRIDE_METHOD,
+ infos: MessageKind.INVALID_OVERRIDDEN_METHOD),
+ check(
+ """
class A {
method({a, b}) => null; // testNamedParameters:11
}
class Class extends A {
method({b}) => null; // testNamedParameters:12
}
- """, warnings: MessageKind.INVALID_OVERRIDE_METHOD,
- infos: MessageKind.INVALID_OVERRIDDEN_METHOD),
-
- check("""
+ """,
+ warnings: MessageKind.INVALID_OVERRIDE_METHOD,
+ infos: MessageKind.INVALID_OVERRIDDEN_METHOD),
+ check(
+ """
class A {
method({a, b, c, d}) => null; // testNamedParameters:13
}
class Class extends A {
method({a, e, d, c}) => null; // testNamedParameters:14
}
- """, warnings: MessageKind.INVALID_OVERRIDE_METHOD,
- infos: MessageKind.INVALID_OVERRIDDEN_METHOD),
+ """,
+ warnings: MessageKind.INVALID_OVERRIDE_METHOD,
+ infos: MessageKind.INVALID_OVERRIDDEN_METHOD),
]);
}
@@ -314,15 +311,17 @@
}
"""),
- check("""
+ check(
+ """
class A {
int method() => null; // testNotSubtype:11
}
class Class extends A {
void method() {} // testNotSubtype:12
}
- """, warnings: MessageKind.INVALID_OVERRIDE_METHOD,
- infos: MessageKind.INVALID_OVERRIDDEN_METHOD),
+ """,
+ warnings: MessageKind.INVALID_OVERRIDE_METHOD,
+ infos: MessageKind.INVALID_OVERRIDDEN_METHOD),
check("""
class A {
@@ -348,18 +347,21 @@
}
"""),
- check("""
+ check(
+ """
class A {
method(int a) => null; // testNotSubtype:19
}
class Class extends A {
method(String a) => null; // testNotSubtype:20
}
- """, warnings: MessageKind.INVALID_OVERRIDE_METHOD,
- infos: MessageKind.INVALID_OVERRIDDEN_METHOD),
+ """,
+ warnings: MessageKind.INVALID_OVERRIDE_METHOD,
+ infos: MessageKind.INVALID_OVERRIDDEN_METHOD),
// TODO(johnniwinther): These are unclear. Issue 16443 has been filed.
- check("""
+ check(
+ """
class A {
method(int a) => null; // testNotSubtype:23
}
@@ -371,10 +373,12 @@
class Class implements C {
method(double a) => null; // testNotSubtype:25
}
- """, warnings: MessageKind.INVALID_OVERRIDE_METHOD,
- infos: MessageKind.INVALID_OVERRIDDEN_METHOD),
+ """,
+ warnings: MessageKind.INVALID_OVERRIDE_METHOD,
+ infos: MessageKind.INVALID_OVERRIDDEN_METHOD),
- check("""
+ check(
+ """
class A {
method(num a) => null; // testNotSubtype:29
}
@@ -386,10 +390,12 @@
class Class implements C {
method(double a) => null; // testNotSubtype:31
}
- """, warnings: MessageKind.INVALID_OVERRIDE_METHOD,
- infos: MessageKind.INVALID_OVERRIDDEN_METHOD),
+ """,
+ warnings: MessageKind.INVALID_OVERRIDE_METHOD,
+ infos: MessageKind.INVALID_OVERRIDDEN_METHOD),
- check("""
+ check(
+ """
class A {
method(int a) => null; // testNotSubtype:26
}
@@ -401,10 +407,15 @@
class Class implements C {
method(String a) => null; // testNotSubtype:28
}
- """, warnings: [MessageKind.INVALID_OVERRIDE_METHOD,
- MessageKind.INVALID_OVERRIDE_METHOD],
- infos: [MessageKind.INVALID_OVERRIDDEN_METHOD,
- MessageKind.INVALID_OVERRIDDEN_METHOD]),
+ """,
+ warnings: [
+ MessageKind.INVALID_OVERRIDE_METHOD,
+ MessageKind.INVALID_OVERRIDE_METHOD
+ ],
+ infos: [
+ MessageKind.INVALID_OVERRIDDEN_METHOD,
+ MessageKind.INVALID_OVERRIDDEN_METHOD
+ ]),
]);
}
@@ -446,15 +457,17 @@
}
"""),
- check("""
+ check(
+ """
class A {
int get getter => null; // testGetterNotSubtype:9
}
class Class extends A {
double get getter => null; // testGetterNotSubtype:10
}
- """, warnings: MessageKind.INVALID_OVERRIDE_GETTER,
- infos: MessageKind.INVALID_OVERRIDDEN_GETTER),
+ """,
+ warnings: MessageKind.INVALID_OVERRIDE_GETTER,
+ infos: MessageKind.INVALID_OVERRIDDEN_GETTER),
check("""
class A {
@@ -468,7 +481,8 @@
}
"""),
- check("""
+ check(
+ """
class A {
int get getter => null; // testGetterNotSubtype:14
}
@@ -478,10 +492,12 @@
class Class extends A implements B {
double get getter => null; // testGetterNotSubtype:16
}
- """, warnings: MessageKind.INVALID_OVERRIDE_GETTER,
- infos: MessageKind.INVALID_OVERRIDDEN_GETTER),
+ """,
+ warnings: MessageKind.INVALID_OVERRIDE_GETTER,
+ infos: MessageKind.INVALID_OVERRIDDEN_GETTER),
- check("""
+ check(
+ """
class A {
int get getter => null; // testGetterNotSubtype:17
}
@@ -491,12 +507,18 @@
class Class extends A implements B {
double get getter => null; // testGetterNotSubtype:19
}
- """, warnings: [MessageKind.INVALID_OVERRIDE_GETTER,
- MessageKind.INVALID_OVERRIDE_GETTER],
- infos: [MessageKind.INVALID_OVERRIDDEN_GETTER,
- MessageKind.INVALID_OVERRIDDEN_GETTER]),
+ """,
+ warnings: [
+ MessageKind.INVALID_OVERRIDE_GETTER,
+ MessageKind.INVALID_OVERRIDE_GETTER
+ ],
+ infos: [
+ MessageKind.INVALID_OVERRIDDEN_GETTER,
+ MessageKind.INVALID_OVERRIDDEN_GETTER
+ ]),
- check("""
+ check(
+ """
class A {
int get getter => null; // testGetterNotSubtype:20
}
@@ -506,13 +528,19 @@
class Class implements A, B {
double get getter => null; // testGetterNotSubtype:22
}
- """, warnings: [MessageKind.INVALID_OVERRIDE_GETTER,
- MessageKind.INVALID_OVERRIDE_GETTER],
- infos: [MessageKind.INVALID_OVERRIDDEN_GETTER,
- MessageKind.INVALID_OVERRIDDEN_GETTER]),
+ """,
+ warnings: [
+ MessageKind.INVALID_OVERRIDE_GETTER,
+ MessageKind.INVALID_OVERRIDE_GETTER
+ ],
+ infos: [
+ MessageKind.INVALID_OVERRIDDEN_GETTER,
+ MessageKind.INVALID_OVERRIDDEN_GETTER
+ ]),
// TODO(johnniwinther): These are unclear. Issue 16443 has been filed.
- check("""
+ check(
+ """
class A {
int get getter => null; // testGetterNotSubtype:23
}
@@ -524,10 +552,12 @@
class Class implements C {
double get getter => null; // testGetterNotSubtype:25
}
- """, warnings: MessageKind.INVALID_OVERRIDE_GETTER,
- infos: MessageKind.INVALID_OVERRIDDEN_GETTER),
+ """,
+ warnings: MessageKind.INVALID_OVERRIDE_GETTER,
+ infos: MessageKind.INVALID_OVERRIDDEN_GETTER),
- check("""
+ check(
+ """
class A {
int get getter => null; // testGetterNotSubtype:26
}
@@ -539,10 +569,15 @@
class Class implements C {
String get getter => null; // testGetterNotSubtype:28
}
- """, warnings: [MessageKind.INVALID_OVERRIDE_GETTER,
- MessageKind.INVALID_OVERRIDE_GETTER],
- infos: [MessageKind.INVALID_OVERRIDDEN_GETTER,
- MessageKind.INVALID_OVERRIDDEN_GETTER]),
+ """,
+ warnings: [
+ MessageKind.INVALID_OVERRIDE_GETTER,
+ MessageKind.INVALID_OVERRIDE_GETTER
+ ],
+ infos: [
+ MessageKind.INVALID_OVERRIDDEN_GETTER,
+ MessageKind.INVALID_OVERRIDDEN_GETTER
+ ]),
]);
}
@@ -578,15 +613,17 @@
}
"""),
- check("""
+ check(
+ """
class A<T> {
method(T t) => null; // testGenericNotSubtype:8
}
class Class<S> extends A<S> {
method(int i) => null; // testGenericNotSubtype:9
}
- """, warnings: MessageKind.INVALID_OVERRIDE_METHOD,
- infos: MessageKind.INVALID_OVERRIDDEN_METHOD),
+ """,
+ warnings: MessageKind.INVALID_OVERRIDE_METHOD,
+ infos: MessageKind.INVALID_OVERRIDDEN_METHOD),
check("""
class A<T> {
@@ -600,7 +637,8 @@
}
"""),
- check("""
+ check(
+ """
class A<T> {
method(T t) => null; // testGenericNotSubtype:12
}
@@ -610,10 +648,12 @@
class Class<U> extends A<U> implements B<num> {
method(int i) => null; // testGenericNotSubtype:14
}
- """, warnings: MessageKind.INVALID_OVERRIDE_METHOD,
- infos: MessageKind.INVALID_OVERRIDDEN_METHOD),
+ """,
+ warnings: MessageKind.INVALID_OVERRIDE_METHOD,
+ infos: MessageKind.INVALID_OVERRIDDEN_METHOD),
- check("""
+ check(
+ """
class A<T> {
method(T t) => null; // testGenericNotSubtype:15
}
@@ -623,12 +663,18 @@
class Class extends A<int> implements B<String> {
method(double d) => null; // testGenericNotSubtype:17
}
- """, warnings: [MessageKind.INVALID_OVERRIDE_METHOD,
- MessageKind.INVALID_OVERRIDE_METHOD],
- infos: [MessageKind.INVALID_OVERRIDDEN_METHOD,
- MessageKind.INVALID_OVERRIDDEN_METHOD]),
+ """,
+ warnings: [
+ MessageKind.INVALID_OVERRIDE_METHOD,
+ MessageKind.INVALID_OVERRIDE_METHOD
+ ],
+ infos: [
+ MessageKind.INVALID_OVERRIDDEN_METHOD,
+ MessageKind.INVALID_OVERRIDDEN_METHOD
+ ]),
- check("""
+ check(
+ """
class A<T> {
method(T t) => null; // testGenericNotSubtype:18
}
@@ -638,13 +684,19 @@
class Class implements A<int>, B<String> {
method(double d) => null; // testGenericNotSubtype:20
}
- """, warnings: [MessageKind.INVALID_OVERRIDE_METHOD,
- MessageKind.INVALID_OVERRIDE_METHOD],
- infos: [MessageKind.INVALID_OVERRIDDEN_METHOD,
- MessageKind.INVALID_OVERRIDDEN_METHOD]),
+ """,
+ warnings: [
+ MessageKind.INVALID_OVERRIDE_METHOD,
+ MessageKind.INVALID_OVERRIDE_METHOD
+ ],
+ infos: [
+ MessageKind.INVALID_OVERRIDDEN_METHOD,
+ MessageKind.INVALID_OVERRIDDEN_METHOD
+ ]),
// TODO(johnniwinther): These are unclear. Issue 16443 has been filed.
- check("""
+ check(
+ """
class A<T> {
method(T t) => null; // testGenericNotSubtype:21
}
@@ -656,10 +708,12 @@
class Class implements C {
method(double d) => null; // testGenericNotSubtype:23
}
- """, warnings: MessageKind.INVALID_OVERRIDE_METHOD,
- infos: MessageKind.INVALID_OVERRIDDEN_METHOD),
+ """,
+ warnings: MessageKind.INVALID_OVERRIDE_METHOD,
+ infos: MessageKind.INVALID_OVERRIDDEN_METHOD),
- check("""
+ check(
+ """
class A<T> {
method(T t) => null; // testGenericNotSubtype:24
}
@@ -671,16 +725,21 @@
class Class implements C {
method(String s) => null; // testGenericNotSubtype:26
}
- """, warnings: [MessageKind.INVALID_OVERRIDE_METHOD,
- MessageKind.INVALID_OVERRIDE_METHOD],
- infos: [MessageKind.INVALID_OVERRIDDEN_METHOD,
- MessageKind.INVALID_OVERRIDDEN_METHOD]),
+ """,
+ warnings: [
+ MessageKind.INVALID_OVERRIDE_METHOD,
+ MessageKind.INVALID_OVERRIDE_METHOD
+ ],
+ infos: [
+ MessageKind.INVALID_OVERRIDDEN_METHOD,
+ MessageKind.INVALID_OVERRIDDEN_METHOD
+ ]),
]);
}
Future testSetterNotSubtype() {
return Future.wait([
- check("""
+ check("""
class A {
set setter(_) => null; // testSetterNotSubtype:1
}
@@ -689,7 +748,7 @@
}
"""),
- check("""
+ check("""
class A {
void set setter(_) {} // testSetterNotSubtype:3
}
@@ -698,7 +757,7 @@
}
"""),
- check("""
+ check("""
class A {
set setter(_) => null; // testSetterNotSubtype:5
}
@@ -707,7 +766,7 @@
}
"""),
- check("""
+ check("""
class A {
set setter(_) => null; // testSetterNotSubtype:7
}
@@ -716,7 +775,7 @@
}
"""),
- check("""
+ check("""
class A {
set setter(num _) => null; // testSetterNotSubtype:9
}
@@ -725,7 +784,7 @@
}
"""),
- check("""
+ check("""
class A {
set setter(num _) => null; // testSetterNotSubtype:11
}
@@ -734,7 +793,7 @@
}
"""),
- check("""
+ check("""
class A {
set setter(int _) => null; // testSetterNotSubtype:13
}
@@ -743,17 +802,19 @@
}
"""),
- check("""
+ check(
+ """
class A {
set setter(int _) => null; // testSetterNotSubtype:15
}
class Class extends A {
set setter(double _) => null; // testSetterNotSubtype:16
}
- """, warnings: MessageKind.INVALID_OVERRIDE_SETTER,
- infos: MessageKind.INVALID_OVERRIDDEN_SETTER),
+ """,
+ warnings: MessageKind.INVALID_OVERRIDE_SETTER,
+ infos: MessageKind.INVALID_OVERRIDDEN_SETTER),
- check("""
+ check("""
class A {
set setter(int _) => null; // testSetterNotSubtype:17
}
@@ -765,7 +826,8 @@
}
"""),
- check("""
+ check(
+ """
class A {
set setter(int _) => null; // testSetterNotSubtype:20
}
@@ -775,10 +837,12 @@
class Class extends A implements B {
set setter(double _) => null; // testSetterNotSubtype:22
}
- """, warnings: MessageKind.INVALID_OVERRIDE_SETTER,
- infos: MessageKind.INVALID_OVERRIDDEN_SETTER),
+ """,
+ warnings: MessageKind.INVALID_OVERRIDE_SETTER,
+ infos: MessageKind.INVALID_OVERRIDDEN_SETTER),
- check("""
+ check(
+ """
class A {
set setter(int _) => null; // testSetterNotSubtype:23
}
@@ -788,12 +852,18 @@
class Class extends A implements B {
set setter(double _) => null; // testSetterNotSubtype:25
}
- """, warnings: [MessageKind.INVALID_OVERRIDE_SETTER,
- MessageKind.INVALID_OVERRIDE_SETTER],
- infos: [MessageKind.INVALID_OVERRIDDEN_SETTER,
- MessageKind.INVALID_OVERRIDDEN_SETTER]),
+ """,
+ warnings: [
+ MessageKind.INVALID_OVERRIDE_SETTER,
+ MessageKind.INVALID_OVERRIDE_SETTER
+ ],
+ infos: [
+ MessageKind.INVALID_OVERRIDDEN_SETTER,
+ MessageKind.INVALID_OVERRIDDEN_SETTER
+ ]),
- check("""
+ check(
+ """
class A {
set setter(int _) => null; // testSetterNotSubtype:26
}
@@ -803,13 +873,19 @@
class Class implements A, B {
set setter(double _) => null; // testSetterNotSubtype:28
}
- """, warnings: [MessageKind.INVALID_OVERRIDE_SETTER,
- MessageKind.INVALID_OVERRIDE_SETTER],
- infos: [MessageKind.INVALID_OVERRIDDEN_SETTER,
- MessageKind.INVALID_OVERRIDDEN_SETTER]),
+ """,
+ warnings: [
+ MessageKind.INVALID_OVERRIDE_SETTER,
+ MessageKind.INVALID_OVERRIDE_SETTER
+ ],
+ infos: [
+ MessageKind.INVALID_OVERRIDDEN_SETTER,
+ MessageKind.INVALID_OVERRIDDEN_SETTER
+ ]),
- // TODO(johnniwinther): These are unclear. Issue 16443 has been filed.
- check("""
+ // TODO(johnniwinther): These are unclear. Issue 16443 has been filed.
+ check(
+ """
class A {
set setter(int _) => null; // testSetterNotSubtype:29
}
@@ -821,10 +897,12 @@
class Class implements C {
set setter(double _) => null; // testSetterNotSubtype:31
}
- """, warnings: MessageKind.INVALID_OVERRIDE_SETTER,
- infos: MessageKind.INVALID_OVERRIDDEN_SETTER),
+ """,
+ warnings: MessageKind.INVALID_OVERRIDE_SETTER,
+ infos: MessageKind.INVALID_OVERRIDDEN_SETTER),
- check("""
+ check(
+ """
class A {
set setter(int _) => null; // testSetterNotSubtype:32
}
@@ -836,10 +914,15 @@
class Class implements C {
set setter(String _) => null; // testSetterNotSubtype:34
}
- """, warnings: [MessageKind.INVALID_OVERRIDE_SETTER,
- MessageKind.INVALID_OVERRIDE_SETTER],
- infos: [MessageKind.INVALID_OVERRIDDEN_SETTER,
- MessageKind.INVALID_OVERRIDDEN_SETTER]),
+ """,
+ warnings: [
+ MessageKind.INVALID_OVERRIDE_SETTER,
+ MessageKind.INVALID_OVERRIDE_SETTER
+ ],
+ infos: [
+ MessageKind.INVALID_OVERRIDDEN_SETTER,
+ MessageKind.INVALID_OVERRIDDEN_SETTER
+ ]),
]);
}
@@ -853,7 +936,6 @@
int field; // testFieldNotSubtype:2
}
"""),
-
check("""
class A {
num field; // testFieldNotSubtype:3
@@ -862,7 +944,6 @@
int field; // testFieldNotSubtype:4
}
"""),
-
check("""
class A {
int field; // testFieldNotSubtype:5
@@ -871,17 +952,17 @@
num field; // testFieldNotSubtype:6
}
"""),
-
- check("""
+ check(
+ """
class A {
int field; // testFieldNotSubtype:7
}
class Class extends A {
double field; // testFieldNotSubtype:8
}
- """, warnings: MessageKind.INVALID_OVERRIDE_FIELD,
- infos: MessageKind.INVALID_OVERRIDDEN_FIELD),
-
+ """,
+ warnings: MessageKind.INVALID_OVERRIDE_FIELD,
+ infos: MessageKind.INVALID_OVERRIDDEN_FIELD),
check("""
class A {
int field; // testFieldNotSubtype:9
@@ -893,7 +974,6 @@
double field; // testFieldNotSubtype:11
}
"""),
-
check("""
class A {
num field; // testFieldNotSubtype:12
@@ -902,27 +982,28 @@
int get field => null; // testFieldNotSubtype:13
}
"""),
-
- check("""
+ check(
+ """
class A {
num field; // testFieldNotSubtype:14
}
class Class extends A {
String get field => null; // testFieldNotSubtype:15
}
- """, warnings: MessageKind.INVALID_OVERRIDE_FIELD_WITH_GETTER,
- infos: MessageKind.INVALID_OVERRIDDEN_FIELD),
-
- check("""
+ """,
+ warnings: MessageKind.INVALID_OVERRIDE_FIELD_WITH_GETTER,
+ infos: MessageKind.INVALID_OVERRIDDEN_FIELD),
+ check(
+ """
class A {
num get field => null; // testFieldNotSubtype:16
}
class Class extends A {
String field; // testFieldNotSubtype:17
}
- """, warnings: MessageKind.INVALID_OVERRIDE_GETTER_WITH_FIELD,
- infos: MessageKind.INVALID_OVERRIDDEN_GETTER),
-
+ """,
+ warnings: MessageKind.INVALID_OVERRIDE_GETTER_WITH_FIELD,
+ infos: MessageKind.INVALID_OVERRIDDEN_GETTER),
check("""
class A {
num field; // testFieldNotSubtype:18
@@ -931,7 +1012,6 @@
set field(int _) {} // testFieldNotSubtype:19
}
"""),
-
check("""
class A {
num field; // testFieldNotSubtype:19
@@ -940,7 +1020,6 @@
void set field(int _) {} // testFieldNotSubtype:20
}
"""),
-
check("""
class A {
set field(int _) {} // testFieldNotSubtype:21
@@ -949,7 +1028,6 @@
num field; // testFieldNotSubtype:22
}
"""),
-
check("""
class A {
void set field(int _) {} // testFieldNotSubtype:23
@@ -958,28 +1036,30 @@
num field; // testFieldNotSubtype:24
}
"""),
-
- check("""
+ check(
+ """
class A {
num field; // testFieldNotSubtype:25
}
class Class extends A {
set field(String _) {} // testFieldNotSubtype:26
}
- """, warnings: MessageKind.INVALID_OVERRIDE_FIELD_WITH_SETTER,
- infos: MessageKind.INVALID_OVERRIDDEN_FIELD),
-
- check("""
+ """,
+ warnings: MessageKind.INVALID_OVERRIDE_FIELD_WITH_SETTER,
+ infos: MessageKind.INVALID_OVERRIDDEN_FIELD),
+ check(
+ """
class A {
set field(num _) {} // testFieldNotSubtype:27
}
class Class extends A {
String field; // testFieldNotSubtype:28
}
- """, warnings: MessageKind.INVALID_OVERRIDE_SETTER_WITH_FIELD,
- infos: MessageKind.INVALID_OVERRIDDEN_SETTER),
-
- check("""
+ """,
+ warnings: MessageKind.INVALID_OVERRIDE_SETTER_WITH_FIELD,
+ infos: MessageKind.INVALID_OVERRIDDEN_SETTER),
+ check(
+ """
class A {
int field; // testFieldNotSubtype:29
}
@@ -987,13 +1067,17 @@
String get field => null; // testFieldNotSubtype:30
void set field(String s) {} // testFieldNotSubtype:31
}
- """, warnings: [MessageKind.INVALID_OVERRIDE_FIELD_WITH_GETTER,
- MessageKind.INVALID_OVERRIDE_FIELD_WITH_SETTER],
- infos: [MessageKind.INVALID_OVERRIDDEN_FIELD,
- MessageKind.INVALID_OVERRIDDEN_FIELD]),
-
-
- check("""
+ """,
+ warnings: [
+ MessageKind.INVALID_OVERRIDE_FIELD_WITH_GETTER,
+ MessageKind.INVALID_OVERRIDE_FIELD_WITH_SETTER
+ ],
+ infos: [
+ MessageKind.INVALID_OVERRIDDEN_FIELD,
+ MessageKind.INVALID_OVERRIDDEN_FIELD
+ ]),
+ check(
+ """
class A {
String get field => null; // testFieldNotSubtype:32
void set field(String s) {} // testFieldNotSubtype:33
@@ -1001,55 +1085,64 @@
class Class implements A {
int field; // testFieldNotSubtype:34
}
- """, warnings: [MessageKind.INVALID_OVERRIDE_GETTER_WITH_FIELD,
- MessageKind.INVALID_OVERRIDE_SETTER_WITH_FIELD],
- infos: [MessageKind.INVALID_OVERRIDDEN_GETTER,
- MessageKind.INVALID_OVERRIDDEN_SETTER]),
+ """,
+ warnings: [
+ MessageKind.INVALID_OVERRIDE_GETTER_WITH_FIELD,
+ MessageKind.INVALID_OVERRIDE_SETTER_WITH_FIELD
+ ],
+ infos: [
+ MessageKind.INVALID_OVERRIDDEN_GETTER,
+ MessageKind.INVALID_OVERRIDDEN_SETTER
+ ]),
]);
}
Future testMixedOverride() {
return Future.wait([
- check("""
+ check(
+ """
class A {
var member; // testMixedOverride:1
}
class Class extends A {
member() {} // testMixedOverride:2
}
- """, errors: MessageKind.CANNOT_OVERRIDE_FIELD_WITH_METHOD,
- infos: MessageKind.CANNOT_OVERRIDE_FIELD_WITH_METHOD_CONT),
-
- check("""
+ """,
+ errors: MessageKind.CANNOT_OVERRIDE_FIELD_WITH_METHOD,
+ infos: MessageKind.CANNOT_OVERRIDE_FIELD_WITH_METHOD_CONT),
+ check(
+ """
class A {
member() {} // testMixedOverride:3
}
class Class extends A {
var member; // testMixedOverride:4
}
- """, errors: MessageKind.CANNOT_OVERRIDE_METHOD_WITH_FIELD,
- infos: MessageKind.CANNOT_OVERRIDE_METHOD_WITH_FIELD_CONT),
-
- check("""
+ """,
+ errors: MessageKind.CANNOT_OVERRIDE_METHOD_WITH_FIELD,
+ infos: MessageKind.CANNOT_OVERRIDE_METHOD_WITH_FIELD_CONT),
+ check(
+ """
class A {
get member => null; // testMixedOverride:5
}
class Class extends A {
member() {} // testMixedOverride:6
}
- """, errors: MessageKind.CANNOT_OVERRIDE_GETTER_WITH_METHOD,
- infos: MessageKind.CANNOT_OVERRIDE_GETTER_WITH_METHOD_CONT),
-
- check("""
+ """,
+ errors: MessageKind.CANNOT_OVERRIDE_GETTER_WITH_METHOD,
+ infos: MessageKind.CANNOT_OVERRIDE_GETTER_WITH_METHOD_CONT),
+ check(
+ """
class A {
member() {} // testMixedOverride:7
}
class Class extends A {
get member => null; // testMixedOverride:8
}
- """, errors: MessageKind.CANNOT_OVERRIDE_METHOD_WITH_GETTER,
- infos: MessageKind.CANNOT_OVERRIDE_METHOD_WITH_GETTER_CONT),
-
+ """,
+ errors: MessageKind.CANNOT_OVERRIDE_METHOD_WITH_GETTER,
+ infos: MessageKind.CANNOT_OVERRIDE_METHOD_WITH_GETTER_CONT),
check("""
abstract class A {
var member; // testMixedOverride:9
@@ -1060,8 +1153,8 @@
abstract class Class implements A, B {
}
"""),
-
- check("""
+ check(
+ """
abstract class A {
var member; // testMixedOverride:11
}
@@ -1070,11 +1163,14 @@
}
abstract class Class implements A, B {
}
- """, warnings: MessageKind.INHERIT_GETTER_AND_METHOD,
- infos: [MessageKind.INHERITED_METHOD,
- MessageKind.INHERITED_IMPLICIT_GETTER]),
-
- check("""
+ """,
+ warnings: MessageKind.INHERIT_GETTER_AND_METHOD,
+ infos: [
+ MessageKind.INHERITED_METHOD,
+ MessageKind.INHERITED_IMPLICIT_GETTER
+ ]),
+ check(
+ """
abstract class A {
get member; // testMixedOverride:13
}
@@ -1083,11 +1179,14 @@
}
abstract class Class implements A, B {
}
- """, warnings: MessageKind.INHERIT_GETTER_AND_METHOD,
- infos: [MessageKind.INHERITED_METHOD,
- MessageKind.INHERITED_EXPLICIT_GETTER]),
-
- check("""
+ """,
+ warnings: MessageKind.INHERIT_GETTER_AND_METHOD,
+ infos: [
+ MessageKind.INHERITED_METHOD,
+ MessageKind.INHERITED_EXPLICIT_GETTER
+ ]),
+ check(
+ """
abstract class A {
get member; // testMixedOverride:15
}
@@ -1105,14 +1204,17 @@
}
abstract class Class implements A, B, C, D, E {
}
- """, warnings: MessageKind.INHERIT_GETTER_AND_METHOD,
- infos: [MessageKind.INHERITED_EXPLICIT_GETTER,
- MessageKind.INHERITED_METHOD,
- MessageKind.INHERITED_IMPLICIT_GETTER,
- MessageKind.INHERITED_METHOD,
- MessageKind.INHERITED_EXPLICIT_GETTER]),
-
- check("""
+ """,
+ warnings: MessageKind.INHERIT_GETTER_AND_METHOD,
+ infos: [
+ MessageKind.INHERITED_EXPLICIT_GETTER,
+ MessageKind.INHERITED_METHOD,
+ MessageKind.INHERITED_IMPLICIT_GETTER,
+ MessageKind.INHERITED_METHOD,
+ MessageKind.INHERITED_EXPLICIT_GETTER
+ ]),
+ check(
+ """
abstract class A {
get member; // testMixedOverride:20
}
@@ -1124,13 +1226,16 @@
class Class extends C {
member() {} // testMixedOverride:22
}
- """, errors: MessageKind.CANNOT_OVERRIDE_GETTER_WITH_METHOD,
- warnings: MessageKind.INHERIT_GETTER_AND_METHOD,
- infos: [MessageKind.INHERITED_METHOD,
- MessageKind.INHERITED_EXPLICIT_GETTER,
- MessageKind.CANNOT_OVERRIDE_GETTER_WITH_METHOD_CONT]),
-
- check("""
+ """,
+ errors: MessageKind.CANNOT_OVERRIDE_GETTER_WITH_METHOD,
+ warnings: MessageKind.INHERIT_GETTER_AND_METHOD,
+ infos: [
+ MessageKind.INHERITED_METHOD,
+ MessageKind.INHERITED_EXPLICIT_GETTER,
+ MessageKind.CANNOT_OVERRIDE_GETTER_WITH_METHOD_CONT
+ ]),
+ check(
+ """
abstract class A {
get member; // testMixedOverride:23
}
@@ -1142,11 +1247,14 @@
class Class extends C {
get member => null; // testMixedOverride:25
}
- """, errors: MessageKind.CANNOT_OVERRIDE_METHOD_WITH_GETTER,
- warnings: MessageKind.INHERIT_GETTER_AND_METHOD,
- infos: [MessageKind.INHERITED_METHOD,
- MessageKind.INHERITED_EXPLICIT_GETTER,
- MessageKind.CANNOT_OVERRIDE_METHOD_WITH_GETTER_CONT]),
+ """,
+ errors: MessageKind.CANNOT_OVERRIDE_METHOD_WITH_GETTER,
+ warnings: MessageKind.INHERIT_GETTER_AND_METHOD,
+ infos: [
+ MessageKind.INHERITED_METHOD,
+ MessageKind.INHERITED_EXPLICIT_GETTER,
+ MessageKind.CANNOT_OVERRIDE_METHOD_WITH_GETTER_CONT
+ ]),
]);
}
@@ -1157,28 +1265,30 @@
method(); // testAbstractMethod:1
}
"""),
-
- check("""
+ check(
+ """
class Class {
method(); // testAbstractMethod:2
}
- """, warnings: MessageKind.ABSTRACT_METHOD,
- infos: []),
-
- check("""
+ """,
+ warnings: MessageKind.ABSTRACT_METHOD,
+ infos: []),
+ check(
+ """
class Class {
get getter; // testAbstractMethod:3
}
- """, warnings: MessageKind.ABSTRACT_GETTER,
- infos: []),
-
- check("""
+ """,
+ warnings: MessageKind.ABSTRACT_GETTER,
+ infos: []),
+ check(
+ """
class Class {
set setter(_); // testAbstractMethod:4
}
- """, warnings: MessageKind.ABSTRACT_SETTER,
- infos: []),
-
+ """,
+ warnings: MessageKind.ABSTRACT_SETTER,
+ infos: []),
check("""
abstract class A {
method(); // testAbstractMethod:5
@@ -1187,7 +1297,6 @@
method() {} // testAbstractMethod:6
}
"""),
-
check("""
abstract class A {
method(); // testAbstractMethod:7
@@ -1196,35 +1305,38 @@
method([a]) {} // testAbstractMethod:8
}
"""),
-
- check("""
+ check(
+ """
abstract class A {
method(); // testAbstractMethod:9
}
class Class extends A {
}
- """, warnings: MessageKind.UNIMPLEMENTED_METHOD_ONE,
- infos: MessageKind.UNIMPLEMENTED_METHOD_CONT),
-
- check("""
+ """,
+ warnings: MessageKind.UNIMPLEMENTED_METHOD_ONE,
+ infos: MessageKind.UNIMPLEMENTED_METHOD_CONT),
+ check(
+ """
abstract class A {
get getter; // testAbstractMethod:10
}
class Class extends A {
}
- """, warnings: MessageKind.UNIMPLEMENTED_GETTER_ONE,
- infos: MessageKind.UNIMPLEMENTED_EXPLICIT_GETTER),
-
- check("""
+ """,
+ warnings: MessageKind.UNIMPLEMENTED_GETTER_ONE,
+ infos: MessageKind.UNIMPLEMENTED_EXPLICIT_GETTER),
+ check(
+ """
abstract class A {
set setter(_); // testAbstractMethod:11
}
class Class extends A {
}
- """, warnings: MessageKind.UNIMPLEMENTED_SETTER_ONE,
- infos: MessageKind.UNIMPLEMENTED_EXPLICIT_SETTER),
-
- check("""
+ """,
+ warnings: MessageKind.UNIMPLEMENTED_SETTER_ONE,
+ infos: MessageKind.UNIMPLEMENTED_EXPLICIT_SETTER),
+ check(
+ """
abstract class A {
method(); // testAbstractMethod:12
}
@@ -1233,17 +1345,21 @@
}
class Class extends A implements B {
}
- """, warnings: MessageKind.UNIMPLEMENTED_METHOD,
- infos: [MessageKind.UNIMPLEMENTED_METHOD_CONT,
- MessageKind.UNIMPLEMENTED_METHOD_CONT]),
-
- check("""
+ """,
+ warnings: MessageKind.UNIMPLEMENTED_METHOD,
+ infos: [
+ MessageKind.UNIMPLEMENTED_METHOD_CONT,
+ MessageKind.UNIMPLEMENTED_METHOD_CONT
+ ]),
+ check(
+ """
class Class implements Function {
}
- """, warnings: MessageKind.UNIMPLEMENTED_METHOD_ONE,
- infos: []),
-
- check("""
+ """,
+ warnings: MessageKind.UNIMPLEMENTED_METHOD_ONE,
+ infos: []),
+ check(
+ """
abstract class A {
get getter; // testAbstractMethod:14
}
@@ -1252,11 +1368,14 @@
}
class Class extends A implements B {
}
- """, warnings: MessageKind.UNIMPLEMENTED_GETTER,
- infos: [MessageKind.UNIMPLEMENTED_EXPLICIT_GETTER,
- MessageKind.UNIMPLEMENTED_EXPLICIT_GETTER]),
-
- check("""
+ """,
+ warnings: MessageKind.UNIMPLEMENTED_GETTER,
+ infos: [
+ MessageKind.UNIMPLEMENTED_EXPLICIT_GETTER,
+ MessageKind.UNIMPLEMENTED_EXPLICIT_GETTER
+ ]),
+ check(
+ """
abstract class A {
set setter(_); // testAbstractMethod:16
}
@@ -1265,11 +1384,14 @@
}
class Class extends A implements B {
}
- """, warnings: MessageKind.UNIMPLEMENTED_SETTER,
- infos: [MessageKind.UNIMPLEMENTED_EXPLICIT_SETTER,
- MessageKind.UNIMPLEMENTED_EXPLICIT_SETTER]),
-
- check("""
+ """,
+ warnings: MessageKind.UNIMPLEMENTED_SETTER,
+ infos: [
+ MessageKind.UNIMPLEMENTED_EXPLICIT_SETTER,
+ MessageKind.UNIMPLEMENTED_EXPLICIT_SETTER
+ ]),
+ check(
+ """
abstract class A {
get field; // testAbstractMethod:18
}
@@ -1279,11 +1401,14 @@
class Class extends A implements B {
set field(_) {} // testAbstractMethod:20
}
- """, warnings: MessageKind.UNIMPLEMENTED_GETTER,
- infos: [MessageKind.UNIMPLEMENTED_EXPLICIT_GETTER,
- MessageKind.UNIMPLEMENTED_IMPLICIT_GETTER]),
-
- check("""
+ """,
+ warnings: MessageKind.UNIMPLEMENTED_GETTER,
+ infos: [
+ MessageKind.UNIMPLEMENTED_EXPLICIT_GETTER,
+ MessageKind.UNIMPLEMENTED_IMPLICIT_GETTER
+ ]),
+ check(
+ """
abstract class A {
set field(_); // testAbstractMethod:21
}
@@ -1293,10 +1418,12 @@
class Class extends A implements B {
get field => 0; // testAbstractMethod:23
}
- """, warnings: MessageKind.UNIMPLEMENTED_SETTER,
- infos: [MessageKind.UNIMPLEMENTED_EXPLICIT_SETTER,
- MessageKind.UNIMPLEMENTED_IMPLICIT_SETTER]),
-
+ """,
+ warnings: MessageKind.UNIMPLEMENTED_SETTER,
+ infos: [
+ MessageKind.UNIMPLEMENTED_EXPLICIT_SETTER,
+ MessageKind.UNIMPLEMENTED_IMPLICIT_SETTER
+ ]),
check("""
class A {
method() {} // testAbstractMethod:24
@@ -1305,7 +1432,6 @@
method() {} // testAbstractMethod:25
}
"""),
-
check("""
class A {
method() {} // testAbstractMethod:26
@@ -1314,16 +1440,16 @@
method([a]) {} // testAbstractMethod:27
}
"""),
-
- check("""
+ check(
+ """
class A {
method() {} // testAbstractMethod:28
}
class Class implements A {
}
- """, warnings: MessageKind.UNIMPLEMENTED_METHOD_ONE,
- infos: MessageKind.UNIMPLEMENTED_METHOD_CONT),
-
+ """,
+ warnings: MessageKind.UNIMPLEMENTED_METHOD_ONE,
+ infos: MessageKind.UNIMPLEMENTED_METHOD_CONT),
check("""
class A {
method() {} // testAbstractMethod:29
@@ -1334,19 +1460,24 @@
class Class extends A implements B {
}
"""),
-
- check("""
+ check(
+ """
class A {
var member; // testAbstractMethod:31
}
class Class implements A {
}
- """, warnings: [MessageKind.UNIMPLEMENTED_GETTER_ONE,
- MessageKind.UNIMPLEMENTED_SETTER_ONE],
- infos: [MessageKind.UNIMPLEMENTED_IMPLICIT_GETTER,
- MessageKind.UNIMPLEMENTED_IMPLICIT_SETTER]),
-
- check("""
+ """,
+ warnings: [
+ MessageKind.UNIMPLEMENTED_GETTER_ONE,
+ MessageKind.UNIMPLEMENTED_SETTER_ONE
+ ],
+ infos: [
+ MessageKind.UNIMPLEMENTED_IMPLICIT_GETTER,
+ MessageKind.UNIMPLEMENTED_IMPLICIT_SETTER
+ ]),
+ check(
+ """
class A {
var member; // testAbstractMethod:32
}
@@ -1356,14 +1487,19 @@
}
class Class implements A, B {
}
- """, warnings: [MessageKind.UNIMPLEMENTED_GETTER,
- MessageKind.UNIMPLEMENTED_SETTER],
- infos: [MessageKind.UNIMPLEMENTED_EXPLICIT_GETTER,
- MessageKind.UNIMPLEMENTED_IMPLICIT_GETTER,
- MessageKind.UNIMPLEMENTED_EXPLICIT_SETTER,
- MessageKind.UNIMPLEMENTED_IMPLICIT_SETTER]),
-
- check("""
+ """,
+ warnings: [
+ MessageKind.UNIMPLEMENTED_GETTER,
+ MessageKind.UNIMPLEMENTED_SETTER
+ ],
+ infos: [
+ MessageKind.UNIMPLEMENTED_EXPLICIT_GETTER,
+ MessageKind.UNIMPLEMENTED_IMPLICIT_GETTER,
+ MessageKind.UNIMPLEMENTED_EXPLICIT_SETTER,
+ MessageKind.UNIMPLEMENTED_IMPLICIT_SETTER
+ ]),
+ check(
+ """
class A {
var member; // testAbstractMethod:35
}
@@ -1372,61 +1508,70 @@
}
class Class implements A, B {
}
- """, warnings: [MessageKind.UNIMPLEMENTED_GETTER,
- MessageKind.UNIMPLEMENTED_SETTER],
- infos: [MessageKind.UNIMPLEMENTED_IMPLICIT_GETTER,
- MessageKind.UNIMPLEMENTED_IMPLICIT_GETTER,
- MessageKind.UNIMPLEMENTED_IMPLICIT_SETTER,
- MessageKind.UNIMPLEMENTED_IMPLICIT_SETTER]),
-
- check("""
+ """,
+ warnings: [
+ MessageKind.UNIMPLEMENTED_GETTER,
+ MessageKind.UNIMPLEMENTED_SETTER
+ ],
+ infos: [
+ MessageKind.UNIMPLEMENTED_IMPLICIT_GETTER,
+ MessageKind.UNIMPLEMENTED_IMPLICIT_GETTER,
+ MessageKind.UNIMPLEMENTED_IMPLICIT_SETTER,
+ MessageKind.UNIMPLEMENTED_IMPLICIT_SETTER
+ ]),
+ check(
+ """
class A {
get member => 0; // testAbstractMethod:37
}
class Class implements A {
}
- """, warnings: MessageKind.UNIMPLEMENTED_GETTER_ONE,
- infos: MessageKind.UNIMPLEMENTED_EXPLICIT_GETTER),
-
- check("""
+ """,
+ warnings: MessageKind.UNIMPLEMENTED_GETTER_ONE,
+ infos: MessageKind.UNIMPLEMENTED_EXPLICIT_GETTER),
+ check(
+ """
class A {
set member(_) {} // testAbstractMethod:38
}
class Class implements A {
}
- """, warnings: MessageKind.UNIMPLEMENTED_SETTER_ONE,
- infos: MessageKind.UNIMPLEMENTED_EXPLICIT_SETTER),
-
- check("""
+ """,
+ warnings: MessageKind.UNIMPLEMENTED_SETTER_ONE,
+ infos: MessageKind.UNIMPLEMENTED_EXPLICIT_SETTER),
+ check(
+ """
class A {
var member; // testAbstractMethod:39
}
class Class implements A {
get member => 0;
}
- """, warnings: MessageKind.UNIMPLEMENTED_SETTER_ONE,
- infos: MessageKind.UNIMPLEMENTED_IMPLICIT_SETTER),
-
- check("""
+ """,
+ warnings: MessageKind.UNIMPLEMENTED_SETTER_ONE,
+ infos: MessageKind.UNIMPLEMENTED_IMPLICIT_SETTER),
+ check(
+ """
class A {
var field; // testAbstractMethod:40
}
class Class implements A {
final field = 0; // testAbstractMethod:41
}
- """, warnings: MessageKind.UNIMPLEMENTED_SETTER_ONE,
- infos: MessageKind.UNIMPLEMENTED_IMPLICIT_SETTER),
-
- check("""
+ """,
+ warnings: MessageKind.UNIMPLEMENTED_SETTER_ONE,
+ infos: MessageKind.UNIMPLEMENTED_IMPLICIT_SETTER),
+ check(
+ """
class A {
var member; // testAbstractMethod:42
}
class Class implements A {
set member(_) {}
}
- """, warnings: MessageKind.UNIMPLEMENTED_GETTER_ONE,
- infos: MessageKind.UNIMPLEMENTED_IMPLICIT_GETTER),
-
+ """,
+ warnings: MessageKind.UNIMPLEMENTED_GETTER_ONE,
+ infos: MessageKind.UNIMPLEMENTED_IMPLICIT_GETTER),
check("""
abstract class A {
method() {} // testAbstractMethod:43
@@ -1440,61 +1585,62 @@
Future testNoSuchMethod() {
return Future.wait([
- check("""
+ check(
+ """
class Class {
method(); // testNoSuchMethod:1
}
- """, warnings: MessageKind.ABSTRACT_METHOD,
- infos: []),
-
- check("""
+ """,
+ warnings: MessageKind.ABSTRACT_METHOD,
+ infos: []),
+ check(
+ """
@proxy
class Class {
method(); // testNoSuchMethod:2
}
- """, warnings: MessageKind.ABSTRACT_METHOD,
- infos: []),
-
+ """,
+ warnings: MessageKind.ABSTRACT_METHOD,
+ infos: []),
check("""
class Class {
noSuchMethod(_) => null;
method(); // testNoSuchMethod:3
}
"""),
-
check("""
class Class {
noSuchMethod(_, [__]) => null;
method(); // testNoSuchMethod:4
}
"""),
-
check("""
class Class {
noSuchMethod(_);
method(); // testNoSuchMethod:5
}
"""),
-
- check("""
+ check(
+ """
abstract class A {
method(); // testNoSuchMethod:6
}
class Class extends A {
}
- """, warnings: MessageKind.UNIMPLEMENTED_METHOD_ONE,
- infos: MessageKind.UNIMPLEMENTED_METHOD_CONT),
-
- check("""
+ """,
+ warnings: MessageKind.UNIMPLEMENTED_METHOD_ONE,
+ infos: MessageKind.UNIMPLEMENTED_METHOD_CONT),
+ check(
+ """
abstract class A {
method(); // testNoSuchMethod:7
}
@proxy
class Class extends A {
}
- """, warnings: MessageKind.UNIMPLEMENTED_METHOD_ONE,
- infos: MessageKind.UNIMPLEMENTED_METHOD_CONT),
-
+ """,
+ warnings: MessageKind.UNIMPLEMENTED_METHOD_ONE,
+ infos: MessageKind.UNIMPLEMENTED_METHOD_CONT),
check("""
abstract class A {
method(); // testNoSuchMethod:8
@@ -1503,35 +1649,37 @@
noSuchMethod(_) => null;
}
"""),
-
- check("""
+ check(
+ """
class A {
method() {} // testNoSuchMethod:9
}
class Class implements A {
}
- """, warnings: MessageKind.UNIMPLEMENTED_METHOD_ONE,
- infos: MessageKind.UNIMPLEMENTED_METHOD_CONT),
-
- check("""
+ """,
+ warnings: MessageKind.UNIMPLEMENTED_METHOD_ONE,
+ infos: MessageKind.UNIMPLEMENTED_METHOD_CONT),
+ check(
+ """
class A {
method() {} // testNoSuchMethod:10
}
class Class implements A {
}
- """, warnings: MessageKind.UNIMPLEMENTED_METHOD_ONE,
- infos: MessageKind.UNIMPLEMENTED_METHOD_CONT),
-
- check("""
+ """,
+ warnings: MessageKind.UNIMPLEMENTED_METHOD_ONE,
+ infos: MessageKind.UNIMPLEMENTED_METHOD_CONT),
+ check(
+ """
class A {
method() {} // testNoSuchMethod:11
}
@proxy
class Class implements A {
}
- """, warnings: MessageKind.UNIMPLEMENTED_METHOD_ONE,
- infos: MessageKind.UNIMPLEMENTED_METHOD_CONT),
-
+ """,
+ warnings: MessageKind.UNIMPLEMENTED_METHOD_ONE,
+ infos: MessageKind.UNIMPLEMENTED_METHOD_CONT),
check("""
class A {
method() {} // testNoSuchMethod:12
@@ -1540,7 +1688,6 @@
noSuchMethod(_) => null;
}
"""),
-
check("""
class A {
noSuchMethod(_) => null;
diff --git a/tests/compiler/dart2js/package_root_test.dart b/tests/compiler/dart2js/package_root_test.dart
index 40cab4a..20428dd 100644
--- a/tests/compiler/dart2js/package_root_test.dart
+++ b/tests/compiler/dart2js/package_root_test.dart
@@ -11,9 +11,8 @@
import 'package:async_helper/async_helper.dart';
import 'package:expect/expect.dart';
import 'package:compiler/compiler.dart'
- show DiagnosticHandler, Diagnostic, PackagesDiscoveryProvider;
-import 'package:compiler/src/diagnostics/messages.dart'
- show MessageKind;
+ show DiagnosticHandler, Diagnostic, PackagesDiscoveryProvider;
+import 'package:compiler/src/diagnostics/messages.dart' show MessageKind;
import 'package:package_config/packages.dart';
import 'memory_compiler.dart';
@@ -32,11 +31,10 @@
final Uri PACKAGE_CONFIG_URI = Uri.parse('memory:package.config');
-Future runTest(Uri main,
- MessageKind expectedMessageKind,
- {Uri packageRoot,
- Uri packageConfig,
- PackagesDiscoveryProvider packagesDiscoveryProvider}) async {
+Future runTest(Uri main, MessageKind expectedMessageKind,
+ {Uri packageRoot,
+ Uri packageConfig,
+ PackagesDiscoveryProvider packagesDiscoveryProvider}) async {
DiagnosticCollector collector = new DiagnosticCollector();
await runCompiler(
entryPoint: main,
@@ -45,8 +43,8 @@
packageRoot: packageRoot,
packageConfig: packageConfig,
packagesDiscoveryProvider: packagesDiscoveryProvider);
- Expect.equals(1, collector.errors.length,
- "Unexpected errors: ${collector.errors}");
+ Expect.equals(
+ 1, collector.errors.length, "Unexpected errors: ${collector.errors}");
Expect.equals(expectedMessageKind, collector.errors.first.message.kind,
"Unexpected error: ${collector.errors.first}");
}
@@ -60,30 +58,21 @@
return new Future.value(Packages.noPackages);
};
- await runTest(
- Uri.parse('memory:main.dart'),
- MessageKind.READ_SCRIPT_ERROR,
+ await runTest(Uri.parse('memory:main.dart'), MessageKind.READ_SCRIPT_ERROR,
packageRoot: packageRoot);
- await runTest(
- Uri.parse('memory:main.dart'),
- MessageKind.LIBRARY_NOT_FOUND,
+ await runTest(Uri.parse('memory:main.dart'), MessageKind.LIBRARY_NOT_FOUND,
packageConfig: PACKAGE_CONFIG_URI);
- await runTest(
- Uri.parse('memory:main.dart'),
- MessageKind.LIBRARY_NOT_FOUND,
+ await runTest(Uri.parse('memory:main.dart'), MessageKind.LIBRARY_NOT_FOUND,
packagesDiscoveryProvider: noPackagesDiscovery);
await runTest(
- Uri.parse('package:foo/foo.dart'),
- MessageKind.READ_SELF_ERROR,
+ Uri.parse('package:foo/foo.dart'), MessageKind.READ_SELF_ERROR,
packageRoot: packageRoot);
await runTest(
- Uri.parse('package:foo/foo.dart'),
- MessageKind.LIBRARY_NOT_FOUND,
+ Uri.parse('package:foo/foo.dart'), MessageKind.LIBRARY_NOT_FOUND,
packageConfig: PACKAGE_CONFIG_URI);
await runTest(
- Uri.parse('package:foo/foo.dart'),
- MessageKind.LIBRARY_NOT_FOUND,
+ Uri.parse('package:foo/foo.dart'), MessageKind.LIBRARY_NOT_FOUND,
packagesDiscoveryProvider: noPackagesDiscovery);
});
}
diff --git a/tests/compiler/dart2js/parameter_phi_elimination_test.dart b/tests/compiler/dart2js/parameter_phi_elimination_test.dart
index 6268037..a60d874 100644
--- a/tests/compiler/dart2js/parameter_phi_elimination_test.dart
+++ b/tests/compiler/dart2js/parameter_phi_elimination_test.dart
@@ -17,7 +17,6 @@
}
""";
-
main() {
compile(SOURCE, entry: "baz");
}
diff --git a/tests/compiler/dart2js/parser_helper.dart b/tests/compiler/dart2js/parser_helper.dart
index 48ab2c4..4ed194b 100644
--- a/tests/compiler/dart2js/parser_helper.dart
+++ b/tests/compiler/dart2js/parser_helper.dart
@@ -56,15 +56,13 @@
throw 'unsupported operation';
}
- void reportError(
- DiagnosticMessage message,
+ void reportError(DiagnosticMessage message,
[List<DiagnosticMessage> infos = const <DiagnosticMessage>[]]) {
log(message);
infos.forEach(log);
}
- void reportWarning(
- DiagnosticMessage message,
+ void reportWarning(DiagnosticMessage message,
[List<DiagnosticMessage> infos = const <DiagnosticMessage>[]]) {
log(message);
infos.forEach(log);
@@ -75,8 +73,7 @@
log(new Message(MessageTemplate.TEMPLATES[errorCode], arguments, false));
}
- void reportHint(
- DiagnosticMessage message,
+ void reportHint(DiagnosticMessage message,
[List<DiagnosticMessage> infos = const <DiagnosticMessage>[]]) {
log(message);
infos.forEach(log);
@@ -85,12 +82,9 @@
withCurrentElement(Element element, f()) => f();
@override
- DiagnosticMessage createMessage(
- Spannable spannable,
- MessageKind messageKind,
+ DiagnosticMessage createMessage(Spannable spannable, MessageKind messageKind,
[Map arguments = const {}]) {
- return new DiagnosticMessage(
- null, spannable,
+ return new DiagnosticMessage(null, spannable,
new Message(MessageTemplate.TEMPLATES[messageKind], arguments, false));
}
@@ -98,20 +92,19 @@
bool get hasReportedError => false;
}
-Token scan(String text) =>
- new StringScanner.fromString(text)
- .tokenize();
+Token scan(String text) => new StringScanner.fromString(text).tokenize();
Node parseBodyCode(String text, Function parseMethod,
- {DiagnosticReporter reporter}) {
+ {DiagnosticReporter reporter}) {
Token tokens = scan(text);
if (reporter == null) reporter = new LoggerCanceler();
Uri uri = new Uri(scheme: "source");
- Script script = new Script(uri, uri,new MockFile(text));
+ Script script = new Script(uri, uri, new MockFile(text));
LibraryElement library = new LibraryElementX(script);
NodeListener listener = new NodeListener(
new ScannerOptions(canUseNative: true),
- reporter, library.entryCompilationUnit);
+ reporter,
+ library.entryCompilationUnit);
Parser parser = new Parser(listener, new MockParserOptions());
Token endToken = parseMethod(parser, tokens);
assert(endToken.kind == EOF_TOKEN);
@@ -122,7 +115,7 @@
}
Node parseStatement(String text) =>
- parseBodyCode(text, (parser, tokens) => parser.parseStatement(tokens));
+ parseBodyCode(text, (parser, tokens) => parser.parseStatement(tokens));
Node parseFunction(String text, Compiler compiler) {
ElementX element = parseUnit(text, compiler, compiler.mainApp).head;
@@ -132,22 +125,18 @@
}
Node parseMember(String text, {DiagnosticReporter reporter}) {
- return parseBodyCode(
- text,
- (parser, tokens) => parser.parseMember(tokens),
+ return parseBodyCode(text, (parser, tokens) => parser.parseMember(tokens),
reporter: reporter);
}
class MockFile extends StringSourceFile {
- MockFile(text)
- : super.fromName('<string>', text);
+ MockFile(text) : super.fromName('<string>', text);
}
var sourceCounter = 0;
-Link<Element> parseUnit(String text, Compiler compiler,
- LibraryElement library,
- [void registerSource(Uri uri, String source)]) {
+Link<Element> parseUnit(String text, Compiler compiler, LibraryElement library,
+ [void registerSource(Uri uri, String source)]) {
Token tokens = scan(text);
Uri uri = new Uri(scheme: "source", path: '${++sourceCounter}');
if (registerSource != null) {
@@ -158,15 +147,15 @@
DiagnosticReporter reporter = compiler.reporter;
ElementListener listener = new ElementListener(
compiler.parsingContext.getScannerOptionsFor(library),
- reporter, unit, new IdGenerator());
+ reporter,
+ unit,
+ new IdGenerator());
PartialParser parser = new PartialParser(listener, new MockParserOptions());
reporter.withCurrentElement(unit, () => parser.parseUnit(tokens));
return unit.localMembers;
}
NodeList fullParseUnit(String source, {DiagnosticReporter reporter}) {
- return parseBodyCode(
- source,
- (parser, tokens) => parser.parseUnit(tokens),
+ return parseBodyCode(source, (parser, tokens) => parser.parseUnit(tokens),
reporter: reporter);
}
diff --git a/tests/compiler/dart2js/parser_test.dart b/tests/compiler/dart2js/parser_test.dart
index 762d074..0487450 100644
--- a/tests/compiler/dart2js/parser_test.dart
+++ b/tests/compiler/dart2js/parser_test.dart
@@ -304,8 +304,7 @@
throw this;
}
- void reportError(
- DiagnosticMessage message,
+ void reportError(DiagnosticMessage message,
[List<DiagnosticMessage> infos = const <DiagnosticMessage>[]]) {
reportFatalError(message.spannable);
}
@@ -319,24 +318,25 @@
}
@override
- DiagnosticMessage createMessage(
- spannable, messageKind, [arguments = const {}]) {
+ DiagnosticMessage createMessage(spannable, messageKind,
+ [arguments = const {}]) {
return new DiagnosticMessage(null, spannable, null);
}
}
void testMissingCloseParen() {
- final String source =
-'''foo(x { // <= missing closing ")"
+ final String source = '''foo(x { // <= missing closing ")"
return x;
}''';
parse() {
parseMember(source, reporter: new Collector());
}
+
check(Collector c) {
Expect.equals(OPEN_CURLY_BRACKET_TOKEN, c.token);
return true;
}
+
Expect.throws(parse, check);
}
@@ -345,10 +345,12 @@
parse() {
fullParseUnit(source, reporter: new Collector());
}
+
check(Collector c) {
Expect.equals(BAD_INPUT_TOKEN, c.token);
return true;
}
+
Expect.throws(parse, check);
}
@@ -357,10 +359,12 @@
parse() {
fullParseUnit(source, reporter: new Collector());
}
+
check(Collector c) {
Expect.equals(LT_TOKEN, c.token);
return true;
}
+
Expect.throws(parse, check);
}
diff --git a/tests/compiler/dart2js/part_of_test.dart b/tests/compiler/dart2js/part_of_test.dart
index 3a134dc..d2e81d8 100644
--- a/tests/compiler/dart2js/part_of_test.dart
+++ b/tests/compiler/dart2js/part_of_test.dart
@@ -6,8 +6,7 @@
import "package:expect/expect.dart";
import "package:async_helper/async_helper.dart";
-import 'package:compiler/src/diagnostics/messages.dart' show
- MessageKind;
+import 'package:compiler/src/diagnostics/messages.dart' show MessageKind;
import 'mock_compiler.dart';
final libraryUri = Uri.parse('test:library.dart');
@@ -27,14 +26,16 @@
compiler.registerSource(partUri, PART_SOURCE);
asyncTest(() => compiler.libraryLoader.loadLibrary(libraryUri).then((_) {
- DiagnosticCollector collector = compiler.diagnosticCollector;
- print('errors: ${collector.errors}');
- print('warnings: ${collector.warnings}');
- Expect.isTrue(collector.errors.isEmpty);
- Expect.equals(1, collector.warnings.length);
- Expect.equals(MessageKind.LIBRARY_NAME_MISMATCH,
- collector.warnings.first.messageKind);
- Expect.equals('foo',
- collector.warnings.first.message.arguments['libraryName'].toString());
- }));
+ DiagnosticCollector collector = compiler.diagnosticCollector;
+ print('errors: ${collector.errors}');
+ print('warnings: ${collector.warnings}');
+ Expect.isTrue(collector.errors.isEmpty);
+ Expect.equals(1, collector.warnings.length);
+ Expect.equals(MessageKind.LIBRARY_NAME_MISMATCH,
+ collector.warnings.first.messageKind);
+ Expect.equals(
+ 'foo',
+ collector.warnings.first.message.arguments['libraryName']
+ .toString());
+ }));
}
diff --git a/tests/compiler/dart2js/patch_test.dart b/tests/compiler/dart2js/patch_test.dart
index 00245a7..f981843 100644
--- a/tests/compiler/dart2js/patch_test.dart
+++ b/tests/compiler/dart2js/patch_test.dart
@@ -6,32 +6,30 @@
import 'package:expect/expect.dart';
import 'package:async_helper/async_helper.dart';
import 'package:compiler/src/compiler.dart';
-import 'package:compiler/src/diagnostics/messages.dart' show
- MessageKind;
+import 'package:compiler/src/diagnostics/messages.dart' show MessageKind;
import 'package:compiler/src/elements/elements.dart';
import 'package:compiler/src/elements/modelx.dart';
import 'package:compiler/src/tree/tree.dart';
import 'package:compiler/src/types/types.dart';
-import 'package:compiler/src/universe/call_structure.dart' show
- CallStructure;
-import 'package:compiler/src/universe/selector.dart' show
- Selector;
+import 'package:compiler/src/universe/call_structure.dart' show CallStructure;
+import 'package:compiler/src/universe/selector.dart' show Selector;
import 'package:compiler/src/world.dart';
import 'mock_compiler.dart';
import 'mock_libraries.dart';
Future<Compiler> applyPatch(String script, String patch,
- {bool analyzeAll: false,
- bool analyzeOnly: false,
- bool runCompiler: false,
- String main: "",
- String patchVersion}) {
+ {bool analyzeAll: false,
+ bool analyzeOnly: false,
+ bool runCompiler: false,
+ String main: "",
+ String patchVersion}) {
Map<String, String> core = <String, String>{'script': script};
- MockCompiler compiler = new MockCompiler.internal(coreSource: core,
- analyzeAll: analyzeAll,
- analyzeOnly: analyzeOnly,
- patchVersion: patchVersion);
+ MockCompiler compiler = new MockCompiler.internal(
+ coreSource: core,
+ analyzeAll: analyzeAll,
+ analyzeOnly: analyzeOnly,
+ patchVersion: patchVersion);
compiler.diagnosticHandler = createHandler(compiler, '');
var uri = Uri.parse("patch:core");
compiler.registerSource(uri, "$DEFAULT_PATCH_CORE_SOURCE\n$patch");
@@ -45,30 +43,28 @@
}
void expectHasBody(compiler, ElementX element) {
- var node = element.parseNode(compiler.parsingContext);
- Expect.isNotNull(node, "Element isn't parseable, when a body was expected");
- Expect.isNotNull(node.body);
- // If the element has a body it is either a Block or a Return statement,
- // both with different begin and end tokens.
- Expect.isTrue(node.body is Block || node.body is Return);
- Expect.notEquals(node.body.getBeginToken(), node.body.getEndToken());
+ var node = element.parseNode(compiler.parsingContext);
+ Expect.isNotNull(node, "Element isn't parseable, when a body was expected");
+ Expect.isNotNull(node.body);
+ // If the element has a body it is either a Block or a Return statement,
+ // both with different begin and end tokens.
+ Expect.isTrue(node.body is Block || node.body is Return);
+ Expect.notEquals(node.body.getBeginToken(), node.body.getEndToken());
}
void expectHasNoBody(compiler, ElementX element) {
- var node = element.parseNode(compiler.parsingContext);
- Expect.isNotNull(node, "Element isn't parseable, when a body was expected");
- Expect.isFalse(node.hasBody);
+ var node = element.parseNode(compiler.parsingContext);
+ Expect.isNotNull(node, "Element isn't parseable, when a body was expected");
+ Expect.isFalse(node.hasBody);
}
-Element ensure(compiler,
- String name,
- Element lookup(name),
- {bool expectIsPatched: false,
- bool expectIsPatch: false,
- bool checkHasBody: false,
- bool expectIsGetter: false,
- bool expectIsFound: true,
- bool expectIsRegular: false}) {
+Element ensure(compiler, String name, Element lookup(name),
+ {bool expectIsPatched: false,
+ bool expectIsPatch: false,
+ bool checkHasBody: false,
+ bool expectIsGetter: false,
+ bool expectIsFound: true,
+ bool expectIsRegular: false}) {
var element = lookup(name);
if (!expectIsFound) {
Expect.isNull(element);
@@ -128,18 +124,17 @@
Future testPatchFunction() async {
var compiler = await applyPatch(
- "external test();",
- "@patch test() { return 'string'; } ");
+ "external test();", "@patch test() { return 'string'; } ");
ensure(compiler, "test", compiler.commonElements.coreLibrary.find,
- expectIsPatched: true, checkHasBody: true);
+ expectIsPatched: true, checkHasBody: true);
ensure(compiler, "test", compiler.commonElements.coreLibrary.patch.find,
- expectIsPatch: true, checkHasBody: true);
+ expectIsPatch: true, checkHasBody: true);
DiagnosticCollector collector = compiler.diagnosticCollector;
- Expect.isTrue(collector.warnings.isEmpty,
- "Unexpected warnings: ${collector.warnings}");
- Expect.isTrue(collector.errors.isEmpty,
- "Unexpected errors: ${collector.errors}");
+ Expect.isTrue(
+ collector.warnings.isEmpty, "Unexpected warnings: ${collector.warnings}");
+ Expect.isTrue(
+ collector.errors.isEmpty, "Unexpected errors: ${collector.errors}");
}
Future testPatchFunctionMetadata() async {
@@ -152,42 +147,40 @@
const _b = 1;
@patch @_b test() {}
""");
- Element origin = ensure(compiler, "test",
- compiler.commonElements.coreLibrary.find,
+ Element origin = ensure(
+ compiler, "test", compiler.commonElements.coreLibrary.find,
expectIsPatched: true, checkHasBody: true);
- Element patch = ensure(compiler, "test",
- compiler.commonElements.coreLibrary.patch.find,
+ Element patch = ensure(
+ compiler, "test", compiler.commonElements.coreLibrary.patch.find,
expectIsPatch: true, checkHasBody: true);
DiagnosticCollector collector = compiler.diagnosticCollector;
- Expect.isTrue(collector.warnings.isEmpty,
- "Unexpected warnings: ${collector.warnings}");
- Expect.isTrue(collector.errors.isEmpty,
- "Unexpected errors: ${collector.errors}");
+ Expect.isTrue(
+ collector.warnings.isEmpty, "Unexpected warnings: ${collector.warnings}");
+ Expect.isTrue(
+ collector.errors.isEmpty, "Unexpected errors: ${collector.errors}");
Expect.equals(1, origin.metadata.length,
- "Unexpected origin metadata: ${origin.metadata}.");
+ "Unexpected origin metadata: ${origin.metadata}.");
Expect.equals(3, patch.metadata.length,
- "Unexpected patch metadata: ${patch.metadata}.");
+ "Unexpected patch metadata: ${patch.metadata}.");
}
-
Future testPatchVersioned() async {
String fullPatch = "test(){return 'string';}";
String lazyPatch = "test(){return 'new and improved string';}";
- String patchSource =
- """
+ String patchSource = """
@patch_full $fullPatch
@patch_lazy $lazyPatch
""";
Future test(String patchVersion,
- {String patchText,
- bool expectIsPatched: true,
- String expectedError,
- String defaultPatch: '',
- String expectedInternalError}) async {
+ {String patchText,
+ bool expectIsPatched: true,
+ String expectedError,
+ String defaultPatch: '',
+ String expectedInternalError}) async {
return applyPatch(
"external test();",
"""
@@ -195,48 +188,48 @@
$patchSource
""",
patchVersion: patchVersion).then((compiler) {
- Element origin = ensure(compiler, "test",
- compiler.commonElements.coreLibrary.find,
- expectIsPatched: expectIsPatched, checkHasBody: true);
- if (expectIsPatched) {
- AstElement patch = ensure(compiler, "test",
- compiler.commonElements.coreLibrary.patch.find,
- expectIsPatch: true, checkHasBody: true);
- Expect.equals(origin.patch, patch);
- Expect.equals(patch.origin, origin);
- Expect.equals(patchText, patch.node.toString());
- }
+ Element origin = ensure(
+ compiler, "test", compiler.commonElements.coreLibrary.find,
+ expectIsPatched: expectIsPatched, checkHasBody: true);
+ if (expectIsPatched) {
+ AstElement patch = ensure(
+ compiler, "test", compiler.commonElements.coreLibrary.patch.find,
+ expectIsPatch: true, checkHasBody: true);
+ Expect.equals(origin.patch, patch);
+ Expect.equals(patch.origin, origin);
+ Expect.equals(patchText, patch.node.toString());
+ }
- compiler.analyzeElement(origin);
- compiler.enqueuer.resolution.emptyDeferredQueueForTesting();
+ compiler.analyzeElement(origin);
+ compiler.enqueuer.resolution.emptyDeferredQueueForTesting();
- DiagnosticCollector collector = compiler.diagnosticCollector;
- Expect.isTrue(collector.warnings.isEmpty,
- "Unexpected warnings: ${collector.warnings}");
- if (expectedError != null) {
- Expect.equals(expectedError,
- collector.errors.first.message.toString());
- } else {
- Expect.isTrue(collector.errors.isEmpty,
- "Unexpected errors: ${collector.errors}");
- }
- }).catchError((error) {
- if (expectedInternalError != null) {
- Expect.equals(
- 'Internal Error: $expectedInternalError', error.toString());
- } else {
- throw error;
- }
- });
+ DiagnosticCollector collector = compiler.diagnosticCollector;
+ Expect.isTrue(collector.warnings.isEmpty,
+ "Unexpected warnings: ${collector.warnings}");
+ if (expectedError != null) {
+ Expect.equals(expectedError, collector.errors.first.message.toString());
+ } else {
+ Expect.isTrue(
+ collector.errors.isEmpty, "Unexpected errors: ${collector.errors}");
+ }
+ }).catchError((error) {
+ if (expectedInternalError != null) {
+ Expect.equals(
+ 'Internal Error: $expectedInternalError', error.toString());
+ } else {
+ throw error;
+ }
+ });
}
await test('full', patchText: fullPatch);
await test('lazy', patchText: lazyPatch);
- await test('unknown', expectIsPatched: false,
- expectedError: 'External method without an implementation.');
+ await test('unknown',
+ expectIsPatched: false,
+ expectedError: 'External method without an implementation.');
await test('full',
- defaultPatch: "@patch test(){}",
- expectedInternalError: "Trying to patch a function more than once.");
+ defaultPatch: "@patch test(){}",
+ expectedInternalError: "Trying to patch a function more than once.");
}
Future testPatchConstructor() async {
@@ -251,30 +244,32 @@
@patch Class();
}
""");
- var classOrigin = ensure(compiler, "Class",
- compiler.commonElements.coreLibrary.find, expectIsPatched: true);
+ var classOrigin = ensure(
+ compiler, "Class", compiler.commonElements.coreLibrary.find,
+ expectIsPatched: true);
classOrigin.ensureResolved(compiler.resolution);
- var classPatch = ensure(compiler, "Class",
- compiler.commonElements.coreLibrary.patch.find, expectIsPatch: true);
+ var classPatch = ensure(
+ compiler, "Class", compiler.commonElements.coreLibrary.patch.find,
+ expectIsPatch: true);
Expect.equals(classPatch, classOrigin.patch);
Expect.equals(classOrigin, classPatch.origin);
- var constructorOrigin = ensure(compiler, "",
- (name) => classOrigin.localLookup(name),
- expectIsPatched: true);
- var constructorPatch = ensure(compiler, "",
- (name) => classPatch.localLookup(name),
- expectIsPatch: true);
+ var constructorOrigin = ensure(
+ compiler, "", (name) => classOrigin.localLookup(name),
+ expectIsPatched: true);
+ var constructorPatch = ensure(
+ compiler, "", (name) => classPatch.localLookup(name),
+ expectIsPatch: true);
Expect.equals(constructorPatch, constructorOrigin.patch);
Expect.equals(constructorOrigin, constructorPatch.origin);
DiagnosticCollector collector = compiler.diagnosticCollector;
- Expect.isTrue(collector.warnings.isEmpty,
- "Unexpected warnings: ${collector.warnings}");
- Expect.isTrue(collector.errors.isEmpty,
- "Unexpected errors: ${collector.errors}");
+ Expect.isTrue(
+ collector.warnings.isEmpty, "Unexpected warnings: ${collector.warnings}");
+ Expect.isTrue(
+ collector.errors.isEmpty, "Unexpected errors: ${collector.errors}");
}
Future testPatchRedirectingConstructor() async {
@@ -291,37 +286,36 @@
@patch Class._(x, y) { print('$x,$y'); }
}
""");
- var classOrigin = ensure(compiler, "Class",
- compiler.commonElements.coreLibrary.find, expectIsPatched: true);
+ var classOrigin = ensure(
+ compiler, "Class", compiler.commonElements.coreLibrary.find,
+ expectIsPatched: true);
classOrigin.ensureResolved(compiler.resolution);
- var classPatch = ensure(compiler, "Class",
- compiler.commonElements.coreLibrary.patch.find, expectIsPatch: true);
+ var classPatch = ensure(
+ compiler, "Class", compiler.commonElements.coreLibrary.patch.find,
+ expectIsPatch: true);
Expect.equals(classOrigin, classPatch.origin);
Expect.equals(classPatch, classOrigin.patch);
var constructorRedirecting =
- ensure(compiler, "",
- (name) => classOrigin.localLookup(name));
- var constructorOrigin =
- ensure(compiler, "_",
- (name) => classOrigin.localLookup(name),
- expectIsPatched: true);
- var constructorPatch =
- ensure(compiler, "_",
- (name) => classPatch.localLookup(name),
- expectIsPatch: true);
+ ensure(compiler, "", (name) => classOrigin.localLookup(name));
+ var constructorOrigin = ensure(
+ compiler, "_", (name) => classOrigin.localLookup(name),
+ expectIsPatched: true);
+ var constructorPatch = ensure(
+ compiler, "_", (name) => classPatch.localLookup(name),
+ expectIsPatch: true);
Expect.equals(constructorOrigin, constructorPatch.origin);
Expect.equals(constructorPatch, constructorOrigin.patch);
compiler.resolver.resolve(constructorRedirecting);
DiagnosticCollector collector = compiler.diagnosticCollector;
- Expect.isTrue(collector.warnings.isEmpty,
- "Unexpected warnings: ${collector.warnings}");
- Expect.isTrue(collector.errors.isEmpty,
- "Unexpected errors: ${collector.errors}");
+ Expect.isTrue(
+ collector.warnings.isEmpty, "Unexpected warnings: ${collector.warnings}");
+ Expect.isTrue(
+ collector.errors.isEmpty, "Unexpected errors: ${collector.errors}");
}
Future testPatchMember() async {
@@ -336,22 +330,23 @@
@patch String toString() => 'string';
}
""");
- var container = ensure(compiler, "Class",
- compiler.commonElements.coreLibrary.find, expectIsPatched: true);
+ var container = ensure(
+ compiler, "Class", compiler.commonElements.coreLibrary.find,
+ expectIsPatched: true);
container.parseNode(compiler.parsingContext);
ensure(compiler, "Class", compiler.commonElements.coreLibrary.patch.find,
- expectIsPatch: true);
+ expectIsPatch: true);
ensure(compiler, "toString", container.lookupLocalMember,
- expectIsPatched: true, checkHasBody: true);
+ expectIsPatched: true, checkHasBody: true);
ensure(compiler, "toString", container.patch.lookupLocalMember,
- expectIsPatch: true, checkHasBody: true);
+ expectIsPatch: true, checkHasBody: true);
DiagnosticCollector collector = compiler.diagnosticCollector;
- Expect.isTrue(collector.warnings.isEmpty,
- "Unexpected warnings: ${collector.warnings}");
- Expect.isTrue(collector.errors.isEmpty,
- "Unexpected errors: ${collector.errors}");
+ Expect.isTrue(
+ collector.warnings.isEmpty, "Unexpected warnings: ${collector.warnings}");
+ Expect.isTrue(
+ collector.errors.isEmpty, "Unexpected errors: ${collector.errors}");
}
Future testPatchGetter() async {
@@ -366,27 +361,20 @@
@patch int get field => 5;
}
""");
- var container = ensure(compiler, "Class",
- compiler.commonElements.coreLibrary.find, expectIsPatched: true);
+ var container = ensure(
+ compiler, "Class", compiler.commonElements.coreLibrary.find,
+ expectIsPatched: true);
container.parseNode(compiler.parsingContext);
- ensure(compiler,
- "field",
- container.lookupLocalMember,
- expectIsGetter: true,
- expectIsPatched: true,
- checkHasBody: true);
- ensure(compiler,
- "field",
- container.patch.lookupLocalMember,
- expectIsGetter: true,
- expectIsPatch: true,
- checkHasBody: true);
+ ensure(compiler, "field", container.lookupLocalMember,
+ expectIsGetter: true, expectIsPatched: true, checkHasBody: true);
+ ensure(compiler, "field", container.patch.lookupLocalMember,
+ expectIsGetter: true, expectIsPatch: true, checkHasBody: true);
DiagnosticCollector collector = compiler.diagnosticCollector;
- Expect.isTrue(collector.warnings.isEmpty,
- "Unexpected warnings: ${collector.warnings}");
- Expect.isTrue(collector.errors.isEmpty,
- "Unexpected errors: ${collector.errors}");
+ Expect.isTrue(
+ collector.warnings.isEmpty, "Unexpected warnings: ${collector.warnings}");
+ Expect.isTrue(
+ collector.errors.isEmpty, "Unexpected errors: ${collector.errors}");
}
Future testRegularMember() async {
@@ -400,22 +388,23 @@
@patch class Class {
}
""");
- var container = ensure(compiler, "Class",
- compiler.commonElements.coreLibrary.find, expectIsPatched: true);
+ var container = ensure(
+ compiler, "Class", compiler.commonElements.coreLibrary.find,
+ expectIsPatched: true);
container.parseNode(compiler.parsingContext);
ensure(compiler, "Class", compiler.commonElements.coreLibrary.patch.find,
- expectIsPatch: true);
+ expectIsPatch: true);
ensure(compiler, "regular", container.lookupLocalMember,
- checkHasBody: true, expectIsRegular: true);
+ checkHasBody: true, expectIsRegular: true);
ensure(compiler, "regular", container.patch.lookupLocalMember,
- checkHasBody: true, expectIsRegular: true);
+ checkHasBody: true, expectIsRegular: true);
DiagnosticCollector collector = compiler.diagnosticCollector;
- Expect.isTrue(collector.warnings.isEmpty,
- "Unexpected warnings: ${collector.warnings}");
- Expect.isTrue(collector.errors.isEmpty,
- "Unexpected errors: ${collector.errors}");
+ Expect.isTrue(
+ collector.warnings.isEmpty, "Unexpected warnings: ${collector.warnings}");
+ Expect.isTrue(
+ collector.errors.isEmpty, "Unexpected errors: ${collector.errors}");
}
Future testInjectedMember() async {
@@ -429,22 +418,23 @@
void _injected() {}
}
""");
- var container = ensure(compiler, "Class",
- compiler.commonElements.coreLibrary.find, expectIsPatched: true);
+ var container = ensure(
+ compiler, "Class", compiler.commonElements.coreLibrary.find,
+ expectIsPatched: true);
container.parseNode(compiler.parsingContext);
ensure(compiler, "Class", compiler.commonElements.coreLibrary.patch.find,
- expectIsPatch: true);
+ expectIsPatch: true);
ensure(compiler, "_injected", container.lookupLocalMember,
- expectIsFound: false);
+ expectIsFound: false);
ensure(compiler, "_injected", container.patch.lookupLocalMember,
- checkHasBody: true, expectIsRegular: true);
+ checkHasBody: true, expectIsRegular: true);
DiagnosticCollector collector = compiler.diagnosticCollector;
- Expect.isTrue(collector.warnings.isEmpty,
- "Unexpected warnings: ${collector.warnings}");
- Expect.isTrue(collector.errors.isEmpty,
- "Unexpected errors: ${collector.errors}");
+ Expect.isTrue(
+ collector.warnings.isEmpty, "Unexpected warnings: ${collector.warnings}");
+ Expect.isTrue(
+ collector.errors.isEmpty, "Unexpected errors: ${collector.errors}");
}
Future testInjectedPublicMember() async {
@@ -458,68 +448,55 @@
void injected() {}
}
""");
- var container = ensure(compiler, "Class",
- compiler.commonElements.coreLibrary.find, expectIsPatched: true);
+ var container = ensure(
+ compiler, "Class", compiler.commonElements.coreLibrary.find,
+ expectIsPatched: true);
container.parseNode(compiler.parsingContext);
ensure(compiler, "Class", compiler.commonElements.coreLibrary.patch.find,
- expectIsPatch: true);
+ expectIsPatch: true);
ensure(compiler, "injected", container.lookupLocalMember,
- expectIsFound: false);
+ expectIsFound: false);
ensure(compiler, "injected", container.patch.lookupLocalMember,
- checkHasBody: true, expectIsRegular: true);
+ checkHasBody: true, expectIsRegular: true);
DiagnosticCollector collector = compiler.diagnosticCollector;
- Expect.isTrue(collector.warnings.isEmpty,
- "Unexpected warnings: ${collector.warnings}");
- Expect.equals(1, collector.errors.length,
- "Unexpected errors: ${collector.errors}");
Expect.isTrue(
- collector.errors.first.message.kind ==
- MessageKind.INJECTED_PUBLIC_MEMBER);
+ collector.warnings.isEmpty, "Unexpected warnings: ${collector.warnings}");
+ Expect.equals(
+ 1, collector.errors.length, "Unexpected errors: ${collector.errors}");
+ Expect.isTrue(collector.errors.first.message.kind ==
+ MessageKind.INJECTED_PUBLIC_MEMBER);
}
Future testInjectedFunction() async {
- var compiler = await applyPatch(
- "",
- "int _function() => 5;");
- ensure(compiler,
- "_function",
- compiler.commonElements.coreLibrary.find,
- expectIsFound: false);
- ensure(compiler,
- "_function",
- compiler.commonElements.coreLibrary.patch.find,
- checkHasBody: true, expectIsRegular: true);
+ var compiler = await applyPatch("", "int _function() => 5;");
+ ensure(compiler, "_function", compiler.commonElements.coreLibrary.find,
+ expectIsFound: false);
+ ensure(compiler, "_function", compiler.commonElements.coreLibrary.patch.find,
+ checkHasBody: true, expectIsRegular: true);
DiagnosticCollector collector = compiler.diagnosticCollector;
- Expect.isTrue(collector.warnings.isEmpty,
- "Unexpected warnings: ${collector.warnings}");
- Expect.isTrue(collector.errors.isEmpty,
- "Unexpected errors: ${collector.errors}");
+ Expect.isTrue(
+ collector.warnings.isEmpty, "Unexpected warnings: ${collector.warnings}");
+ Expect.isTrue(
+ collector.errors.isEmpty, "Unexpected errors: ${collector.errors}");
}
Future testInjectedPublicFunction() async {
- var compiler = await applyPatch(
- "",
- "int function() => 5;");
- ensure(compiler,
- "function",
- compiler.commonElements.coreLibrary.find,
- expectIsFound: false);
- ensure(compiler,
- "function",
- compiler.commonElements.coreLibrary.patch.find,
- checkHasBody: true, expectIsRegular: true);
+ var compiler = await applyPatch("", "int function() => 5;");
+ ensure(compiler, "function", compiler.commonElements.coreLibrary.find,
+ expectIsFound: false);
+ ensure(compiler, "function", compiler.commonElements.coreLibrary.patch.find,
+ checkHasBody: true, expectIsRegular: true);
DiagnosticCollector collector = compiler.diagnosticCollector;
- Expect.isTrue(collector.warnings.isEmpty,
- "Unexpected warnings: ${collector.warnings}");
- Expect.equals(1, collector.errors.length,
- "Unexpected errors: ${collector.errors}");
Expect.isTrue(
- collector.errors.first.message.kind ==
- MessageKind.INJECTED_PUBLIC_MEMBER);
+ collector.warnings.isEmpty, "Unexpected warnings: ${collector.warnings}");
+ Expect.equals(
+ 1, collector.errors.length, "Unexpected errors: ${collector.errors}");
+ Expect.isTrue(collector.errors.first.message.kind ==
+ MessageKind.INJECTED_PUBLIC_MEMBER);
}
Future testPatchSignatureCheck() async {
@@ -554,51 +531,48 @@
@patch void method11({int str}) {}
}
""");
- var container = ensure(compiler, "Class",
- compiler.commonElements.coreLibrary.find, expectIsPatched: true);
+ var container = ensure(
+ compiler, "Class", compiler.commonElements.coreLibrary.find,
+ expectIsPatched: true);
container.ensureResolved(compiler.resolution);
container.parseNode(compiler.parsingContext);
DiagnosticCollector collector = compiler.diagnosticCollector;
void expect(String methodName, List infos, List errors) {
collector.clear();
- compiler.resolver.resolveMethodElement(
- ensure(compiler, methodName, container.lookupLocalMember,
- expectIsPatched: true, checkHasBody: true));
+ compiler.resolver.resolveMethodElement(ensure(
+ compiler, methodName, container.lookupLocalMember,
+ expectIsPatched: true, checkHasBody: true));
Expect.equals(0, collector.warnings.length);
Expect.equals(infos.length, collector.infos.length,
- "Unexpected infos: ${collector.infos} on $methodName");
- for (int i = 0 ; i < infos.length ; i++) {
+ "Unexpected infos: ${collector.infos} on $methodName");
+ for (int i = 0; i < infos.length; i++) {
Expect.equals(infos[i], collector.infos.elementAt(i).message.kind);
}
Expect.equals(errors.length, collector.errors.length,
- "Unexpected errors: ${collector.errors} on $methodName");
- for (int i = 0 ; i < errors.length ; i++) {
+ "Unexpected errors: ${collector.errors} on $methodName");
+ for (int i = 0; i < errors.length; i++) {
Expect.equals(errors[i], collector.errors.elementAt(i).message.kind);
}
}
expect("method1", [], [MessageKind.PATCH_RETURN_TYPE_MISMATCH]);
- expect("method2", [],
- [MessageKind.PATCH_REQUIRED_PARAMETER_COUNT_MISMATCH]);
+ expect("method2", [], [MessageKind.PATCH_REQUIRED_PARAMETER_COUNT_MISMATCH]);
expect("method3", [MessageKind.PATCH_POINT_TO_PARAMETER],
- [MessageKind.PATCH_PARAMETER_MISMATCH]);
- expect("method4", [],
- [MessageKind.PATCH_OPTIONAL_PARAMETER_COUNT_MISMATCH]);
- expect("method5", [],
- [MessageKind.PATCH_OPTIONAL_PARAMETER_COUNT_MISMATCH]);
- expect("method6", [],
- [MessageKind.PATCH_OPTIONAL_PARAMETER_NAMED_MISMATCH]);
+ [MessageKind.PATCH_PARAMETER_MISMATCH]);
+ expect("method4", [], [MessageKind.PATCH_OPTIONAL_PARAMETER_COUNT_MISMATCH]);
+ expect("method5", [], [MessageKind.PATCH_OPTIONAL_PARAMETER_COUNT_MISMATCH]);
+ expect("method6", [], [MessageKind.PATCH_OPTIONAL_PARAMETER_NAMED_MISMATCH]);
expect("method7", [MessageKind.PATCH_POINT_TO_PARAMETER],
- [MessageKind.PATCH_PARAMETER_MISMATCH]);
+ [MessageKind.PATCH_PARAMETER_MISMATCH]);
expect("method8", [MessageKind.PATCH_POINT_TO_PARAMETER],
- [MessageKind.PATCH_PARAMETER_MISMATCH]);
+ [MessageKind.PATCH_PARAMETER_MISMATCH]);
expect("method9", [MessageKind.PATCH_POINT_TO_PARAMETER],
- [MessageKind.PATCH_PARAMETER_TYPE_MISMATCH]);
+ [MessageKind.PATCH_PARAMETER_TYPE_MISMATCH]);
expect("method10", [MessageKind.PATCH_POINT_TO_PARAMETER],
- [MessageKind.PATCH_PARAMETER_TYPE_MISMATCH]);
+ [MessageKind.PATCH_PARAMETER_TYPE_MISMATCH]);
expect("method11", [MessageKind.PATCH_POINT_TO_PARAMETER],
- [MessageKind.PATCH_PARAMETER_TYPE_MISMATCH]);
+ [MessageKind.PATCH_PARAMETER_TYPE_MISMATCH]);
}
Future testExternalWithoutImplementationTopLevel() async {
@@ -609,19 +583,18 @@
"""
// @patch void foo() {}
""");
- var function = ensure(compiler, "foo",
- compiler.commonElements.coreLibrary.find);
+ var function =
+ ensure(compiler, "foo", compiler.commonElements.coreLibrary.find);
compiler.resolver.resolve(function);
DiagnosticCollector collector = compiler.diagnosticCollector;
- Expect.isTrue(collector.warnings.isEmpty,
- "Unexpected warnings: ${collector.warnings}");
+ Expect.isTrue(
+ collector.warnings.isEmpty, "Unexpected warnings: ${collector.warnings}");
print('testExternalWithoutImplementationTopLevel:${collector.errors}');
Expect.equals(1, collector.errors.length);
- Expect.isTrue(
- collector.errors.first.message.kind ==
- MessageKind.PATCH_EXTERNAL_WITHOUT_IMPLEMENTATION);
+ Expect.isTrue(collector.errors.first.message.kind ==
+ MessageKind.PATCH_EXTERNAL_WITHOUT_IMPLEMENTATION);
Expect.stringEquals('External method without an implementation.',
- collector.errors.first.message.toString());
+ collector.errors.first.message.toString());
}
Future testExternalWithoutImplementationMember() async {
@@ -636,22 +609,22 @@
// @patch void foo() {}
}
""");
- var container = ensure(compiler, "Class",
- compiler.commonElements.coreLibrary.find, expectIsPatched: true);
+ var container = ensure(
+ compiler, "Class", compiler.commonElements.coreLibrary.find,
+ expectIsPatched: true);
container.parseNode(compiler.parsingContext);
DiagnosticCollector collector = compiler.diagnosticCollector;
collector.clear();
compiler.resolver.resolveMethodElement(
ensure(compiler, "foo", container.lookupLocalMember));
- Expect.isTrue(collector.warnings.isEmpty,
- "Unexpected warnings: ${collector.warnings}");
+ Expect.isTrue(
+ collector.warnings.isEmpty, "Unexpected warnings: ${collector.warnings}");
print('testExternalWithoutImplementationMember:${collector.errors}');
Expect.equals(1, collector.errors.length);
- Expect.isTrue(
- collector.errors.first.message.kind ==
- MessageKind.PATCH_EXTERNAL_WITHOUT_IMPLEMENTATION);
+ Expect.isTrue(collector.errors.first.message.kind ==
+ MessageKind.PATCH_EXTERNAL_WITHOUT_IMPLEMENTATION);
Expect.stringEquals('External method without an implementation.',
- collector.errors.first.message.toString());
+ collector.errors.first.message.toString());
}
Future testIsSubclass() async {
@@ -662,8 +635,9 @@
"""
@patch class A {}
""");
- ClassElement cls = ensure(compiler, "A",
- compiler.commonElements.coreLibrary.find, expectIsPatched: true);
+ ClassElement cls = ensure(
+ compiler, "A", compiler.commonElements.coreLibrary.find,
+ expectIsPatched: true);
ClassElement patch = cls.patch;
Expect.isTrue(cls != patch);
Expect.isTrue(cls.isSubclassOf(patch));
@@ -679,8 +653,8 @@
@patch class Class {}
""");
DiagnosticCollector collector = compiler.diagnosticCollector;
- Expect.isTrue(collector.warnings.isEmpty,
- "Unexpected warnings: ${collector.warnings}");
+ Expect.isTrue(
+ collector.warnings.isEmpty, "Unexpected warnings: ${collector.warnings}");
print('testPatchNonExistingTopLevel:${collector.errors}');
Expect.equals(1, collector.errors.length);
Expect.isTrue(
@@ -697,13 +671,14 @@
@patch void foo() {}
}
""");
- var container = ensure(compiler, "Class",
- compiler.commonElements.coreLibrary.find, expectIsPatched: true);
+ var container = ensure(
+ compiler, "Class", compiler.commonElements.coreLibrary.find,
+ expectIsPatched: true);
container.parseNode(compiler.parsingContext);
DiagnosticCollector collector = compiler.diagnosticCollector;
- Expect.isTrue(collector.warnings.isEmpty,
- "Unexpected warnings: ${collector.warnings}");
+ Expect.isTrue(
+ collector.warnings.isEmpty, "Unexpected warnings: ${collector.warnings}");
print('testPatchNonExistingMember:${collector.errors}');
Expect.equals(1, collector.errors.length);
Expect.isTrue(
@@ -721,8 +696,8 @@
ensure(compiler, "foo", compiler.commonElements.coreLibrary.find);
DiagnosticCollector collector = compiler.diagnosticCollector;
- Expect.isTrue(collector.warnings.isEmpty,
- "Unexpected warnings: ${collector.warnings}");
+ Expect.isTrue(
+ collector.warnings.isEmpty, "Unexpected warnings: ${collector.warnings}");
print('testPatchNonPatchablePatch:${collector.errors}');
Expect.equals(1, collector.errors.length);
Expect.isTrue(
@@ -740,8 +715,8 @@
ensure(compiler, "foo", compiler.commonElements.coreLibrary.find);
DiagnosticCollector collector = compiler.diagnosticCollector;
- Expect.isTrue(collector.warnings.isEmpty,
- "Unexpected warnings: ${collector.warnings}");
+ Expect.isTrue(
+ collector.warnings.isEmpty, "Unexpected warnings: ${collector.warnings}");
print('testPatchNonPatchableOrigin:${collector.errors}');
Expect.equals(2, collector.errors.length);
Expect.equals(
@@ -785,8 +760,9 @@
@patch void foo() {}
}
""");
- var container = ensure(compiler, "Class",
- compiler.commonElements.coreLibrary.find, expectIsPatched: true);
+ var container = ensure(
+ compiler, "Class", compiler.commonElements.coreLibrary.find,
+ expectIsPatched: true);
container.parseNode(compiler.parsingContext);
DiagnosticCollector collector = compiler.diagnosticCollector;
@@ -917,9 +893,8 @@
collector.errors.first.message.kind == MessageKind.PATCH_NON_FUNCTION);
Expect.equals(0, collector.warnings.length);
Expect.equals(1, collector.infos.length);
- Expect.isTrue(
- collector.infos.first.message.kind ==
- MessageKind.PATCH_POINT_TO_FUNCTION);
+ Expect.isTrue(collector.infos.first.message.kind ==
+ MessageKind.PATCH_POINT_TO_FUNCTION);
}
Future testPatchAndSelector() async {
@@ -943,19 +918,21 @@
new B();
}
""",
- runCompiler: true, analyzeOnly: true);
+ runCompiler: true,
+ analyzeOnly: true);
World world = compiler.world;
world.populate();
- ClassElement cls = ensure(compiler, "A",
- compiler.commonElements.coreLibrary.find, expectIsPatched: true);
+ ClassElement cls = ensure(
+ compiler, "A", compiler.commonElements.coreLibrary.find,
+ expectIsPatched: true);
cls.ensureResolved(compiler.resolution);
ensure(compiler, "method", cls.patch.lookupLocalMember,
- checkHasBody: true, expectIsRegular: true);
+ checkHasBody: true, expectIsRegular: true);
ensure(compiler, "clear", cls.lookupLocalMember,
- checkHasBody: true, expectIsPatched: true);
+ checkHasBody: true, expectIsPatched: true);
compiler.phase = Compiler.PHASE_DONE_RESOLVING;
@@ -995,9 +972,9 @@
expectedWarnings = <MessageKind>[expectedWarnings];
}
- var compiler = await applyPatch('', patchText, analyzeAll: true,
- analyzeOnly: true);
- compiler.librariesToAnalyzeWhenRun = [Uri.parse('dart:core')];
+ var compiler =
+ await applyPatch('', patchText, analyzeAll: true, analyzeOnly: true);
+ compiler.librariesToAnalyzeWhenRun = [Uri.parse('dart:core')];
await compiler.run(null);
DiagnosticCollector collector = compiler.diagnosticCollector;
compareWarningKinds(patchText, expectedWarnings, collector.warnings);
@@ -1005,20 +982,22 @@
await expect('String s = 0;', MessageKind.NOT_ASSIGNABLE);
await expect('void method() { String s = 0; }', MessageKind.NOT_ASSIGNABLE);
- await expect('''
+ await expect(
+ '''
class Class {
String s = 0;
}
''',
- MessageKind.NOT_ASSIGNABLE);
- await expect('''
+ MessageKind.NOT_ASSIGNABLE);
+ await expect(
+ '''
class Class {
void method() {
String s = 0;
}
}
''',
- MessageKind.NOT_ASSIGNABLE);
+ MessageKind.NOT_ASSIGNABLE);
}
Future testEffectiveTarget() async {
@@ -1055,8 +1034,8 @@
}
""";
- var compiler = await applyPatch(origin, patch, analyzeAll: true,
- analyzeOnly: true, runCompiler: true);
+ var compiler = await applyPatch(origin, patch,
+ analyzeAll: true, analyzeOnly: true, runCompiler: true);
ClassElement clsA = compiler.commonElements.coreLibrary.find("A");
ClassElement clsB = compiler.commonElements.coreLibrary.find("B");
@@ -1081,8 +1060,8 @@
ConstructorElement forwardThree = clsA.lookupConstructor("forwardThree");
target = forwardThree.effectiveTarget;
Expect.isFalse(forwardThree.isMalformed);
- Expect.isTrue(target.isInjected,
- "Unexpected target $target for $forwardThree");
+ Expect.isTrue(
+ target.isInjected, "Unexpected target $target for $forwardThree");
Expect.equals("injected", target.name);
}
@@ -1094,12 +1073,12 @@
}
""";
var compiler = await applyPatch(originText, patchText,
- analyzeAll: true, analyzeOnly: true);
+ analyzeAll: true, analyzeOnly: true);
compiler.librariesToAnalyzeWhenRun = [Uri.parse('dart:core')];
await compiler.run(null);
DiagnosticCollector collector = compiler.diagnosticCollector;
- compareWarningKinds(patchText,
- [MessageKind.NOT_ASSIGNABLE], collector.warnings);
+ compareWarningKinds(
+ patchText, [MessageKind.NOT_ASSIGNABLE], collector.warnings);
}
main() {
diff --git a/tests/compiler/dart2js/platform_config_parser_test.dart b/tests/compiler/dart2js/platform_config_parser_test.dart
index a25e2da..2769086 100644
--- a/tests/compiler/dart2js/platform_config_parser_test.dart
+++ b/tests/compiler/dart2js/platform_config_parser_test.dart
@@ -91,9 +91,9 @@
name2:value2
""",
{
- "AA": {"name": "value"},
- "BB": {"name": "value", "name2": "value2"}
- });
+ "AA": {"name": "value"},
+ "BB": {"name": "value", "name2": "value2"}
+ });
// Ok, file not ending in newline.
test(
@@ -101,8 +101,8 @@
[AA]
name:value""",
{
- "A": {"name": "value"}
- });
+ "A": {"name": "value"}
+ });
// Ok, whitespace is trimmed away.
test(
diff --git a/tests/compiler/dart2js/platform_consistency_test.dart b/tests/compiler/dart2js/platform_consistency_test.dart
index fa50b29..5d6e638 100644
--- a/tests/compiler/dart2js/platform_consistency_test.dart
+++ b/tests/compiler/dart2js/platform_consistency_test.dart
@@ -7,30 +7,27 @@
import "package:compiler/compiler_new.dart";
import "package:expect/expect.dart";
-Uri unsupported = Uri.parse("unsupported:");
+Uri unsupported = Uri.parse("unsupported:");
main() async {
CompilerInput input = new CompilerSourceFileProvider();
- Map<String, Uri> client = await load(
- Uri.base.resolve("sdk/lib/dart_client.platform"),
- input);
- Map<String, Uri> server = await load(
- Uri.base.resolve("sdk/lib/dart_server.platform"),
- input);
- Map<String, Uri> shared = await load(
- Uri.base.resolve("sdk/lib/dart_shared.platform"),
- input);
+ Map<String, Uri> client =
+ await load(Uri.base.resolve("sdk/lib/dart_client.platform"), input);
+ Map<String, Uri> server =
+ await load(Uri.base.resolve("sdk/lib/dart_server.platform"), input);
+ Map<String, Uri> shared =
+ await load(Uri.base.resolve("sdk/lib/dart_shared.platform"), input);
Expect.setEquals(new Set.from(shared.keys), new Set.from(client.keys));
Expect.setEquals(new Set.from(shared.keys), new Set.from(server.keys));
for (String libraryName in shared.keys) {
test(Map<String, Uri> m) {
- if (m[libraryName] != unsupported &&
- shared[libraryName] != unsupported) {
+ if (m[libraryName] != unsupported && shared[libraryName] != unsupported) {
Expect.equals(shared[libraryName], m[libraryName]);
}
}
+
test(client);
test(server);
}
- }
+}
diff --git a/tests/compiler/dart2js/preserve_uris_test.dart b/tests/compiler/dart2js/preserve_uris_test.dart
index 9d58894..ed7a361 100644
--- a/tests/compiler/dart2js/preserve_uris_test.dart
+++ b/tests/compiler/dart2js/preserve_uris_test.dart
@@ -6,7 +6,7 @@
import 'package:async_helper/async_helper.dart';
import 'memory_compiler.dart' show runCompiler, OutputCollector;
-const MEMORY_SOURCE_FILES = const <String, String> {
+const MEMORY_SOURCE_FILES = const <String, String>{
'main.dart': """
library main;
diff --git a/tests/compiler/dart2js/pretty_parameter_test.dart b/tests/compiler/dart2js/pretty_parameter_test.dart
index 3aa4db1..e075e68 100644
--- a/tests/compiler/dart2js/pretty_parameter_test.dart
+++ b/tests/compiler/dart2js/pretty_parameter_test.dart
@@ -74,33 +74,31 @@
main() {
asyncTest(() => Future.wait([
- compile(FOO, entry: 'foo', check: (String generated) {
- Expect.isTrue(generated.contains(r"function(a, b) {"));
- }),
-
- compile(BAR, entry: 'bar', check: (String generated) {
- Expect.isTrue(generated.contains(r"function($eval, $$eval) {"));
- }),
-
- compile(PARAMETER_AND_TEMP, entry: 'bar', check: (String generated) {
- Expect.isTrue(generated.contains(r"print(t00)"));
- // Check that the second 't0' got another name.
- Expect.isTrue(generated.contains(r"print(t01)"));
- }),
-
- compile(MULTIPLE_PHIS_ONE_LOCAL, entry: 'foo', check: (String generated) {
- Expect.isTrue(generated.contains("var a;"));
- // Check that there is only one var declaration.
- checkNumberOfMatches(new RegExp("var").allMatches(generated).iterator, 1);
- }),
-
- compile(NO_LOCAL, entry: 'foo', check: (String generated) {
- Expect.isFalse(generated.contains('var'));
- }),
-
- compile(PARAMETER_INIT, entry: 'foo', check: (String generated) {
- // Check that there is only one var declaration.
- checkNumberOfMatches(new RegExp("var").allMatches(generated).iterator, 1);
- }),
- ]));
+ compile(FOO, entry: 'foo', check: (String generated) {
+ Expect.isTrue(generated.contains(r"function(a, b) {"));
+ }),
+ compile(BAR, entry: 'bar', check: (String generated) {
+ Expect.isTrue(generated.contains(r"function($eval, $$eval) {"));
+ }),
+ compile(PARAMETER_AND_TEMP, entry: 'bar', check: (String generated) {
+ Expect.isTrue(generated.contains(r"print(t00)"));
+ // Check that the second 't0' got another name.
+ Expect.isTrue(generated.contains(r"print(t01)"));
+ }),
+ compile(MULTIPLE_PHIS_ONE_LOCAL, entry: 'foo',
+ check: (String generated) {
+ Expect.isTrue(generated.contains("var a;"));
+ // Check that there is only one var declaration.
+ checkNumberOfMatches(
+ new RegExp("var").allMatches(generated).iterator, 1);
+ }),
+ compile(NO_LOCAL, entry: 'foo', check: (String generated) {
+ Expect.isFalse(generated.contains('var'));
+ }),
+ compile(PARAMETER_INIT, entry: 'foo', check: (String generated) {
+ // Check that there is only one var declaration.
+ checkNumberOfMatches(
+ new RegExp("var").allMatches(generated).iterator, 1);
+ }),
+ ]));
}
diff --git a/tests/compiler/dart2js/private_test.dart b/tests/compiler/dart2js/private_test.dart
index fbfba80..4c5f633 100644
--- a/tests/compiler/dart2js/private_test.dart
+++ b/tests/compiler/dart2js/private_test.dart
@@ -41,11 +41,10 @@
}
''';
-
analyze(String text, [expectedWarnings]) {
return () {
if (expectedWarnings == null) expectedWarnings = [];
- if (expectedWarnings is !List) expectedWarnings = [expectedWarnings];
+ if (expectedWarnings is! List) expectedWarnings = [expectedWarnings];
MockCompiler compiler = new MockCompiler.internal(analyzeOnly: true);
compiler.registerSource(Uri.parse(PRIVATE_SOURCE_URI), PRIVATE_SOURCE);
@@ -80,95 +79,91 @@
void main() {
asyncTest(() => Future.forEach([
- // Read from private variable.
- analyze('var value = _privateVariable;', MessageKind.CANNOT_RESOLVE),
- // Write to private variable.
- analyze('_privateVariable = 0;', MessageKind.CANNOT_RESOLVE),
- // Access private function.
- analyze('var value = _privateFunction;', MessageKind.CANNOT_RESOLVE),
- // Call private function.
- analyze('_privateFunction();', MessageKind.CANNOT_RESOLVE),
+ // Read from private variable.
+ analyze('var value = _privateVariable;', MessageKind.CANNOT_RESOLVE),
+ // Write to private variable.
+ analyze('_privateVariable = 0;', MessageKind.CANNOT_RESOLVE),
+ // Access private function.
+ analyze('var value = _privateFunction;', MessageKind.CANNOT_RESOLVE),
+ // Call private function.
+ analyze('_privateFunction();', MessageKind.CANNOT_RESOLVE),
- // Call unnamed (public) constructor on private class.
- analyze('new _PrivateClass();', MessageKind.CANNOT_RESOLVE),
- // Call public constructor on private class.
- analyze('new _PrivateClass.publicConstructor();',
+ // Call unnamed (public) constructor on private class.
+ analyze('new _PrivateClass();', MessageKind.CANNOT_RESOLVE),
+ // Call public constructor on private class.
+ analyze('new _PrivateClass.publicConstructor();',
MessageKind.CANNOT_RESOLVE),
- // Call private constructor on private class.
- analyze('new _PrivateClass._privateConstructor();',
- MessageKind.CANNOT_RESOLVE),
- // Call public getter of private type.
- analyze('var value = publicClass.private;'),
- // Read from private field on private class.
- analyze('var value = publicClass.private._privateField;',
- MessageKind.PRIVATE_ACCESS),
- // Write to private field on private class.
- analyze('publicClass.private._privateField = 0;',
- MessageKind.PRIVATE_ACCESS),
- // Call private getter on private class.
- analyze('var value = publicClass.private._privateGetter;',
- MessageKind.PRIVATE_ACCESS),
- // Call private setter on private class.
- analyze('publicClass.private._privateSetter = 0;',
- MessageKind.PRIVATE_ACCESS),
- // Access private method on private class.
- analyze('var value = publicClass.private._privateMethod;',
- MessageKind.PRIVATE_ACCESS),
- // Call private method on private class.
- analyze('publicClass.private._privateMethod();',
- MessageKind.PRIVATE_ACCESS),
+ // Call private constructor on private class.
+ analyze('new _PrivateClass._privateConstructor();',
+ MessageKind.CANNOT_RESOLVE),
+ // Call public getter of private type.
+ analyze('var value = publicClass.private;'),
+ // Read from private field on private class.
+ analyze('var value = publicClass.private._privateField;',
+ MessageKind.PRIVATE_ACCESS),
+ // Write to private field on private class.
+ analyze('publicClass.private._privateField = 0;',
+ MessageKind.PRIVATE_ACCESS),
+ // Call private getter on private class.
+ analyze('var value = publicClass.private._privateGetter;',
+ MessageKind.PRIVATE_ACCESS),
+ // Call private setter on private class.
+ analyze('publicClass.private._privateSetter = 0;',
+ MessageKind.PRIVATE_ACCESS),
+ // Access private method on private class.
+ analyze('var value = publicClass.private._privateMethod;',
+ MessageKind.PRIVATE_ACCESS),
+ // Call private method on private class.
+ analyze('publicClass.private._privateMethod();',
+ MessageKind.PRIVATE_ACCESS),
- // Read from public field on private class.
- analyze('var value = publicClass.private.publicField;'),
- // Write to public field on private class.
- analyze('publicClass.private.publicField = 0;'),
- // Call public getter on private class.
- analyze('var value = publicClass.private.publicGetter;'),
- // Call public setter on private class.
- analyze('publicClass.private.publicSetter = 0;'),
- // Access public method on private class.
- analyze('var value = publicClass.private.publicMethod;'),
- // Call public method on private class.
- analyze('publicClass.private.publicMethod();'),
+ // Read from public field on private class.
+ analyze('var value = publicClass.private.publicField;'),
+ // Write to public field on private class.
+ analyze('publicClass.private.publicField = 0;'),
+ // Call public getter on private class.
+ analyze('var value = publicClass.private.publicGetter;'),
+ // Call public setter on private class.
+ analyze('publicClass.private.publicSetter = 0;'),
+ // Access public method on private class.
+ analyze('var value = publicClass.private.publicMethod;'),
+ // Call public method on private class.
+ analyze('publicClass.private.publicMethod();'),
- // Call unnamed (public) constructor on public class.
- analyze('publicClass = new PublicClass();'),
- // Call public constructor on public class.
- analyze('publicClass = new PublicClass.publicConstructor();'),
- // Call private constructor on public class.
- analyze('publicClass = new PublicClass._privateConstructor();',
- MessageKind.CANNOT_FIND_CONSTRUCTOR),
- // Read from private field on public class.
- analyze('var value = publicClass._privateField;',
- MessageKind.PRIVATE_ACCESS),
- // Write to private field on public class.
- analyze('publicClass._privateField = 0;',
- MessageKind.PRIVATE_ACCESS),
- // Call private getter on public class.
- analyze('var value = publicClass._privateGetter;',
- MessageKind.PRIVATE_ACCESS),
- // Call private setter on public class.
- analyze('publicClass._privateSetter = 0;',
- MessageKind.PRIVATE_ACCESS),
- // Access private method on public class.
- analyze('var value = publicClass._privateMethod;',
- MessageKind.PRIVATE_ACCESS),
- // Call private method on public class.
- analyze('publicClass._privateMethod();',
- MessageKind.PRIVATE_ACCESS),
+ // Call unnamed (public) constructor on public class.
+ analyze('publicClass = new PublicClass();'),
+ // Call public constructor on public class.
+ analyze('publicClass = new PublicClass.publicConstructor();'),
+ // Call private constructor on public class.
+ analyze('publicClass = new PublicClass._privateConstructor();',
+ MessageKind.CANNOT_FIND_CONSTRUCTOR),
+ // Read from private field on public class.
+ analyze('var value = publicClass._privateField;',
+ MessageKind.PRIVATE_ACCESS),
+ // Write to private field on public class.
+ analyze('publicClass._privateField = 0;', MessageKind.PRIVATE_ACCESS),
+ // Call private getter on public class.
+ analyze('var value = publicClass._privateGetter;',
+ MessageKind.PRIVATE_ACCESS),
+ // Call private setter on public class.
+ analyze('publicClass._privateSetter = 0;', MessageKind.PRIVATE_ACCESS),
+ // Access private method on public class.
+ analyze('var value = publicClass._privateMethod;',
+ MessageKind.PRIVATE_ACCESS),
+ // Call private method on public class.
+ analyze('publicClass._privateMethod();', MessageKind.PRIVATE_ACCESS),
- // Read from public field on public class.
- analyze('var value = publicClass.publicField;'),
- // Write to public field on public class.
- analyze('publicClass.publicField = 0;'),
- // Call public getter on public class.
- analyze('var value = publicClass.publicGetter;'),
- // Call public setter on public class.
- analyze('publicClass.publicSetter = 0;'),
- // Access public method on public class.
- analyze('var value = publicClass.publicMethod;'),
- // Call public method on public class.
- analyze('publicClass.publicMethod();'),
- ], (f) => f()));
+ // Read from public field on public class.
+ analyze('var value = publicClass.publicField;'),
+ // Write to public field on public class.
+ analyze('publicClass.publicField = 0;'),
+ // Call public getter on public class.
+ analyze('var value = publicClass.publicGetter;'),
+ // Call public setter on public class.
+ analyze('publicClass.publicSetter = 0;'),
+ // Access public method on public class.
+ analyze('var value = publicClass.publicMethod;'),
+ // Call public method on public class.
+ analyze('publicClass.publicMethod();'),
+ ], (f) => f()));
}
-
diff --git a/tests/compiler/dart2js/proxy_test.dart b/tests/compiler/dart2js/proxy_test.dart
index 3a0af23..0131db9 100644
--- a/tests/compiler/dart2js/proxy_test.dart
+++ b/tests/compiler/dart2js/proxy_test.dart
@@ -13,11 +13,11 @@
/// can contain a list of line numbers for keys 'missing' and 'unexpected' for
/// the warnings of each category.
const Map<String, dynamic> TESTS = const {
- 'language/proxy_test.dart': null,
- 'language/proxy2_test.dart': null,
- 'language/proxy3_test.dart': null,
- 'language/proxy4_test.dart': null,
- 'language/proxy5_test.dart': null,
+ 'language/proxy_test.dart': null,
+ 'language/proxy2_test.dart': null,
+ 'language/proxy3_test.dart': null,
+ 'language/proxy4_test.dart': null,
+ 'language/proxy5_test.dart': null,
};
void main(List<String> args) {
diff --git a/tests/compiler/dart2js/quarantined/http_launch_data/http_launch_main.dart b/tests/compiler/dart2js/quarantined/http_launch_data/http_launch_main.dart
index 68ea634..b2359a9 100644
--- a/tests/compiler/dart2js/quarantined/http_launch_data/http_launch_main.dart
+++ b/tests/compiler/dart2js/quarantined/http_launch_data/http_launch_main.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 'lib1.dart';
main() {
diff --git a/tests/compiler/dart2js/quarantined/http_launch_data/http_launch_main_package.dart b/tests/compiler/dart2js/quarantined/http_launch_data/http_launch_main_package.dart
index ec876b3..3a8acff 100644
--- a/tests/compiler/dart2js/quarantined/http_launch_data/http_launch_main_package.dart
+++ b/tests/compiler/dart2js/quarantined/http_launch_data/http_launch_main_package.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:simple/simple.dart';
main() {
diff --git a/tests/compiler/dart2js/quarantined/http_test.dart b/tests/compiler/dart2js/quarantined/http_test.dart
index 328cea3..1132029 100644
--- a/tests/compiler/dart2js/quarantined/http_test.dart
+++ b/tests/compiler/dart2js/quarantined/http_test.dart
@@ -32,9 +32,9 @@
final File file = new File(requestPath.toFilePath());
return file.exists().then((bool found) {
if (found) {
- file.openRead()
- .pipe(request.response)
- .catchError((e) { _sendNotFound(request.response); });
+ file.openRead().pipe(request.response).catchError((e) {
+ _sendNotFound(request.response);
+ });
} else {
_sendNotFound(request.response);
}
@@ -65,17 +65,17 @@
Future testNonHttp() {
String inFilePath = pathOfData.resolve('http_launch_main.dart').toFilePath();
List<String> args = [inFilePath, "--out=" + outFilePath];
- return launchDart2Js(args)
- .then(check)
- .then((_) { cleanup(); });
+ return launchDart2Js(args).then(check).then((_) {
+ cleanup();
+ });
}
Future testHttpMain(String serverUrl) {
String inFilePath = '$serverUrl/http_launch_main.dart';
List<String> args = [inFilePath, "--out=" + outFilePath];
- return launchDart2Js(args)
- .then(check)
- .then((_) { cleanup(); });
+ return launchDart2Js(args).then(check).then((_) {
+ cleanup();
+ });
}
Future testHttpLib(String serverUrl) {
@@ -89,19 +89,23 @@
return launchDart2Js(args)
.then(check)
.whenComplete(file.deleteSync)
- .then((_) { cleanup(); });
+ .then((_) {
+ cleanup();
+ });
}
Future testHttpPackage(String serverUrl) {
String inFilePath =
pathOfData.resolve('http_launch_main_package.dart').toFilePath();
String packageRoot = '$serverUrl/packages/';
- List<String> args = [inFilePath,
- "--out=" + outFilePath,
- "--package-root=" + packageRoot];
- return launchDart2Js(args)
- .then(check)
- .then((_) { cleanup(); });
+ List<String> args = [
+ inFilePath,
+ "--out=" + outFilePath,
+ "--package-root=" + packageRoot
+ ];
+ return launchDart2Js(args).then(check).then((_) {
+ cleanup();
+ });
}
Future testBadHttp(String serverUrl) {
@@ -115,7 +119,9 @@
return launchDart2Js(args)
.then((pr) => checkNotFound(pr, "not_existing.dart"))
.whenComplete(file.deleteSync)
- .then((_) { cleanup(); });
+ .then((_) {
+ cleanup();
+ });
}
Future testBadHttp2(String serverUrl) {
@@ -123,7 +129,9 @@
List<String> args = [inFilePath, "--out=" + outFilePath];
return launchDart2Js(args)
.then((processResult) => checkNotFound(processResult, "not_found.dart"))
- .then((_) { cleanup(); });
+ .then((_) {
+ cleanup();
+ });
}
serverRunning(HttpServer server, String scheme) {
@@ -135,41 +143,39 @@
asyncStart();
server.listen(handleRequest);
return new Future.value()
- .then((_) => cleanup()) // Make sure we start fresh.
- .then((_) => testNonHttp())
- .then((_) => testHttpMain(serverUrl))
- .then((_) => testHttpLib(serverUrl))
- .then((_) => testHttpPackage(serverUrl))
- .then((_) => testBadHttp(serverUrl))
- .then((_) => testBadHttp2(serverUrl))
- .whenComplete(() => tempDir.delete(recursive: true))
- .whenComplete(server.close)
- .then((_) => asyncEnd());
+ .then((_) => cleanup()) // Make sure we start fresh.
+ .then((_) => testNonHttp())
+ .then((_) => testHttpMain(serverUrl))
+ .then((_) => testHttpLib(serverUrl))
+ .then((_) => testHttpPackage(serverUrl))
+ .then((_) => testBadHttp(serverUrl))
+ .then((_) => testBadHttp2(serverUrl))
+ .whenComplete(() => tempDir.delete(recursive: true))
+ .whenComplete(server.close)
+ .then((_) => asyncEnd());
}
Future testHttp() {
- return HttpServer.bind(InternetAddress.LOOPBACK_IP_V4, 0)
+ return HttpServer
+ .bind(InternetAddress.LOOPBACK_IP_V4, 0)
.then((HttpServer server) => serverRunning(server, "http"));
}
void initializeSSL() {
Uri pathOfPkcert = pathOfData.resolve('pkcert');
String testPkcertDatabase = pathOfPkcert.toFilePath();
- SecureSocket.initialize(database: testPkcertDatabase,
- password: 'dartdart');
+ SecureSocket.initialize(database: testPkcertDatabase, password: 'dartdart');
}
Future testHttps() {
initializeSSL();
- return HttpServer.bindSecure(InternetAddress.LOOPBACK_IP_V4,
- 0,
- certificateName: 'localhost_cert')
+ return HttpServer
+ .bindSecure(InternetAddress.LOOPBACK_IP_V4, 0,
+ certificateName: 'localhost_cert')
.then((HttpServer server) => serverRunning(server, "https"));
}
main() {
asyncStart();
- testHttp()
- .then((_) => testHttps)
- .whenComplete(asyncEnd);
+ testHttp().then((_) => testHttps).whenComplete(asyncEnd);
}
diff --git a/tests/compiler/dart2js/redundant_phi_eliminator_test.dart b/tests/compiler/dart2js/redundant_phi_eliminator_test.dart
index d7f2b72..da81d94 100644
--- a/tests/compiler/dart2js/redundant_phi_eliminator_test.dart
+++ b/tests/compiler/dart2js/redundant_phi_eliminator_test.dart
@@ -17,7 +17,6 @@
}
""";
-
const String TEST_TWO = r"""
void foo() {
var temp = 0;
@@ -31,16 +30,15 @@
main() {
asyncTest(() => Future.wait([
- compile(TEST_ONE, entry: 'foo', check: (String generated) {
- RegExp regexp = new RegExp("toBeRemoved");
- Expect.isTrue(!regexp.hasMatch(generated));
- }),
-
- compile(TEST_TWO, entry: 'foo', check: (String generated) {
- RegExp regexp = new RegExp("toBeRemoved");
- Expect.isTrue(!regexp.hasMatch(generated));
- regexp = new RegExp("temp");
- Expect.isTrue(!regexp.hasMatch(generated));
- }),
- ]));
+ compile(TEST_ONE, entry: 'foo', check: (String generated) {
+ RegExp regexp = new RegExp("toBeRemoved");
+ Expect.isTrue(!regexp.hasMatch(generated));
+ }),
+ compile(TEST_TWO, entry: 'foo', check: (String generated) {
+ RegExp regexp = new RegExp("toBeRemoved");
+ Expect.isTrue(!regexp.hasMatch(generated));
+ regexp = new RegExp("temp");
+ Expect.isTrue(!regexp.hasMatch(generated));
+ }),
+ ]));
}
diff --git a/tests/compiler/dart2js/reexport_handled_test.dart b/tests/compiler/dart2js/reexport_handled_test.dart
index ade3373..4bdaa04 100644
--- a/tests/compiler/dart2js/reexport_handled_test.dart
+++ b/tests/compiler/dart2js/reexport_handled_test.dart
@@ -8,8 +8,7 @@
import "package:async_helper/async_helper.dart";
import 'mock_compiler.dart';
import 'package:compiler/src/elements/elements.dart'
- show Element,
- LibraryElement;
+ show Element, LibraryElement;
final exportingLibraryUri = Uri.parse('exporting.dart');
const String EXPORTING_LIBRARY_SOURCE = '''
@@ -26,21 +25,22 @@
void main() {
MockCompiler compiler;
asyncTest(() => MockCompiler.create((MockCompiler c) {
- compiler = c;
- compiler.registerSource(exportingLibraryUri, EXPORTING_LIBRARY_SOURCE);
- compiler.registerSource(reexportingLibraryUri, REEXPORTING_LIBRARY_SOURCE);
- return compiler.libraryLoader.loadLibrary(exportingLibraryUri);
- }).then((exportingLibrary) {
- Expect.isTrue(exportingLibrary.exportsHandled);
- var foo = exportingLibrary.findExported('foo');
- Expect.isNotNull(foo);
- Expect.isTrue(foo.isField);
+ compiler = c;
+ compiler.registerSource(exportingLibraryUri, EXPORTING_LIBRARY_SOURCE);
+ compiler.registerSource(
+ reexportingLibraryUri, REEXPORTING_LIBRARY_SOURCE);
+ return compiler.libraryLoader.loadLibrary(exportingLibraryUri);
+ }).then((exportingLibrary) {
+ Expect.isTrue(exportingLibrary.exportsHandled);
+ var foo = exportingLibrary.findExported('foo');
+ Expect.isNotNull(foo);
+ Expect.isTrue(foo.isField);
- // Load reexporting library when exports are handled on the exporting library.
- return compiler.libraryLoader.loadLibrary(reexportingLibraryUri);
- }).then((reexportingLibrary) {
- var foo = reexportingLibrary.findExported('foo');
- Expect.isNotNull(foo);
- Expect.isTrue(foo.isField);
- }));
+ // Load reexporting library when exports are handled on the exporting library.
+ return compiler.libraryLoader.loadLibrary(reexportingLibraryUri);
+ }).then((reexportingLibrary) {
+ var foo = reexportingLibrary.findExported('foo');
+ Expect.isNotNull(foo);
+ Expect.isTrue(foo.isField);
+ }));
}
diff --git a/tests/compiler/dart2js/regress_10231_test.dart b/tests/compiler/dart2js/regress_10231_test.dart
index 2e06461..9031931 100644
--- a/tests/compiler/dart2js/regress_10231_test.dart
+++ b/tests/compiler/dart2js/regress_10231_test.dart
@@ -10,11 +10,11 @@
void main() {
asyncTest(() => generate(SOURCE).then((result) {
- var code = result['test'];
- Expect.isNotNull(code);
- Expect.equals(0, new RegExp('add').allMatches(code).length);
- Expect.equals(3, new RegExp('\\+').allMatches(code).length);
- }));
+ var code = result['test'];
+ Expect.isNotNull(code);
+ Expect.equals(0, new RegExp('add').allMatches(code).length);
+ Expect.equals(3, new RegExp('\\+').allMatches(code).length);
+ }));
}
const String SOURCE = """
diff --git a/tests/compiler/dart2js/related_types.dart b/tests/compiler/dart2js/related_types.dart
index d3f04e3..7d56a65 100644
--- a/tests/compiler/dart2js/related_types.dart
+++ b/tests/compiler/dart2js/related_types.dart
@@ -103,19 +103,14 @@
void checkRelated(Node node, DartType left, DartType right) {
if (hasEmptyIntersection(left, right)) {
reporter.reportHintMessage(
- node,
- MessageKind.NO_COMMON_SUBTYPES,
- {'left': left, 'right': right});
+ node, MessageKind.NO_COMMON_SUBTYPES, {'left': left, 'right': right});
}
}
/// Check weakly typed collection methods, like `Map.containsKey`,
/// `Map.containsValue` and `Iterable.contains`.
- void checkDynamicInvoke(
- Node node,
- DartType receiverType,
- List<DartType> argumentTypes,
- Selector selector) {
+ void checkDynamicInvoke(Node node, DartType receiverType,
+ List<DartType> argumentTypes, Selector selector) {
if (selector.name == 'containsKey' &&
selector.callStructure == CallStructure.ONE_ARG) {
InterfaceType mapType = findMapType(receiverType);
@@ -124,21 +119,21 @@
checkRelated(node, keyType, argumentTypes.first);
}
} else if (selector.name == 'containsValue' &&
- selector.callStructure == CallStructure.ONE_ARG) {
+ selector.callStructure == CallStructure.ONE_ARG) {
InterfaceType mapType = findMapType(receiverType);
if (mapType != null) {
DartType valueType = findMapValueType(mapType);
checkRelated(node, valueType, argumentTypes.first);
}
} else if (selector.name == 'contains' &&
- selector.callStructure == CallStructure.ONE_ARG) {
+ selector.callStructure == CallStructure.ONE_ARG) {
InterfaceType iterableType = findIterableType(receiverType);
if (iterableType != null) {
DartType elementType = findIterableElementType(iterableType);
checkRelated(node, elementType, argumentTypes.first);
}
} else if (selector.name == 'remove' &&
- selector.callStructure == CallStructure.ONE_ARG) {
+ selector.callStructure == CallStructure.ONE_ARG) {
InterfaceType mapType = findMapType(receiverType);
if (mapType != null) {
DartType keyType = findMapKeyType(mapType);
@@ -361,61 +356,47 @@
@override
DartType visitDynamicPropertyInvoke(
- Send node,
- Node receiver,
- NodeList arguments,
- Selector selector, _) {
+ Send node, Node receiver, NodeList arguments, Selector selector, _) {
DartType receiverType = apply(receiver);
List<DartType> argumentTypes = findArgumentTypes(arguments);
- FunctionType methodType = lookupInterfaceMemberInvocationType(
- receiverType, selector.memberName);
+ FunctionType methodType =
+ lookupInterfaceMemberInvocationType(receiverType, selector.memberName);
checkDynamicInvoke(node, receiverType, argumentTypes, selector);
return findReturnType(methodType);
}
@override
DartType visitThisPropertyInvoke(
- Send node,
- NodeList arguments,
- Selector selector, _) {
+ Send node, NodeList arguments, Selector selector, _) {
DartType receiverType = thisType;
List<DartType> argumentTypes = findArgumentTypes(arguments);
- FunctionType methodType = lookupInterfaceMemberInvocationType(
- receiverType, selector.memberName);
+ FunctionType methodType =
+ lookupInterfaceMemberInvocationType(receiverType, selector.memberName);
checkDynamicInvoke(node, receiverType, argumentTypes, selector);
return findReturnType(methodType);
}
@override
DartType visitIfNotNullDynamicPropertyInvoke(
- Send node,
- Node receiver,
- NodeList arguments,
- Selector selector, _) {
+ Send node, Node receiver, NodeList arguments, Selector selector, _) {
DartType receiverType = apply(receiver);
List<DartType> argumentTypes = findArgumentTypes(arguments);
- FunctionType methodType = lookupInterfaceMemberInvocationType(
- receiverType, selector.memberName);
+ FunctionType methodType =
+ lookupInterfaceMemberInvocationType(receiverType, selector.memberName);
checkDynamicInvoke(node, receiverType, argumentTypes, selector);
return findReturnType(methodType);
}
@override
- DartType visitTopLevelFunctionInvoke(
- Send node,
- MethodElement function,
- NodeList arguments,
- CallStructure callStructure, _) {
+ DartType visitTopLevelFunctionInvoke(Send node, MethodElement function,
+ NodeList arguments, CallStructure callStructure, _) {
apply(arguments);
return findReturnType(function.type);
}
@override
- DartType visitStaticFunctionInvoke(
- Send node,
- MethodElement function,
- NodeList arguments,
- CallStructure callStructure, _) {
+ DartType visitStaticFunctionInvoke(Send node, MethodElement function,
+ NodeList arguments, CallStructure callStructure, _) {
apply(arguments);
return findReturnType(function.type);
}
@@ -435,4 +416,4 @@
ClassElement visitInterfaceType(InterfaceType type, _) {
return type.element;
}
-}
\ No newline at end of file
+}
diff --git a/tests/compiler/dart2js/related_types_test.dart b/tests/compiler/dart2js/related_types_test.dart
index 63b424a..f5209b2 100644
--- a/tests/compiler/dart2js/related_types_test.dart
+++ b/tests/compiler/dart2js/related_types_test.dart
@@ -264,17 +264,17 @@
memorySourceFiles: {'main.dart': CODE},
options: [Flags.analyzeOnly, Flags.analyzeMain],
diagnosticHandler: collector);
- Expect.isFalse(collector.hasRegularMessages, "Unexpected analysis messages.");
+ Expect.isFalse(
+ collector.hasRegularMessages, "Unexpected analysis messages.");
Compiler compiler = result.compiler;
-
void checkMember(MemberElement member) {
if (!member.name.startsWith('test_')) return;
collector.clear();
checkMemberElement(compiler, member);
- Expect.equals(1, collector.hints.length,
- "Unexpected hint count for $member.");
+ Expect.equals(
+ 1, collector.hints.length, "Unexpected hint count for $member.");
Expect.equals(
MessageKind.NO_COMMON_SUBTYPES,
collector.hints.first.message.kind,
diff --git a/tests/compiler/dart2js/resolution_test.dart b/tests/compiler/dart2js/resolution_test.dart
index 3087ee1..cfca9a8 100644
--- a/tests/compiler/dart2js/resolution_test.dart
+++ b/tests/compiler/dart2js/resolution_test.dart
@@ -96,8 +96,8 @@
Uri uri = new Uri(scheme: 'source');
var compiler = compilerFor(code, uri);
asyncTest(() => compiler.run(uri).then((_) {
- check(compiler);
- }));
+ check(compiler);
+ }));
}
void testHasRuntimeType(String code) {
diff --git a/tests/compiler/dart2js/resolver_test.dart b/tests/compiler/dart2js/resolver_test.dart
index 5ddf37c..8d1ec64 100644
--- a/tests/compiler/dart2js/resolver_test.dart
+++ b/tests/compiler/dart2js/resolver_test.dart
@@ -23,9 +23,8 @@
Node buildIdentifier(String name) => new Identifier(scan(name));
-Node buildInitialization(String name) =>
- parseBodyCode('$name = 1',
- (parser, tokens) => parser.parseOptionallyInitializedIdentifier(tokens));
+Node buildInitialization(String name) => parseBodyCode('$name = 1',
+ (parser, tokens) => parser.parseOptionallyInitializedIdentifier(tokens));
createLocals(List variables) {
var locals = <Node>[];
@@ -64,39 +63,39 @@
main() {
asyncTest(() => Future.forEach([
- testLocalsOne,
- testLocalsTwo,
- testLocalsThree,
- testLocalsFour,
- testLocalsFive,
- testParametersOne,
- testFor,
- testTypeAnnotation,
- testSuperclass,
- // testVarSuperclass, // The parser crashes with 'class Foo extends var'.
- // testOneInterface, // Generates unexpected error message.
- // testTwoInterfaces, // Generates unexpected error message.
- testFunctionExpression,
- testNewExpression,
- testTopLevelFields,
- testClassHierarchy,
- testEnumDeclaration,
- testInitializers,
- testThis,
- testSuperCalls,
- testSwitch,
- testTypeVariables,
- testToString,
- testIndexedOperator,
- testIncrementsAndDecrements,
- testOverrideHashCodeCheck,
- testSupertypeOrder,
- testConstConstructorAndNonFinalFields,
- testCantAssignMethods,
- testCantAssignFinalAndConsts,
- testAwaitHint,
- testConstantExpressions,
- ], (f) => f()));
+ testLocalsOne,
+ testLocalsTwo,
+ testLocalsThree,
+ testLocalsFour,
+ testLocalsFive,
+ testParametersOne,
+ testFor,
+ testTypeAnnotation,
+ testSuperclass,
+ // testVarSuperclass, // The parser crashes with 'class Foo extends var'.
+ // testOneInterface, // Generates unexpected error message.
+ // testTwoInterfaces, // Generates unexpected error message.
+ testFunctionExpression,
+ testNewExpression,
+ testTopLevelFields,
+ testClassHierarchy,
+ testEnumDeclaration,
+ testInitializers,
+ testThis,
+ testSuperCalls,
+ testSwitch,
+ testTypeVariables,
+ testToString,
+ testIndexedOperator,
+ testIncrementsAndDecrements,
+ testOverrideHashCodeCheck,
+ testSupertypeOrder,
+ testConstConstructorAndNonFinalFields,
+ testCantAssignMethods,
+ testCantAssignFinalAndConsts,
+ testAwaitHint,
+ testConstantExpressions,
+ ], (f) => f()));
}
Future testSupertypeOrder() {
@@ -120,9 +119,9 @@
ClassElement classC = compiler.mainApp.find("C");
Expect.equals('[ I2, I1, Object ]', classA.allSupertypes.toString());
Expect.equals('[ A, J2, J1, I2, I1, K2, K1, Object ]',
- classB.allSupertypes.toString());
+ classB.allSupertypes.toString());
Expect.equals('[ B, L1, A, J2, J1, I2, I1, K2, K1, Object ]',
- classC.allSupertypes.toString());
+ classC.allSupertypes.toString());
}),
MockCompiler.create((MockCompiler compiler) {
compiler.parseScript("""
@@ -135,8 +134,8 @@
DiagnosticCollector collector = compiler.diagnosticCollector;
Expect.equals(0, collector.warnings.length);
Expect.equals(1, collector.errors.length);
- Expect.equals(MessageKind.MULTI_INHERITANCE,
- collector.errors.first.message.kind);
+ Expect.equals(
+ MessageKind.MULTI_INHERITANCE, collector.errors.first.message.kind);
Expect.equals(0, collector.crashes.length);
}),
]);
@@ -147,8 +146,8 @@
VariableDefinitions definition = parseStatement(text);
visitor.visit(definition.type);
InterfaceType type = visitor.registry.mapping.getType(definition.type);
- Expect.equals(definition.type.typeArguments.slowLength(),
- type.typeArguments.length);
+ Expect.equals(
+ definition.type.typeArguments.slowLength(), type.typeArguments.length);
int index = 0;
for (DartType argument in type.typeArguments) {
Expect.equals(true, index < expectedElements.length);
@@ -164,22 +163,18 @@
compiler.parseScript('class Foo<T, U> {}');
ClassElement foo = compiler.mainApp.find('Foo');
matchResolvedTypes(visitor, 'Foo<int, String> x;', 'Foo',
- [compiler.coreClasses.intClass,
- compiler.coreClasses.stringClass]);
- matchResolvedTypes(visitor, 'Foo<Foo, Foo> x;', 'Foo',
- [foo, foo]);
+ [compiler.coreClasses.intClass, compiler.coreClasses.stringClass]);
+ matchResolvedTypes(visitor, 'Foo<Foo, Foo> x;', 'Foo', [foo, foo]);
}),
-
MockCompiler.create((MockCompiler compiler) {
compiler.parseScript('class Foo<T, U> {}');
compiler.resolveStatement('Foo<notype, int> x;');
DiagnosticCollector collector = compiler.diagnosticCollector;
Expect.equals(1, collector.warnings.length);
Expect.equals(MessageKind.CANNOT_RESOLVE_TYPE,
- collector.warnings.first.message.kind);
+ collector.warnings.first.message.kind);
Expect.equals(0, collector.errors.length);
}),
-
MockCompiler.create((MockCompiler compiler) {
compiler.parseScript('class Foo<T, U> {}');
compiler.resolveStatement('var x = new Foo<notype, int>();');
@@ -187,15 +182,14 @@
Expect.equals(1, collector.warnings.length);
Expect.equals(0, collector.errors.length);
Expect.equals(MessageKind.CANNOT_RESOLVE_TYPE,
- collector.warnings.first.message.kind);
+ collector.warnings.first.message.kind);
}),
-
MockCompiler.create((MockCompiler compiler) {
compiler.parseScript('class Foo<T> {'
- ' Foo<T> t;'
- ' foo(Foo<T> f) {}'
- ' bar() { g(Foo<T> f) {}; g(); }'
- '}');
+ ' Foo<T> t;'
+ ' foo(Foo<T> f) {}'
+ ' bar() { g(Foo<T> f) {}; g(); }'
+ '}');
ClassElement foo = compiler.mainApp.find('Foo');
foo.ensureResolved(compiler.resolution);
MemberElement tMember = foo.lookupLocalMember('t');
@@ -226,8 +220,7 @@
compiler.resolution,
fooB,
new ResolutionRegistry(
- compiler.backend,
- new CollectingTreeElements(fooB)),
+ compiler.backend, new CollectingTreeElements(fooB)),
scope: new MockTypeVariablesScope(classB.buildScope()));
FunctionExpression node =
(fooB as FunctionElementX).parseNode(compiler.parsingContext);
@@ -253,12 +246,12 @@
Expect.equals(0, collector.warnings.length);
Expect.equals(1, collector.errors.length);
Expect.equals(MessageKind.SWITCH_CASE_TYPES_NOT_EQUAL,
- collector.errors.first.message.kind);
+ collector.errors.first.message.kind);
Expect.equals(2, collector.infos.length);
Expect.equals(MessageKind.SWITCH_CASE_TYPES_NOT_EQUAL_CASE,
- collector.infos.first.message.kind);
+ collector.infos.first.message.kind);
Expect.equals(MessageKind.SWITCH_CASE_TYPES_NOT_EQUAL_CASE,
- collector.infos.elementAt(1).message.kind);
+ collector.infos.elementAt(1).message.kind);
});
}
@@ -290,7 +283,7 @@
Expect.equals(0, collector.warnings.length);
Expect.equals(1, collector.errors.length);
Expect.equals(MessageKind.NO_INSTANCE_AVAILABLE,
- collector.errors.first.message.kind);
+ collector.errors.first.message.kind);
}),
MockCompiler.create((MockCompiler compiler) {
compiler.parseScript("class Foo { static foo() { return this; } }");
@@ -310,38 +303,67 @@
Expect.equals(0, collector.warnings.length);
Expect.equals(1, collector.errors.length);
Expect.equals(MessageKind.NO_INSTANCE_AVAILABLE,
- collector.errors.first.message.kind);
+ collector.errors.first.message.kind);
}),
]);
}
Future testLocalsOne() {
return Future.forEach([
- () => testLocals([["foo", false]]),
- () => testLocals([["foo", false], ["bar", false]]),
- () => testLocals([["foo", false], ["bar", false], ["foobar", false]]),
-
- () => testLocals([["foo", true]]),
- () => testLocals([["foo", false], ["bar", true]]),
- () => testLocals([["foo", true], ["bar", true]]),
-
- () => testLocals([["foo", false], ["bar", false], ["foobar", true]]),
- () => testLocals([["foo", false], ["bar", true], ["foobar", true]]),
- () => testLocals([["foo", true], ["bar", true], ["foobar", true]]),
-
- () => testLocals([["foo", false], ["foo", false]])
- .then((MockCompiler compiler) {
- DiagnosticCollector collector = compiler.diagnosticCollector;
- Expect.equals(1, collector.errors.length);
- Expect.equals(
- new Message(
- MessageTemplate.TEMPLATES[MessageKind.DUPLICATE_DEFINITION],
- {'name': 'foo'}, false),
- collector.errors.first.message);
- })], (f) => f());
+ () => testLocals([
+ ["foo", false]
+ ]),
+ () => testLocals([
+ ["foo", false],
+ ["bar", false]
+ ]),
+ () => testLocals([
+ ["foo", false],
+ ["bar", false],
+ ["foobar", false]
+ ]),
+ () => testLocals([
+ ["foo", true]
+ ]),
+ () => testLocals([
+ ["foo", false],
+ ["bar", true]
+ ]),
+ () => testLocals([
+ ["foo", true],
+ ["bar", true]
+ ]),
+ () => testLocals([
+ ["foo", false],
+ ["bar", false],
+ ["foobar", true]
+ ]),
+ () => testLocals([
+ ["foo", false],
+ ["bar", true],
+ ["foobar", true]
+ ]),
+ () => testLocals([
+ ["foo", true],
+ ["bar", true],
+ ["foobar", true]
+ ]),
+ () => testLocals([
+ ["foo", false],
+ ["foo", false]
+ ]).then((MockCompiler compiler) {
+ DiagnosticCollector collector = compiler.diagnosticCollector;
+ Expect.equals(1, collector.errors.length);
+ Expect.equals(
+ new Message(
+ MessageTemplate.TEMPLATES[MessageKind.DUPLICATE_DEFINITION],
+ {'name': 'foo'},
+ false),
+ collector.errors.first.message);
+ })
+ ], (f) => f());
}
-
Future testLocalsTwo() {
return MockCompiler.create((MockCompiler compiler) {
ResolverVisitor visitor = compiler.resolverVisitor();
@@ -400,20 +422,20 @@
List statements1 = thenPart.statements.nodes.toList();
Node def1 = statements1[0].definitions.nodes.head;
Node id1 = statements1[1].expression;
- Expect.equals(visitor.registry.mapping[def1],
- visitor.registry.mapping[id1]);
+ Expect.equals(
+ visitor.registry.mapping[def1], visitor.registry.mapping[id1]);
Block elsePart = tree.elsePart;
List statements2 = elsePart.statements.nodes.toList();
Node def2 = statements2[0].definitions.nodes.head;
Node id2 = statements2[1].expression;
- Expect.equals(visitor.registry.mapping[def2],
- visitor.registry.mapping[id2]);
+ Expect.equals(
+ visitor.registry.mapping[def2], visitor.registry.mapping[id2]);
- Expect.notEquals(visitor.registry.mapping[def1],
- visitor.registry.mapping[def2]);
- Expect.notEquals(visitor.registry.mapping[id1],
- visitor.registry.mapping[id2]);
+ Expect.notEquals(
+ visitor.registry.mapping[def1], visitor.registry.mapping[def2]);
+ Expect.notEquals(
+ visitor.registry.mapping[id1], visitor.registry.mapping[id2]);
});
}
@@ -434,8 +456,8 @@
Return ret = body.statements.nodes.head;
Send use = ret.expression;
Expect.equals(ElementKind.PARAMETER, visitor.registry.mapping[use].kind);
- Expect.equals(visitor.registry.mapping[param],
- visitor.registry.mapping[use]);
+ Expect.equals(
+ visitor.registry.mapping[param], visitor.registry.mapping[use]);
});
}
@@ -488,7 +510,7 @@
checkSend(Element expected, Node node, Element actual) {
Expect.isTrue(node is Send, node.toDebugString());
- Expect.isTrue(node is !SendSet, node.toDebugString());
+ Expect.isTrue(node is! SendSet, node.toDebugString());
Expect.equals(expected, actual);
}
@@ -509,8 +531,7 @@
Expect.equals(1, collector.warnings.length);
Expect.equals(
- new Message(
- MessageTemplate.TEMPLATES[MessageKind.CANNOT_RESOLVE_TYPE],
+ new Message(MessageTemplate.TEMPLATES[MessageKind.CANNOT_RESOLVE_TYPE],
{'typeName': 'Foo'}, false),
collector.warnings.first.message);
collector.clear();
@@ -537,7 +558,8 @@
Expect.equals(1, collector.errors.length);
var cannotResolveBar = new Message(
MessageTemplate.TEMPLATES[MessageKind.CANNOT_EXTEND_MALFORMED],
- {'className': 'Foo', 'malformedType': 'Bar'}, false);
+ {'className': 'Foo', 'malformedType': 'Bar'},
+ false);
Expect.equals(cannotResolveBar, collector.errors.first.message);
collector.clear();
}),
@@ -549,8 +571,8 @@
ClassElement fooElement = compiler.mainApp.find('Foo');
ClassElement barElement = compiler.mainApp.find('Bar');
- Expect.equals(barElement.computeType(compiler.resolution),
- fooElement.supertype);
+ Expect.equals(
+ barElement.computeType(compiler.resolution), fooElement.supertype);
Expect.isTrue(fooElement.interfaces.isEmpty);
Expect.isTrue(barElement.interfaces.isEmpty);
}),
@@ -564,8 +586,7 @@
DiagnosticCollector collector = compiler.diagnosticCollector;
Expect.equals(1, collector.errors.length);
Expect.equals(
- new Message(
- MessageTemplate.TEMPLATES[MessageKind.CANNOT_RESOLVE_TYPE],
+ new Message(MessageTemplate.TEMPLATES[MessageKind.CANNOT_RESOLVE_TYPE],
{'typeName': 'var'}, false),
collector.errors.first.message);
collector.clear();
@@ -579,8 +600,7 @@
DiagnosticCollector collector = compiler.diagnosticCollector;
Expect.equals(1, collector.errors.length);
Expect.equals(
- new Message(
- MessageTemplate.TEMPLATES[MessageKind.CANNOT_RESOLVE_TYPE],
+ new Message(MessageTemplate.TEMPLATES[MessageKind.CANNOT_RESOLVE_TYPE],
{'typeName': 'bar'}, false),
collector.errors.first.message);
collector.clear();
@@ -593,8 +613,7 @@
compiler.resolution,
null,
new ResolutionRegistry(
- compiler.backend,
- new CollectingTreeElements(null)));
+ compiler.backend, new CollectingTreeElements(null)));
compiler.resolveStatement("Foo bar;");
ClassElement fooElement = compiler.mainApp.find('Foo');
@@ -604,15 +623,14 @@
Expect.isTrue(barElement.interfaces.isEmpty);
Expect.equals(barElement.computeType(compiler.resolution),
- fooElement.interfaces.head);
+ fooElement.interfaces.head);
Expect.equals(1, length(fooElement.interfaces));
});
}
Future testTwoInterfaces() {
return MockCompiler.create((MockCompiler compiler) {
- compiler.parseScript(
- """abstract class I1 {}
+ compiler.parseScript("""abstract class I1 {}
abstract class I2 {}
class C implements I1, I2 {}""");
compiler.resolveStatement("Foo bar;");
@@ -695,13 +713,12 @@
});
}
-Future resolveConstructor(
- String script, String statement, String className,
+Future resolveConstructor(String script, String statement, String className,
String constructor, int expectedElementCount,
{List expectedWarnings: const [],
- List expectedErrors: const [],
- List expectedInfos: const [],
- Map<String, String> corelib}) {
+ List expectedErrors: const [],
+ List expectedInfos: const [],
+ Map<String, String> corelib}) {
MockCompiler compiler = new MockCompiler.internal(coreSource: corelib);
return compiler.init().then((_) {
compiler.parseScript(script);
@@ -714,8 +731,7 @@
compiler.resolution,
element,
new ResolutionRegistry(
- compiler.backend,
- new CollectingTreeElements(element)),
+ compiler.backend, new CollectingTreeElements(element)),
scope: classElement.buildScope());
new InitializerResolver(visitor, element, tree).resolveInitializers();
visitor.visit(tree.body);
@@ -741,7 +757,7 @@
Expect.equals(0, collector.warnings.length);
Expect.equals(1, collector.errors.length);
Expect.equals(MessageKind.CYCLIC_CLASS_HIERARCHY,
- collector.errors.first.message.kind);
+ collector.errors.first.message.kind);
}),
MockCompiler.create((MockCompiler compiler) {
compiler.parseScript("""class A extends B {}
@@ -753,9 +769,9 @@
Expect.equals(0, collector.warnings.length);
Expect.equals(2, collector.errors.length);
Expect.equals(MessageKind.CYCLIC_CLASS_HIERARCHY,
- collector.errors.first.message.kind);
+ collector.errors.first.message.kind);
Expect.equals(MessageKind.CANNOT_FIND_UNNAMED_CONSTRUCTOR,
- collector.errors.elementAt(1).message.kind);
+ collector.errors.elementAt(1).message.kind);
}),
MockCompiler.create((MockCompiler compiler) {
compiler.parseScript("""abstract class A extends B {}
@@ -768,7 +784,7 @@
Expect.equals(0, collector.warnings.length);
Expect.equals(1, collector.errors.length);
Expect.equals(MessageKind.CYCLIC_CLASS_HIERARCHY,
- collector.errors.first.message.kind);
+ collector.errors.first.message.kind);
}),
MockCompiler.create((MockCompiler compiler) {
compiler.parseScript("""class A extends B {}
@@ -783,7 +799,7 @@
ClassElement aElement = compiler.mainApp.find("A");
Link<DartType> supertypes = aElement.allSupertypes;
Expect.equals(<String>['B', 'C', 'Object'].toString(),
- asSortedStrings(supertypes).toString());
+ asSortedStrings(supertypes).toString());
}),
MockCompiler.create((MockCompiler compiler) {
compiler.parseScript("""class A<T> {}
@@ -800,9 +816,14 @@
ClassElement aElement = compiler.mainApp.find("C");
Link<DartType> supertypes = aElement.allSupertypes;
// Object is once per inheritance path, that is from both A and I.
- Expect.equals(<String>['A<int>', 'B<bool, String>',
- 'I<bool, List<String>>', 'Object'].toString(),
- asSortedStrings(supertypes).toString());
+ Expect.equals(
+ <String>[
+ 'A<int>',
+ 'B<bool, String>',
+ 'I<bool, List<String>>',
+ 'Object'
+ ].toString(),
+ asSortedStrings(supertypes).toString());
}),
MockCompiler.create((MockCompiler compiler) {
compiler.parseScript("""class A<T> {}
@@ -817,7 +838,7 @@
ClassElement aElement = compiler.mainApp.find("E");
Link<DartType> supertypes = aElement.allSupertypes;
Expect.equals(<String>['A<E>', 'D', 'Object'].toString(),
- asSortedStrings(supertypes).toString());
+ asSortedStrings(supertypes).toString());
}),
MockCompiler.create((MockCompiler compiler) {
compiler.parseScript("""class A<T> {}
@@ -828,8 +849,8 @@
DiagnosticCollector collector = compiler.diagnosticCollector;
Expect.equals(0, collector.warnings.length);
Expect.equals(1, collector.errors.length);
- Expect.equals(MessageKind.MULTI_INHERITANCE,
- collector.errors.first.message.kind);
+ Expect.equals(
+ MessageKind.MULTI_INHERITANCE, collector.errors.first.message.kind);
Expect.equals(0, collector.crashes.length);
}),
]);
@@ -845,11 +866,10 @@
compiler.resolver.resolve(mainElement);
DiagnosticCollector collector = compiler.diagnosticCollector;
Expect.equals(0, collector.warnings.length,
- 'Unexpected warnings: ${collector.warnings}');
- Expect.equals(1, collector.errors.length,
- 'Unexpected errors: ${collector.errors}');
+ 'Unexpected warnings: ${collector.warnings}');
+ Expect.equals(
+ 1, collector.errors.length, 'Unexpected errors: ${collector.errors}');
}),
-
MockCompiler.create((MockCompiler compiler) {
compiler.parseScript("""enum Enum { A }
main() { Enum e = Enum.A; }""");
@@ -857,11 +877,10 @@
compiler.resolver.resolve(mainElement);
DiagnosticCollector collector = compiler.diagnosticCollector;
Expect.equals(0, collector.warnings.length,
- 'Unexpected warnings: ${collector.warnings}');
- Expect.equals(0, collector.errors.length,
- 'Unexpected errors: ${collector.errors}');
+ 'Unexpected warnings: ${collector.warnings}');
+ Expect.equals(
+ 0, collector.errors.length, 'Unexpected errors: ${collector.errors}');
}),
-
MockCompiler.create((MockCompiler compiler) {
compiler.parseScript("""enum Enum { A }
main() { Enum e = Enum.B; }""");
@@ -869,13 +888,12 @@
compiler.resolver.resolve(mainElement);
DiagnosticCollector collector = compiler.diagnosticCollector;
Expect.equals(1, collector.warnings.length,
- 'Unexpected warnings: ${collector.warnings}');
- Expect.equals(MessageKind.UNDEFINED_GETTER,
- collector.warnings.first.message.kind);
- Expect.equals(0, collector.errors.length,
- 'Unexpected errors: ${collector.errors}');
+ 'Unexpected warnings: ${collector.warnings}');
+ Expect.equals(
+ MessageKind.UNDEFINED_GETTER, collector.warnings.first.message.kind);
+ Expect.equals(
+ 0, collector.errors.length, 'Unexpected errors: ${collector.errors}');
}),
-
MockCompiler.create((MockCompiler compiler) {
compiler.parseScript("""enum Enum { A }
main() { List values = Enum.values; }""");
@@ -883,11 +901,10 @@
compiler.resolver.resolve(mainElement);
DiagnosticCollector collector = compiler.diagnosticCollector;
Expect.equals(0, collector.warnings.length,
- 'Unexpected warnings: ${collector.warnings}');
- Expect.equals(0, collector.errors.length,
- 'Unexpected errors: ${collector.errors}');
+ 'Unexpected warnings: ${collector.warnings}');
+ Expect.equals(
+ 0, collector.errors.length, 'Unexpected errors: ${collector.errors}');
}),
-
MockCompiler.create((MockCompiler compiler) {
compiler.parseScript("""enum Enum { A }
main() { new Enum(0, ''); }""");
@@ -895,13 +912,12 @@
compiler.resolver.resolve(mainElement);
DiagnosticCollector collector = compiler.diagnosticCollector;
Expect.equals(0, collector.warnings.length,
- 'Unexpected warnings: ${collector.warnings}');
- Expect.equals(1, collector.errors.length,
- 'Unexpected errors: ${collector.errors}');
+ 'Unexpected warnings: ${collector.warnings}');
+ Expect.equals(
+ 1, collector.errors.length, 'Unexpected errors: ${collector.errors}');
Expect.equals(MessageKind.CANNOT_INSTANTIATE_ENUM,
- collector.errors.first.message.kind);
+ collector.errors.first.message.kind);
}),
-
MockCompiler.create((MockCompiler compiler) {
compiler.parseScript("""enum Enum { A }
main() { const Enum(0, ''); }""");
@@ -909,11 +925,11 @@
compiler.resolver.resolve(mainElement);
DiagnosticCollector collector = compiler.diagnosticCollector;
Expect.equals(0, collector.warnings.length,
- 'Unexpected warnings: ${collector.warnings}');
- Expect.equals(1, collector.errors.length,
- 'Unexpected errors: ${collector.errors}');
+ 'Unexpected warnings: ${collector.warnings}');
+ Expect.equals(
+ 1, collector.errors.length, 'Unexpected errors: ${collector.errors}');
Expect.equals(MessageKind.CANNOT_INSTANTIATE_ENUM,
- collector.errors.first.message.kind);
+ collector.errors.first.message.kind);
}),
]);
}
@@ -921,16 +937,14 @@
Future testInitializers() {
return Future.forEach([
() {
- String script =
- """class A {
+ String script = """class A {
int foo; int bar;
A() : this.foo = 1, bar = 2;
}""";
return resolveConstructor(script, "A a = new A();", "A", "", 2);
},
() {
- String script =
- """class A {
+ String script = """class A {
int foo; A a;
A() : a.foo = 1;
}""";
@@ -939,8 +953,7 @@
expectedErrors: [MessageKind.INVALID_RECEIVER_IN_INITIALIZER]);
},
() {
- String script =
- """class A {
+ String script = """class A {
int foo;
A() : this.foo = 1, this.foo = 2;
}""";
@@ -949,17 +962,14 @@
expectedErrors: [MessageKind.DUPLICATE_INITIALIZER]);
},
() {
- String script =
- """class A {
+ String script = """class A {
A() : this.foo = 1;
}""";
return resolveConstructor(script, "A a = new A();", "A", "", 1,
- expectedWarnings: [],
- expectedErrors: [MessageKind.CANNOT_RESOLVE]);
+ expectedWarnings: [], expectedErrors: [MessageKind.CANNOT_RESOLVE]);
},
() {
- String script =
- """class A {
+ String script = """class A {
int foo;
int bar;
A() : this.foo = bar;
@@ -969,8 +979,7 @@
expectedErrors: [MessageKind.NO_INSTANCE_AVAILABLE]);
},
() {
- String script =
- """class A {
+ String script = """class A {
int foo() => 42;
A() : foo();
}""";
@@ -979,8 +988,7 @@
expectedErrors: [MessageKind.CONSTRUCTOR_CALL_EXPECTED]);
},
() {
- String script =
- """class A {
+ String script = """class A {
int i;
A.a() : this.b(0);
A.b(int i);
@@ -988,20 +996,19 @@
return resolveConstructor(script, "A a = new A.a();", "A", "a", 1);
},
() {
- String script =
- """class A {
+ String script = """class A {
int i;
A.a() : i = 42, this(0);
A(int i);
}""";
return resolveConstructor(script, "A a = new A.a();", "A", "a", 2,
expectedWarnings: [],
- expectedErrors:
- [MessageKind.REDIRECTING_CONSTRUCTOR_HAS_INITIALIZER]);
+ expectedErrors: [
+ MessageKind.REDIRECTING_CONSTRUCTOR_HAS_INITIALIZER
+ ]);
},
() {
- String script =
- """class A {
+ String script = """class A {
int i;
A(i);
}
@@ -1011,8 +1018,7 @@
return resolveConstructor(script, "B a = new B();", "B", "", 1);
},
() {
- String script =
- """class A {
+ String script = """class A {
int i;
A(i);
}
@@ -1025,10 +1031,11 @@
},
() {
String script = "";
- final INVALID_OBJECT =
- const { 'Object': 'class Object { Object() : super(); }' };
- return resolveConstructor(script,
- "Object o = new Object();", "Object", "", 1,
+ final INVALID_OBJECT = const {
+ 'Object': 'class Object { Object() : super(); }'
+ };
+ return resolveConstructor(
+ script, "Object o = new Object();", "Object", "", 1,
expectedWarnings: [],
expectedErrors: [MessageKind.SUPER_INITIALIZER_IN_OBJECT],
corelib: INVALID_OBJECT);
@@ -1064,12 +1071,24 @@
'const <int>[0, 1, 2]': const ['0', '1', '2', 'const <int>[0, 1, 2]'],
'const {}': const ['const {}'],
'const <String, int>{}': const ['const <String, int>{}'],
- 'const {"a": 0, "b": 1, "c": 2}':
- const ['"a"', '0', '"b"', '1', '"c"', '2',
- 'const {"a": 0, "b": 1, "c": 2}'],
- 'const <String, int>{"a": 0, "b": 1, "c": 2}':
- const ['"a"', '0', '"b"', '1', '"c"', '2',
- 'const <String, int>{"a": 0, "b": 1, "c": 2}'],
+ 'const {"a": 0, "b": 1, "c": 2}': const [
+ '"a"',
+ '0',
+ '"b"',
+ '1',
+ '"c"',
+ '2',
+ 'const {"a": 0, "b": 1, "c": 2}'
+ ],
+ 'const <String, int>{"a": 0, "b": 1, "c": 2}': const [
+ '"a"',
+ '0',
+ '"b"',
+ '1',
+ '"c"',
+ '2',
+ 'const <String, int>{"a": 0, "b": 1, "c": 2}'
+ ],
};
return Future.forEach(testedConstants.keys, (String constant) {
return MockCompiler.create((MockCompiler compiler) {
@@ -1082,11 +1101,15 @@
List<ConstantExpression> constants = elements.constants;
String constantsText =
'[${constants.map((c) => c.toDartText()).join(', ')}]';
- Expect.equals(expectedConstants.length, constants.length,
+ Expect.equals(
+ expectedConstants.length,
+ constants.length,
"Expected ${expectedConstants.length} constants for `${constant}` "
"found $constantsText.");
for (int index = 0; index < expectedConstants.length; index++) {
- Expect.equals(expectedConstants[index], constants[index].toDartText(),
+ Expect.equals(
+ expectedConstants[index],
+ constants[index].toDartText(),
"Expected ${expectedConstants} for `$constant`, "
"found $constantsText.");
}
@@ -1121,15 +1144,14 @@
ClassElement cls = findElement(compiler, className);
Element memberElement = cls.lookupLocalMember(memberName);
Expect.isNotNull(memberElement);
- Expect.isTrue(
- compiler.enqueuer.resolution.hasBeenProcessed(memberElement));
+ Expect.isTrue(compiler.enqueuer.resolution.hasBeenProcessed(memberElement));
}
testToString() {
final script = r"class C { toString() => 'C'; } main() { '${new C()}'; }";
asyncTest(() => compileScript(script).then((compiler) {
- checkMemberResolved(compiler, 'C', 'toString');
- }));
+ checkMemberResolved(compiler, 'C', 'toString');
+ }));
}
operatorName(op, isUnary) {
@@ -1144,9 +1166,9 @@
}
main() { var c = new C(); c[0]++; }""";
asyncTest(() => compileScript(script).then((compiler) {
- checkMemberResolved(compiler, 'C', operatorName('[]', false));
- checkMemberResolved(compiler, 'C', operatorName('[]=', false));
- }));
+ checkMemberResolved(compiler, 'C', operatorName('[]', false));
+ checkMemberResolved(compiler, 'C', operatorName('[]=', false));
+ }));
}
testIncrementsAndDecrements() {
@@ -1166,11 +1188,11 @@
--d;
}""";
asyncTest(() => compileScript(script).then((compiler) {
- checkMemberResolved(compiler, 'A', operatorName('+', false));
- checkMemberResolved(compiler, 'B', operatorName('+', false));
- checkMemberResolved(compiler, 'C', operatorName('-', false));
- checkMemberResolved(compiler, 'D', operatorName('-', false));
- }));
+ checkMemberResolved(compiler, 'A', operatorName('+', false));
+ checkMemberResolved(compiler, 'B', operatorName('+', false));
+ checkMemberResolved(compiler, 'C', operatorName('-', false));
+ checkMemberResolved(compiler, 'D', operatorName('-', false));
+ }));
}
testOverrideHashCodeCheck() {
@@ -1186,26 +1208,26 @@
new A() == new B();
}""";
asyncTest(() => compileScript(script).then((compiler) {
- DiagnosticCollector collector = compiler.diagnosticCollector;
- Expect.equals(0, collector.warnings.length);
- Expect.equals(0, collector.infos.length);
- Expect.equals(1, collector.hints.length);
- Expect.equals(MessageKind.OVERRIDE_EQUALS_NOT_HASH_CODE,
- collector.hints.first.message.kind);
- Expect.equals(0, collector.errors.length);
- }));
+ DiagnosticCollector collector = compiler.diagnosticCollector;
+ Expect.equals(0, collector.warnings.length);
+ Expect.equals(0, collector.infos.length);
+ Expect.equals(1, collector.hints.length);
+ Expect.equals(MessageKind.OVERRIDE_EQUALS_NOT_HASH_CODE,
+ collector.hints.first.message.kind);
+ Expect.equals(0, collector.errors.length);
+ }));
}
testConstConstructorAndNonFinalFields() {
void expect(compiler, List errors, List infos) {
DiagnosticCollector collector = compiler.diagnosticCollector;
Expect.equals(errors.length, collector.errors.length);
- for (int i = 0 ; i < errors.length ; i++) {
+ for (int i = 0; i < errors.length; i++) {
Expect.equals(errors[i], collector.errors.elementAt(i).message.kind);
}
Expect.equals(0, collector.warnings.length);
Expect.equals(infos.length, collector.infos.length);
- for (int i = 0 ; i < infos.length ; i++) {
+ for (int i = 0; i < infos.length; i++) {
Expect.equals(infos[i], collector.infos.elementAt(i).message.kind);
}
}
@@ -1219,10 +1241,9 @@
new A(0);
}""";
asyncTest(() => compileScript(script1).then((compiler) {
- expect(compiler,
- [MessageKind.CONST_CONSTRUCTOR_WITH_NONFINAL_FIELDS],
- [MessageKind.CONST_CONSTRUCTOR_WITH_NONFINAL_FIELDS_FIELD]);
- }));
+ expect(compiler, [MessageKind.CONST_CONSTRUCTOR_WITH_NONFINAL_FIELDS],
+ [MessageKind.CONST_CONSTRUCTOR_WITH_NONFINAL_FIELDS_FIELD]);
+ }));
final script2 = r"""
class A {
@@ -1235,41 +1256,52 @@
new A(0, 1);
}""";
asyncTest(() => compileScript(script2).then((compiler) {
- expect(compiler,
- [MessageKind.CONST_CONSTRUCTOR_WITH_NONFINAL_FIELDS],
- [MessageKind.CONST_CONSTRUCTOR_WITH_NONFINAL_FIELDS_CONSTRUCTOR,
- MessageKind.CONST_CONSTRUCTOR_WITH_NONFINAL_FIELDS_CONSTRUCTOR,
- MessageKind.CONST_CONSTRUCTOR_WITH_NONFINAL_FIELDS_FIELD,
- MessageKind.CONST_CONSTRUCTOR_WITH_NONFINAL_FIELDS_FIELD]);
- }));
+ expect(compiler, [
+ MessageKind.CONST_CONSTRUCTOR_WITH_NONFINAL_FIELDS
+ ], [
+ MessageKind.CONST_CONSTRUCTOR_WITH_NONFINAL_FIELDS_CONSTRUCTOR,
+ MessageKind.CONST_CONSTRUCTOR_WITH_NONFINAL_FIELDS_CONSTRUCTOR,
+ MessageKind.CONST_CONSTRUCTOR_WITH_NONFINAL_FIELDS_FIELD,
+ MessageKind.CONST_CONSTRUCTOR_WITH_NONFINAL_FIELDS_FIELD
+ ]);
+ }));
}
testCantAssignMethods() {
// Can't override local functions
- checkWarningOn('''
+ checkWarningOn(
+ '''
main() {
mname() { mname = 2; };
mname();
}
- ''', [MessageKind.ASSIGNING_METHOD]);
+ ''',
+ [MessageKind.ASSIGNING_METHOD]);
- checkWarningOn('''
+ checkWarningOn(
+ '''
main() {
mname() { };
mname = 3;
}
- ''', [MessageKind.ASSIGNING_METHOD]);
+ ''',
+ [MessageKind.ASSIGNING_METHOD]);
// Can't override top-level functions
- checkWarningOn('''
+ checkWarningOn(
+ '''
m() {}
main() { m = 4; }
- ''', [MessageKind.ASSIGNING_METHOD,
- // TODO(johnniwinther): Avoid duplicate warnings.
- MessageKind.NOT_ASSIGNABLE]);
+ ''',
+ [
+ MessageKind.ASSIGNING_METHOD,
+ // TODO(johnniwinther): Avoid duplicate warnings.
+ MessageKind.NOT_ASSIGNABLE
+ ]);
// Can't override instance methods
- checkWarningOn('''
+ checkWarningOn(
+ '''
main() { new B().bar(); }
class B {
mname() {}
@@ -1277,8 +1309,10 @@
mname = () => null;
}
}
- ''', [MessageKind.UNDEFINED_SETTER]);
- checkWarningOn('''
+ ''',
+ [MessageKind.UNDEFINED_SETTER]);
+ checkWarningOn(
+ '''
main() { new B().bar(); }
class B {
mname() {}
@@ -1286,10 +1320,12 @@
this.mname = () => null;
}
}
- ''', [MessageKind.UNDEFINED_SETTER]);
+ ''',
+ [MessageKind.UNDEFINED_SETTER]);
// Can't override super methods
- checkWarningOn('''
+ checkWarningOn(
+ '''
main() { new B().bar(); }
class A {
mname() {}
@@ -1299,12 +1335,16 @@
super.mname = () => 6;
}
}
- ''', [MessageKind.ASSIGNING_METHOD_IN_SUPER,
- // TODO(johnniwinther): Avoid duplicate warnings.
- MessageKind.UNDEFINED_SETTER]);
+ ''',
+ [
+ MessageKind.ASSIGNING_METHOD_IN_SUPER,
+ // TODO(johnniwinther): Avoid duplicate warnings.
+ MessageKind.UNDEFINED_SETTER
+ ]);
// But index operators should be OK
- checkWarningOn('''
+ checkWarningOn(
+ '''
main() { new B().bar(); }
class B {
operator[]=(x, y) {}
@@ -1312,8 +1352,10 @@
this[1] = 3; // This is OK
}
}
- ''', []);
- checkWarningOn('''
+ ''',
+ []);
+ checkWarningOn(
+ '''
main() { new B().bar(); }
class A {
operator[]=(x, y) {}
@@ -1323,53 +1365,67 @@
super[1] = 3; // This is OK
}
}
- ''', []);
+ ''',
+ []);
}
testCantAssignFinalAndConsts() {
// Can't write final or const locals.
- checkWarningOn('''
+ checkWarningOn(
+ '''
main() {
final x = 1;
x = 2;
}
- ''', [MessageKind.UNDEFINED_STATIC_SETTER_BUT_GETTER]);
- checkWarningOn('''
+ ''',
+ [MessageKind.UNDEFINED_STATIC_SETTER_BUT_GETTER]);
+ checkWarningOn(
+ '''
main() {
const x = 1;
x = 2;
}
- ''', [MessageKind.UNDEFINED_STATIC_SETTER_BUT_GETTER]);
- checkWarningOn('''
+ ''',
+ [MessageKind.UNDEFINED_STATIC_SETTER_BUT_GETTER]);
+ checkWarningOn(
+ '''
final x = 1;
main() { x = 3; }
- ''', [MessageKind.UNDEFINED_STATIC_SETTER_BUT_GETTER]);
+ ''',
+ [MessageKind.UNDEFINED_STATIC_SETTER_BUT_GETTER]);
- checkWarningOn('''
+ checkWarningOn(
+ '''
const x = 1;
main() { x = 3; }
- ''', [MessageKind.UNDEFINED_STATIC_SETTER_BUT_GETTER]);
+ ''',
+ [MessageKind.UNDEFINED_STATIC_SETTER_BUT_GETTER]);
// Detect assignments to final fields:
- checkWarningOn('''
+ checkWarningOn(
+ '''
main() => new B().m();
class B {
final x = 1;
m() { x = 2; }
}
- ''', [MessageKind.UNDEFINED_SETTER]);
+ ''',
+ [MessageKind.UNDEFINED_SETTER]);
// ... even if 'this' is explicit:
- checkWarningOn('''
+ checkWarningOn(
+ '''
main() => new B().m();
class B {
final x = 1;
m() { this.x = 2; }
}
- ''', [MessageKind.UNDEFINED_SETTER]);
+ ''',
+ [MessageKind.UNDEFINED_SETTER]);
// ... and in super class:
- checkWarningOn('''
+ checkWarningOn(
+ '''
main() => new B().m();
class A {
final x = 1;
@@ -1377,12 +1433,16 @@
class B extends A {
m() { super.x = 2; }
}
- ''', [MessageKind.ASSIGNING_FINAL_FIELD_IN_SUPER,
- // TODO(johnniwinther): Avoid duplicate warnings.
- MessageKind.UNDEFINED_SETTER]);
+ ''',
+ [
+ MessageKind.ASSIGNING_FINAL_FIELD_IN_SUPER,
+ // TODO(johnniwinther): Avoid duplicate warnings.
+ MessageKind.UNDEFINED_SETTER
+ ]);
// But non-final fields are OK:
- checkWarningOn('''
+ checkWarningOn(
+ '''
main() => new B().m();
class A {
int x = 1;
@@ -1390,10 +1450,12 @@
class B extends A {
m() { super.x = 2; }
}
- ''', []);
+ ''',
+ []);
// Check getter without setter.
- checkWarningOn('''
+ checkWarningOn(
+ '''
main() => new B().m();
class A {
get x => 1;
@@ -1401,25 +1463,31 @@
class B extends A {
m() { super.x = 2; }
}
- ''', [MessageKind.UNDEFINED_SUPER_SETTER,
- // TODO(johnniwinther): Avoid duplicate warnings.
- MessageKind.UNDEFINED_SETTER]);
+ ''',
+ [
+ MessageKind.UNDEFINED_SUPER_SETTER,
+ // TODO(johnniwinther): Avoid duplicate warnings.
+ MessageKind.UNDEFINED_SETTER
+ ]);
}
/// Helper to test that [script] produces all the given [warnings].
checkWarningOn(String script, List<MessageKind> warnings) {
Expect.isTrue(warnings.length >= 0 && warnings.length <= 2);
asyncTest(() => compileScript(script).then((compiler) {
- DiagnosticCollector collector = compiler.diagnosticCollector;
- Expect.equals(0, collector.errors.length,
- 'Unexpected errors in\n$script\n${collector.errors}');
- Expect.equals(warnings.length, collector.warnings.length,
- 'Unexpected warnings in\n$script\n'
- 'Expected:$warnings\nFound:${collector.warnings}');
- for (int i = 0; i < warnings.length; i++) {
- Expect.equals(warnings[i], collector.warnings.elementAt(i).message.kind);
- }
- }));
+ DiagnosticCollector collector = compiler.diagnosticCollector;
+ Expect.equals(0, collector.errors.length,
+ 'Unexpected errors in\n$script\n${collector.errors}');
+ Expect.equals(
+ warnings.length,
+ collector.warnings.length,
+ 'Unexpected warnings in\n$script\n'
+ 'Expected:$warnings\nFound:${collector.warnings}');
+ for (int i = 0; i < warnings.length; i++) {
+ Expect.equals(
+ warnings[i], collector.warnings.elementAt(i).message.kind);
+ }
+ }));
}
testAwaitHint() {
@@ -1427,36 +1495,45 @@
var prefix = className == null
? "Cannot resolve 'await'"
: "No member named 'await' in class '$className'";
- var where = functionName == null
- ? 'the enclosing function' : "'$functionName'";
+ var where =
+ functionName == null ? 'the enclosing function' : "'$functionName'";
asyncTest(() => compileScript(script).then((compiler) {
- DiagnosticCollector collector = compiler.diagnosticCollector;
- Expect.equals(0, collector.errors.length);
- Expect.equals(1, collector.warnings.length);
- Expect.equals("$prefix.\n"
- "Did you mean to add the 'async' marker to $where?",
- '${collector.warnings.first.message}');
- }));
+ DiagnosticCollector collector = compiler.diagnosticCollector;
+ Expect.equals(0, collector.errors.length);
+ Expect.equals(1, collector.warnings.length);
+ Expect.equals(
+ "$prefix.\n"
+ "Did you mean to add the 'async' marker to $where?",
+ '${collector.warnings.first.message}');
+ }));
}
+
check('main() { await -3; }', functionName: 'main');
check('main() { () => await -3; }');
check('foo() => await -3; main() => foo();', functionName: 'foo');
- check('''
+ check(
+ '''
class A {
m() => await - 3;
}
main() => new A().m();
- ''', className: 'A', functionName: 'm');
- check('''
+ ''',
+ className: 'A',
+ functionName: 'm');
+ check(
+ '''
class A {
static m() => await - 3;
}
main() => A.m();
- ''', functionName: 'm');
- check('''
+ ''',
+ functionName: 'm');
+ check(
+ '''
class A {
m() => () => await - 3;
}
main() => new A().m();
- ''', className: 'A');
+ ''',
+ className: 'A');
}
diff --git a/tests/compiler/dart2js/scanner_offset_length_test.dart b/tests/compiler/dart2js/scanner_offset_length_test.dart
index 3eb5bb5..5239f1c 100644
--- a/tests/compiler/dart2js/scanner_offset_length_test.dart
+++ b/tests/compiler/dart2js/scanner_offset_length_test.dart
@@ -21,14 +21,16 @@
Expect.isTrue(start < text.length,
'start=$start < text.length=${text.length}: $text');
- Expect.isTrue(end <= text.length,
- 'end=$end <= text.length=${text.length}: $text');
+ Expect.isTrue(
+ end <= text.length, 'end=$end <= text.length=${text.length}: $text');
Expect.isTrue(start <= end, 'start=$end <= end=$end: $text');
var substring = text.substring(start, end);
- Expect.stringEquals(token.value, substring,
+ Expect.stringEquals(
+ token.value,
+ substring,
'token.value=${token.value} == '
'text.substring(start,end)=${substring}: $text');
@@ -39,12 +41,12 @@
}
main() {
- check('foo'); // identifier
- check('\'\''); // empty string
- check('\'foo\''); // simple string
- check('\'\$foo\''); // interpolation, identifier
- check('\'\${foo}\''); // interpolation, expression
+ check('foo'); // identifier
+ check('\'\''); // empty string
+ check('\'foo\''); // simple string
+ check('\'\$foo\''); // interpolation, identifier
+ check('\'\${foo}\''); // interpolation, expression
- check('//'); // single line comment
- check('/**/'); // multi line comment
+ check('//'); // single line comment
+ check('/**/'); // multi line comment
}
diff --git a/tests/compiler/dart2js/scanner_test.dart b/tests/compiler/dart2js/scanner_test.dart
index 453ba42..ae5dfd3 100644
--- a/tests/compiler/dart2js/scanner_test.dart
+++ b/tests/compiler/dart2js/scanner_test.dart
@@ -20,11 +20,11 @@
int l = bytes.length;
List<int> stringLiteral = new Uint8List(l + 3);
stringLiteral[0] = 0x27; // single quote
- stringLiteral[l+1] = 0x27; // single quote
+ stringLiteral[l + 1] = 0x27; // single quote
// The bytes given to the scanner must be 0-terminated.
- stringLiteral[l+2] = $EOF;
+ stringLiteral[l + 2] = $EOF;
for (int i = 0; i < l; i++) {
- stringLiteral[i+1] = bytes[i];
+ stringLiteral[i + 1] = bytes[i];
}
return new Utf8BytesScanner.fromBytes(stringLiteral).tokenize();
}
@@ -33,30 +33,144 @@
main() {
// Google favorite: "Îñţérñåţîöñåļîžåţîờñ".
- Token token = scanUTF8([0xc3, 0x8e, 0xc3, 0xb1, 0xc5, 0xa3, 0xc3, 0xa9, 0x72,
- 0xc3, 0xb1, 0xc3, 0xa5, 0xc5, 0xa3, 0xc3, 0xae, 0xc3,
- 0xb6, 0xc3, 0xb1, 0xc3, 0xa5, 0xc4, 0xbc, 0xc3, 0xae,
- 0xc5, 0xbe, 0xc3, 0xa5, 0xc5, 0xa3, 0xc3, 0xae, 0xe1,
- 0xbb, 0x9d, 0xc3, 0xb1]);
+ Token token = scanUTF8([
+ 0xc3,
+ 0x8e,
+ 0xc3,
+ 0xb1,
+ 0xc5,
+ 0xa3,
+ 0xc3,
+ 0xa9,
+ 0x72,
+ 0xc3,
+ 0xb1,
+ 0xc3,
+ 0xa5,
+ 0xc5,
+ 0xa3,
+ 0xc3,
+ 0xae,
+ 0xc3,
+ 0xb6,
+ 0xc3,
+ 0xb1,
+ 0xc3,
+ 0xa5,
+ 0xc4,
+ 0xbc,
+ 0xc3,
+ 0xae,
+ 0xc5,
+ 0xbe,
+ 0xc3,
+ 0xa5,
+ 0xc5,
+ 0xa3,
+ 0xc3,
+ 0xae,
+ 0xe1,
+ 0xbb,
+ 0x9d,
+ 0xc3,
+ 0xb1
+ ]);
Expect.stringEquals("'Îñţérñåţîöñåļîžåţîờñ'", token.value);
// Blueberry porridge in Danish: "blåbærgrød".
- token = scanUTF8([0x62, 0x6c, 0xc3, 0xa5, 0x62, 0xc3, 0xa6, 0x72, 0x67, 0x72,
- 0xc3, 0xb8, 0x64]);
+ token = scanUTF8([
+ 0x62,
+ 0x6c,
+ 0xc3,
+ 0xa5,
+ 0x62,
+ 0xc3,
+ 0xa6,
+ 0x72,
+ 0x67,
+ 0x72,
+ 0xc3,
+ 0xb8,
+ 0x64
+ ]);
Expect.stringEquals("'blåbærgrød'", token.value);
// "சிவா அணாமாைல", that is "Siva Annamalai" in Tamil.
- token = scanUTF8([0xe0, 0xae, 0x9a, 0xe0, 0xae, 0xbf, 0xe0, 0xae, 0xb5, 0xe0,
- 0xae, 0xbe, 0x20, 0xe0, 0xae, 0x85, 0xe0, 0xae, 0xa3, 0xe0,
- 0xae, 0xbe, 0xe0, 0xae, 0xae, 0xe0, 0xae, 0xbe, 0xe0, 0xaf,
- 0x88, 0xe0, 0xae, 0xb2]);
+ token = scanUTF8([
+ 0xe0,
+ 0xae,
+ 0x9a,
+ 0xe0,
+ 0xae,
+ 0xbf,
+ 0xe0,
+ 0xae,
+ 0xb5,
+ 0xe0,
+ 0xae,
+ 0xbe,
+ 0x20,
+ 0xe0,
+ 0xae,
+ 0x85,
+ 0xe0,
+ 0xae,
+ 0xa3,
+ 0xe0,
+ 0xae,
+ 0xbe,
+ 0xe0,
+ 0xae,
+ 0xae,
+ 0xe0,
+ 0xae,
+ 0xbe,
+ 0xe0,
+ 0xaf,
+ 0x88,
+ 0xe0,
+ 0xae,
+ 0xb2
+ ]);
Expect.stringEquals("'சிவா அணாமாைல'", token.value);
// "िसवा अणामालै", that is "Siva Annamalai" in Devanagari.
- token = scanUTF8([0xe0, 0xa4, 0xbf, 0xe0, 0xa4, 0xb8, 0xe0, 0xa4, 0xb5, 0xe0,
- 0xa4, 0xbe, 0x20, 0xe0, 0xa4, 0x85, 0xe0, 0xa4, 0xa3, 0xe0,
- 0xa4, 0xbe, 0xe0, 0xa4, 0xae, 0xe0, 0xa4, 0xbe, 0xe0, 0xa4,
- 0xb2, 0xe0, 0xa5, 0x88]);
+ token = scanUTF8([
+ 0xe0,
+ 0xa4,
+ 0xbf,
+ 0xe0,
+ 0xa4,
+ 0xb8,
+ 0xe0,
+ 0xa4,
+ 0xb5,
+ 0xe0,
+ 0xa4,
+ 0xbe,
+ 0x20,
+ 0xe0,
+ 0xa4,
+ 0x85,
+ 0xe0,
+ 0xa4,
+ 0xa3,
+ 0xe0,
+ 0xa4,
+ 0xbe,
+ 0xe0,
+ 0xa4,
+ 0xae,
+ 0xe0,
+ 0xa4,
+ 0xbe,
+ 0xe0,
+ 0xa4,
+ 0xb2,
+ 0xe0,
+ 0xa5,
+ 0x88
+ ]);
Expect.stringEquals("'िसवा अणामालै'", token.value);
if (!isRunningOnJavaScript()) {
@@ -75,7 +189,23 @@
// Regression test for issue 1761.
// "#! Hello, World!"
- token = scan([0x23, 0x21, 0x20, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x2c, 0x20,
- 0x57, 0x6f, 0x72, 0x6c, 0x64, 0x21]);
+ token = scan([
+ 0x23,
+ 0x21,
+ 0x20,
+ 0x48,
+ 0x65,
+ 0x6c,
+ 0x6c,
+ 0x6f,
+ 0x2c,
+ 0x20,
+ 0x57,
+ 0x6f,
+ 0x72,
+ 0x6c,
+ 0x64,
+ 0x21
+ ]);
Expect.equals(token.info, EOF_INFO); // Treated as a comment.
}
diff --git a/tests/compiler/dart2js/semantic_visitor_test.dart b/tests/compiler/dart2js/semantic_visitor_test.dart
index f8eca14..615852b 100644
--- a/tests/compiler/dart2js/semantic_visitor_test.dart
+++ b/tests/compiler/dart2js/semantic_visitor_test.dart
@@ -19,10 +19,8 @@
import 'package:compiler/src/resolution/semantic_visitor.dart';
import 'package:compiler/src/resolution/tree_elements.dart';
import 'package:compiler/src/tree/tree.dart';
-import 'package:compiler/src/universe/call_structure.dart' show
- CallStructure;
-import 'package:compiler/src/universe/selector.dart' show
- Selector;
+import 'package:compiler/src/universe/call_structure.dart' show CallStructure;
+import 'package:compiler/src/universe/selector.dart' show Selector;
import 'memory_compiler.dart';
part 'semantic_visitor_test_send_data.dart';
@@ -55,27 +53,27 @@
final error;
const Visit(this.method,
- {this.element,
- this.rhs,
- this.arguments,
- this.receiver,
- this.name,
- this.expression,
- this.left,
- this.right,
- this.type,
- this.operator,
- this.index,
- this.getter,
- this.setter,
- this.constant,
- this.selector,
- this.parameters,
- this.body,
- this.target,
- this.targetType,
- this.initializers,
- this.error});
+ {this.element,
+ this.rhs,
+ this.arguments,
+ this.receiver,
+ this.name,
+ this.expression,
+ this.left,
+ this.right,
+ this.type,
+ this.operator,
+ this.index,
+ this.getter,
+ this.setter,
+ this.constant,
+ this.selector,
+ this.parameters,
+ this.body,
+ this.target,
+ this.targetType,
+ this.initializers,
+ this.error});
int get hashCode => toString().hashCode;
@@ -160,13 +158,18 @@
final String method;
const Test(this.code, this.expectedVisits)
- : cls = null, method = 'm', codeByPrefix = null, isDeferred = false;
+ : cls = null,
+ method = 'm',
+ codeByPrefix = null,
+ isDeferred = false;
const Test.clazz(this.code, this.expectedVisits,
- {this.cls: 'C', this.method: 'm'})
- : codeByPrefix = null, isDeferred = false;
+ {this.cls: 'C', this.method: 'm'})
+ : codeByPrefix = null,
+ isDeferred = false;
const Test.prefix(this.codeByPrefix, this.code, this.expectedVisits,
- {this.isDeferred: false})
- : cls = null, method = 'm';
+ {this.isDeferred: false})
+ : cls = null,
+ method = 'm';
String toString() {
StringBuffer sb = new StringBuffer();
@@ -212,56 +215,53 @@
main(List<String> arguments) {
Set<VisitKind> kinds = new Set<VisitKind>.from(VisitKind.values);
asyncTest(() => Future.forEach([
- () {
- return test(
- kinds,
- arguments,
- SEND_TESTS,
- (elements) => new SemanticSendTestVisitor(elements));
- },
- () {
- return test(
- kinds,
- arguments,
- DECL_TESTS,
- (elements) => new SemanticDeclarationTestVisitor(elements));
- },
- () {
- Set<VisitKind> unvisitedKindSet =
- kinds.toSet()..removeAll(UNTESTABLE_KINDS);
- List<VisitKind> unvisitedKindList = unvisitedKindSet.toList();
- unvisitedKindList..sort((a, b) => a.index.compareTo(b.index));
+ () {
+ return test(kinds, arguments, SEND_TESTS,
+ (elements) => new SemanticSendTestVisitor(elements));
+ },
+ () {
+ return test(kinds, arguments, DECL_TESTS,
+ (elements) => new SemanticDeclarationTestVisitor(elements));
+ },
+ () {
+ Set<VisitKind> unvisitedKindSet = kinds.toSet()
+ ..removeAll(UNTESTABLE_KINDS);
+ List<VisitKind> unvisitedKindList = unvisitedKindSet.toList();
+ unvisitedKindList..sort((a, b) => a.index.compareTo(b.index));
- Expect.isTrue(unvisitedKindList.isEmpty,
- "Untested visit kinds:\n ${unvisitedKindList.join(',\n ')},\n");
+ Expect.isTrue(unvisitedKindList.isEmpty,
+ "Untested visit kinds:\n ${unvisitedKindList.join(',\n ')},\n");
- Set<VisitKind> testedUntestableKinds =
- UNTESTABLE_KINDS.toSet()..removeAll(kinds);
- Expect.isTrue(testedUntestableKinds.isEmpty,
- "Tested untestable visit kinds (remove from UNTESTABLE_KINDS):\n "
- "${testedUntestableKinds.join(',\n ')},\n");
- },
- () {
- ClassMirror mirror1 = reflectType(SemanticSendTestVisitor);
- Set<Symbol> symbols1 = mirror1.declarations.keys.toSet();
- ClassMirror mirror2 = reflectType(SemanticSendVisitor);
- Set<Symbol> symbols2 =
- mirror2.declarations.values
- .where((m) => m is MethodMirror &&
- !m.isConstructor &&
- m.simpleName != #apply)
- .map((m) => m.simpleName).toSet();
- symbols2.removeAll(symbols1);
- Expect.isTrue(symbols2.isEmpty,
- "Untested visit methods:\n ${symbols2.join(',\n ')},\n");
- }
- ], (f) => f()));
+ Set<VisitKind> testedUntestableKinds = UNTESTABLE_KINDS.toSet()
+ ..removeAll(kinds);
+ Expect.isTrue(
+ testedUntestableKinds.isEmpty,
+ "Tested untestable visit kinds (remove from UNTESTABLE_KINDS):\n "
+ "${testedUntestableKinds.join(',\n ')},\n");
+ },
+ () {
+ ClassMirror mirror1 = reflectType(SemanticSendTestVisitor);
+ Set<Symbol> symbols1 = mirror1.declarations.keys.toSet();
+ ClassMirror mirror2 = reflectType(SemanticSendVisitor);
+ Set<Symbol> symbols2 = mirror2.declarations.values
+ .where((m) =>
+ m is MethodMirror &&
+ !m.isConstructor &&
+ m.simpleName != #apply)
+ .map((m) => m.simpleName)
+ .toSet();
+ symbols2.removeAll(symbols1);
+ Expect.isTrue(symbols2.isEmpty,
+ "Untested visit methods:\n ${symbols2.join(',\n ')},\n");
+ }
+ ], (f) => f()));
}
-Future test(Set<VisitKind> unvisitedKinds,
- List<String> arguments,
- Map<String, List<Test>> TESTS,
- SemanticTestVisitor createVisitor(TreeElements elements)) async {
+Future test(
+ Set<VisitKind> unvisitedKinds,
+ List<String> arguments,
+ Map<String, List<Test>> TESTS,
+ SemanticTestVisitor createVisitor(TreeElements elements)) async {
Map<String, String> sourceFiles = {};
Map<String, Test> testMap = {};
StringBuffer mainSource = new StringBuffer();
@@ -297,8 +297,8 @@
options: [Flags.analyzeAll, Flags.analyzeOnly]);
Compiler compiler = result.compiler;
testMap.forEach((String filename, Test test) {
- LibraryElement library = compiler.libraryLoader.lookupLibrary(
- Uri.parse('memory:$filename'));
+ LibraryElement library =
+ compiler.libraryLoader.lookupLibrary(Uri.parse('memory:$filename'));
Element element;
String cls = test.cls;
String method = test.method;
@@ -306,27 +306,32 @@
element = library.find(method);
} else {
ClassElement classElement = library.find(cls);
- Expect.isNotNull(classElement,
- "Class '$cls' not found in:\n"
- "${library.compilationUnit.script.text}");
+ Expect.isNotNull(
+ classElement,
+ "Class '$cls' not found in:\n"
+ "${library.compilationUnit.script.text}");
element = classElement.localLookup(method);
}
var expectedVisits = test.expectedVisits;
if (expectedVisits == null) {
- Expect.isTrue(element.isMalformed,
+ Expect.isTrue(
+ element.isMalformed,
"Element '$method' expected to be have parse errors in:\n"
"${library.compilationUnit.script.text}");
return;
} else if (expectedVisits is! List) {
expectedVisits = [expectedVisits];
}
- Expect.isFalse(element.isMalformed,
+ Expect.isFalse(
+ element.isMalformed,
"Element '$method' is not expected to be have parse errors in:\n"
"${library.compilationUnit.script.text}");
void testAstElement(AstElement astElement) {
- Expect.isNotNull(astElement, "Element '$method' not found in:\n"
- "${library.compilationUnit.script.text}");
+ Expect.isNotNull(
+ astElement,
+ "Element '$method' not found in:\n"
+ "${library.compilationUnit.script.text}");
ResolvedAst resolvedAst = astElement.resolvedAst;
SemanticTestVisitor visitor = createVisitor(resolvedAst.elements);
try {
@@ -336,15 +341,18 @@
});
} catch (e, s) {
Expect.fail("$e:\n$s\nIn test:\n"
- "${library.compilationUnit.script.text}");
+ "${library.compilationUnit.script.text}");
}
- Expect.listEquals(expectedVisits, visitor.visits,
+ Expect.listEquals(
+ expectedVisits,
+ visitor.visits,
"In test:\n"
"${library.compilationUnit.script.text}\n\n"
"Expected: $expectedVisits\n"
"Found: ${visitor.visits}");
unvisitedKinds.removeAll(visitor.visits.map((visit) => visit.method));
}
+
if (element.isAbstractField) {
AbstractFieldElement abstractFieldElement = element;
if (abstractFieldElement.getter != null) {
@@ -383,7 +391,6 @@
VISIT_FINAL_PARAMETER_SET_IF_NULL,
VISIT_FINAL_PARAMETER_PREFIX,
VISIT_FINAL_PARAMETER_POSTFIX,
-
VISIT_LOCAL_VARIABLE_GET,
VISIT_LOCAL_VARIABLE_SET,
VISIT_LOCAL_VARIABLE_INVOKE,
@@ -398,7 +405,6 @@
VISIT_FINAL_LOCAL_VARIABLE_SET_IF_NULL,
VISIT_FINAL_LOCAL_VARIABLE_PREFIX,
VISIT_FINAL_LOCAL_VARIABLE_POSTFIX,
-
VISIT_LOCAL_FUNCTION_GET,
VISIT_LOCAL_FUNCTION_INVOKE,
VISIT_LOCAL_FUNCTION_INCOMPATIBLE_INVOKE,
@@ -409,7 +415,6 @@
VISIT_LOCAL_FUNCTION_SET_IF_NULL,
VISIT_LOCAL_FUNCTION_PREFIX,
VISIT_LOCAL_FUNCTION_POSTFIX,
-
VISIT_STATIC_FIELD_GET,
VISIT_STATIC_FIELD_SET,
VISIT_STATIC_FIELD_INVOKE,
@@ -419,31 +424,25 @@
VISIT_STATIC_FIELD_POSTFIX,
VISIT_STATIC_FIELD_DECL,
VISIT_STATIC_CONSTANT_DECL,
-
VISIT_STATIC_GETTER_GET,
VISIT_STATIC_GETTER_SET,
VISIT_STATIC_GETTER_INVOKE,
-
VISIT_STATIC_SETTER_GET,
VISIT_STATIC_SETTER_SET,
VISIT_STATIC_SETTER_INVOKE,
-
VISIT_STATIC_GETTER_SETTER_COMPOUND,
VISIT_STATIC_GETTER_SETTER_SET_IF_NULL,
VISIT_STATIC_METHOD_SETTER_COMPOUND,
VISIT_STATIC_METHOD_SETTER_SET_IF_NULL,
VISIT_STATIC_GETTER_SETTER_PREFIX,
VISIT_STATIC_GETTER_SETTER_POSTFIX,
-
VISIT_STATIC_GETTER_DECL,
VISIT_STATIC_SETTER_DECL,
-
VISIT_FINAL_STATIC_FIELD_SET,
VISIT_STATIC_FINAL_FIELD_COMPOUND,
VISIT_STATIC_FINAL_FIELD_SET_IF_NULL,
VISIT_STATIC_FINAL_FIELD_POSTFIX,
VISIT_STATIC_FINAL_FIELD_PREFIX,
-
VISIT_STATIC_FUNCTION_GET,
VISIT_STATIC_FUNCTION_SET,
VISIT_STATIC_FUNCTION_INVOKE,
@@ -451,7 +450,6 @@
VISIT_STATIC_FUNCTION_DECL,
VISIT_STATIC_METHOD_SETTER_PREFIX,
VISIT_STATIC_METHOD_SETTER_POSTFIX,
-
VISIT_UNRESOLVED_STATIC_GETTER_COMPOUND,
VISIT_UNRESOLVED_STATIC_GETTER_SET_IF_NULL,
VISIT_UNRESOLVED_STATIC_SETTER_COMPOUND,
@@ -464,7 +462,6 @@
VISIT_UNRESOLVED_STATIC_GETTER_POSTFIX,
VISIT_UNRESOLVED_STATIC_SETTER_POSTFIX,
VISIT_STATIC_METHOD_POSTFIX,
-
VISIT_TOP_LEVEL_FIELD_GET,
VISIT_TOP_LEVEL_FIELD_SET,
VISIT_TOP_LEVEL_FIELD_INVOKE,
@@ -479,7 +476,6 @@
VISIT_TOP_LEVEL_FINAL_FIELD_SET_IF_NULL,
VISIT_TOP_LEVEL_FINAL_FIELD_POSTFIX,
VISIT_TOP_LEVEL_FINAL_FIELD_PREFIX,
-
VISIT_TOP_LEVEL_GETTER_GET,
VISIT_TOP_LEVEL_GETTER_SET,
VISIT_TOP_LEVEL_GETTER_INVOKE,
@@ -492,7 +488,6 @@
VISIT_TOP_LEVEL_GETTER_SETTER_POSTFIX,
VISIT_TOP_LEVEL_GETTER_DECL,
VISIT_TOP_LEVEL_SETTER_DECL,
-
VISIT_TOP_LEVEL_FUNCTION_GET,
VISIT_TOP_LEVEL_FUNCTION_SET,
VISIT_TOP_LEVEL_FUNCTION_INVOKE,
@@ -502,7 +497,6 @@
VISIT_TOP_LEVEL_METHOD_SETTER_SET_IF_NULL,
VISIT_TOP_LEVEL_METHOD_SETTER_PREFIX,
VISIT_TOP_LEVEL_METHOD_SETTER_POSTFIX,
-
VISIT_UNRESOLVED_TOP_LEVEL_GETTER_COMPOUND,
VISIT_UNRESOLVED_TOP_LEVEL_GETTER_SET_IF_NULL,
VISIT_UNRESOLVED_TOP_LEVEL_SETTER_COMPOUND,
@@ -515,7 +509,6 @@
VISIT_UNRESOLVED_TOP_LEVEL_GETTER_POSTFIX,
VISIT_UNRESOLVED_TOP_LEVEL_SETTER_POSTFIX,
VISIT_TOP_LEVEL_METHOD_POSTFIX,
-
VISIT_DYNAMIC_PROPERTY_GET,
VISIT_DYNAMIC_PROPERTY_SET,
VISIT_DYNAMIC_PROPERTY_INVOKE,
@@ -523,10 +516,8 @@
VISIT_DYNAMIC_PROPERTY_SET_IF_NULL,
VISIT_DYNAMIC_PROPERTY_PREFIX,
VISIT_DYNAMIC_PROPERTY_POSTFIX,
-
VISIT_THIS_GET,
VISIT_THIS_INVOKE,
-
VISIT_THIS_PROPERTY_GET,
VISIT_THIS_PROPERTY_SET,
VISIT_THIS_PROPERTY_INVOKE,
@@ -534,7 +525,6 @@
VISIT_THIS_PROPERTY_SET_IF_NULL,
VISIT_THIS_PROPERTY_PREFIX,
VISIT_THIS_PROPERTY_POSTFIX,
-
VISIT_SUPER_FIELD_GET,
VISIT_SUPER_FIELD_SET,
VISIT_FINAL_SUPER_FIELD_SET,
@@ -551,7 +541,6 @@
VISIT_SUPER_FIELD_FIELD_SET_IF_NULL,
VISIT_SUPER_FIELD_FIELD_PREFIX,
VISIT_SUPER_FIELD_FIELD_POSTFIX,
-
VISIT_SUPER_GETTER_GET,
VISIT_SUPER_GETTER_SET,
VISIT_SUPER_GETTER_INVOKE,
@@ -570,7 +559,6 @@
VISIT_SUPER_GETTER_SETTER_POSTFIX,
VISIT_SUPER_GETTER_FIELD_POSTFIX,
VISIT_SUPER_FIELD_SETTER_POSTFIX,
-
VISIT_SUPER_METHOD_GET,
VISIT_SUPER_METHOD_SET,
VISIT_SUPER_METHOD_INVOKE,
@@ -583,21 +571,18 @@
VISIT_SUPER_METHOD_SET_IF_NULL,
VISIT_SUPER_METHOD_PREFIX,
VISIT_SUPER_METHOD_POSTFIX,
-
VISIT_UNRESOLVED_GET,
VISIT_UNRESOLVED_SET,
VISIT_UNRESOLVED_INVOKE,
VISIT_UNRESOLVED_SUPER_GET,
VISIT_UNRESOLVED_SUPER_INVOKE,
VISIT_UNRESOLVED_SUPER_SET,
-
VISIT_BINARY,
VISIT_INDEX,
VISIT_EQUALS,
VISIT_NOT_EQUALS,
VISIT_INDEX_PREFIX,
VISIT_INDEX_POSTFIX,
-
VISIT_SUPER_BINARY,
VISIT_UNRESOLVED_SUPER_BINARY,
VISIT_SUPER_INDEX,
@@ -620,19 +605,15 @@
VISIT_UNRESOLVED_SUPER_INDEX_POSTFIX,
VISIT_UNRESOLVED_SUPER_GETTER_INDEX_POSTFIX,
VISIT_UNRESOLVED_SUPER_SETTER_INDEX_POSTFIX,
-
VISIT_UNRESOLVED_SUPER_COMPOUND,
VISIT_UNRESOLVED_SUPER_SET_IF_NULL,
VISIT_UNRESOLVED_SUPER_PREFIX,
VISIT_UNRESOLVED_SUPER_POSTFIX,
-
VISIT_UNARY,
VISIT_SUPER_UNARY,
VISIT_UNRESOLVED_SUPER_UNARY,
VISIT_NOT,
-
VISIT_EXPRESSION_INVOKE,
-
VISIT_CLASS_TYPE_LITERAL_GET,
VISIT_CLASS_TYPE_LITERAL_SET,
VISIT_CLASS_TYPE_LITERAL_INVOKE,
@@ -640,7 +621,6 @@
VISIT_CLASS_TYPE_LITERAL_SET_IF_NULL,
VISIT_CLASS_TYPE_LITERAL_PREFIX,
VISIT_CLASS_TYPE_LITERAL_POSTFIX,
-
VISIT_TYPEDEF_TYPE_LITERAL_GET,
VISIT_TYPEDEF_TYPE_LITERAL_SET,
VISIT_TYPEDEF_TYPE_LITERAL_INVOKE,
@@ -648,7 +628,6 @@
VISIT_TYPEDEF_TYPE_LITERAL_SET_IF_NULL,
VISIT_TYPEDEF_TYPE_LITERAL_PREFIX,
VISIT_TYPEDEF_TYPE_LITERAL_POSTFIX,
-
VISIT_TYPE_VARIABLE_TYPE_LITERAL_GET,
VISIT_TYPE_VARIABLE_TYPE_LITERAL_SET,
VISIT_TYPE_VARIABLE_TYPE_LITERAL_INVOKE,
@@ -656,7 +635,6 @@
VISIT_TYPE_VARIABLE_TYPE_LITERAL_SET_IF_NULL,
VISIT_TYPE_VARIABLE_TYPE_LITERAL_PREFIX,
VISIT_TYPE_VARIABLE_TYPE_LITERAL_POSTFIX,
-
VISIT_DYNAMIC_TYPE_LITERAL_GET,
VISIT_DYNAMIC_TYPE_LITERAL_SET,
VISIT_DYNAMIC_TYPE_LITERAL_INVOKE,
@@ -664,7 +642,6 @@
VISIT_DYNAMIC_TYPE_LITERAL_SET_IF_NULL,
VISIT_DYNAMIC_TYPE_LITERAL_PREFIX,
VISIT_DYNAMIC_TYPE_LITERAL_POSTFIX,
-
VISIT_INDEX_SET,
VISIT_COMPOUND_INDEX_SET,
VISIT_SUPER_INDEX_SET,
@@ -673,19 +650,16 @@
VISIT_UNRESOLVED_SUPER_COMPOUND_INDEX_SET,
VISIT_UNRESOLVED_SUPER_GETTER_COMPOUND_INDEX_SET,
VISIT_UNRESOLVED_SUPER_SETTER_COMPOUND_INDEX_SET,
-
VISIT_INDEX_SET_IF_NULL,
VISIT_SUPER_INDEX_SET_IF_NULL,
VISIT_UNRESOLVED_SUPER_INDEX_SET_IF_NULL,
VISIT_UNRESOLVED_SUPER_GETTER_INDEX_SET_IF_NULL,
VISIT_UNRESOLVED_SUPER_SETTER_INDEX_SET_IF_NULL,
-
VISIT_LOGICAL_AND,
VISIT_LOGICAL_OR,
VISIT_IS,
VISIT_IS_NOT,
VISIT_AS,
-
VISIT_CONST_CONSTRUCTOR_INVOKE,
VISIT_BOOL_FROM_ENVIRONMENT_CONSTRUCTOR_INVOKE,
VISIT_INT_FROM_ENVIRONMENT_CONSTRUCTOR_INVOKE,
@@ -696,17 +670,14 @@
VISIT_REDIRECTING_FACTORY_CONSTRUCTOR_INVOKE,
VISIT_CONSTRUCTOR_INCOMPATIBLE_INVOKE,
ERROR_NON_CONSTANT_CONSTRUCTOR_INVOKE,
-
VISIT_SUPER_CONSTRUCTOR_INVOKE,
VISIT_IMPLICIT_SUPER_CONSTRUCTOR_INVOKE,
VISIT_THIS_CONSTRUCTOR_INVOKE,
VISIT_FIELD_INITIALIZER,
-
VISIT_UNRESOLVED_CLASS_CONSTRUCTOR_INVOKE,
VISIT_UNRESOLVED_CONSTRUCTOR_INVOKE,
VISIT_ABSTRACT_CLASS_CONSTRUCTOR_INVOKE,
VISIT_UNRESOLVED_REDIRECTING_FACTORY_CONSTRUCTOR_INVOKE,
-
VISIT_INSTANCE_GETTER_DECL,
VISIT_INSTANCE_SETTER_DECL,
VISIT_INSTANCE_METHOD_DECL,
@@ -714,24 +685,20 @@
VISIT_ABSTRACT_SETTER_DECL,
VISIT_ABSTRACT_METHOD_DECL,
VISIT_INSTANCE_FIELD_DECL,
-
VISIT_GENERATIVE_CONSTRUCTOR_DECL,
VISIT_REDIRECTING_GENERATIVE_CONSTRUCTOR_DECL,
VISIT_FACTORY_CONSTRUCTOR_DECL,
VISIT_REDIRECTING_FACTORY_CONSTRUCTOR_DECL,
-
VISIT_REQUIRED_PARAMETER_DECL,
VISIT_OPTIONAL_PARAMETER_DECL,
VISIT_NAMED_PARAMETER_DECL,
VISIT_REQUIRED_INITIALIZING_FORMAL_DECL,
VISIT_OPTIONAL_INITIALIZING_FORMAL_DECL,
VISIT_NAMED_INITIALIZING_FORMAL_DECL,
-
VISIT_UNRESOLVED_COMPOUND,
VISIT_UNRESOLVED_SET_IF_NULL,
VISIT_UNRESOLVED_PREFIX,
VISIT_UNRESOLVED_POSTFIX,
-
VISIT_IF_NULL,
VISIT_IF_NOT_NULL_DYNAMIC_PROPERTY_GET,
VISIT_IF_NOT_NULL_DYNAMIC_PROPERTY_SET,
@@ -740,7 +707,6 @@
VISIT_IF_NOT_NULL_DYNAMIC_PROPERTY_SET_IF_NULL,
VISIT_IF_NOT_NULL_DYNAMIC_PROPERTY_PREFIX,
VISIT_IF_NOT_NULL_DYNAMIC_PROPERTY_POSTFIX,
-
ERROR_UNDEFINED_UNARY_EXPRESSION,
ERROR_UNDEFINED_BINARY_EXPRESSION,
ERROR_INVALID_GET,
@@ -759,9 +725,7 @@
ERROR_INVALID_COMPOUND_INDEX_SET,
ERROR_INVALID_INDEX_PREFIX,
ERROR_INVALID_INDEX_POSTFIX,
-
VISIT_CONSTANT_GET,
VISIT_CONSTANT_INVOKE,
-
PREVISIT_DEFERRED_ACCESS,
}
diff --git a/tests/compiler/dart2js/semantic_visitor_test_decl_data.dart b/tests/compiler/dart2js/semantic_visitor_test_decl_data.dart
index 3004a61..f532948 100644
--- a/tests/compiler/dart2js/semantic_visitor_test_decl_data.dart
+++ b/tests/compiler/dart2js/semantic_visitor_test_decl_data.dart
@@ -12,15 +12,11 @@
''',
const [
const Visit(VisitKind.VISIT_TOP_LEVEL_FUNCTION_DECL,
- element: 'function(m)',
- parameters: '(a,b)',
- body: '{}'),
+ element: 'function(m)', parameters: '(a,b)', body: '{}'),
const Visit(VisitKind.VISIT_REQUIRED_PARAMETER_DECL,
- element: 'parameter(m#a)',
- index: 0),
+ element: 'parameter(m#a)', index: 0),
const Visit(VisitKind.VISIT_REQUIRED_PARAMETER_DECL,
- element: 'parameter(m#b)',
- index: 1),
+ element: 'parameter(m#b)', index: 1),
]),
const Test(
'''
@@ -28,16 +24,11 @@
''',
const [
const Visit(VisitKind.VISIT_TOP_LEVEL_FUNCTION_DECL,
- element: 'function(m)',
- parameters: '(a,[b])',
- body: '{}'),
+ element: 'function(m)', parameters: '(a,[b])', body: '{}'),
const Visit(VisitKind.VISIT_REQUIRED_PARAMETER_DECL,
- element: 'parameter(m#a)',
- index: 0),
+ element: 'parameter(m#a)', index: 0),
const Visit(VisitKind.VISIT_OPTIONAL_PARAMETER_DECL,
- element: 'parameter(m#b)',
- index: 1,
- constant: 'null'),
+ element: 'parameter(m#b)', index: 1, constant: 'null'),
]),
const Test(
'''
@@ -45,16 +36,11 @@
''',
const [
const Visit(VisitKind.VISIT_TOP_LEVEL_FUNCTION_DECL,
- element: 'function(m)',
- parameters: '(a,[b=null])',
- body: '{}'),
+ element: 'function(m)', parameters: '(a,[b=null])', body: '{}'),
const Visit(VisitKind.VISIT_REQUIRED_PARAMETER_DECL,
- element: 'parameter(m#a)',
- index: 0),
+ element: 'parameter(m#a)', index: 0),
const Visit(VisitKind.VISIT_OPTIONAL_PARAMETER_DECL,
- element: 'parameter(m#b)',
- constant: 'null',
- index: 1),
+ element: 'parameter(m#b)', constant: 'null', index: 1),
]),
const Test(
'''
@@ -62,16 +48,11 @@
''',
const [
const Visit(VisitKind.VISIT_TOP_LEVEL_FUNCTION_DECL,
- element: 'function(m)',
- parameters: '(a,[b=42])',
- body: '{}'),
+ element: 'function(m)', parameters: '(a,[b=42])', body: '{}'),
const Visit(VisitKind.VISIT_REQUIRED_PARAMETER_DECL,
- element: 'parameter(m#a)',
- index: 0),
+ element: 'parameter(m#a)', index: 0),
const Visit(VisitKind.VISIT_OPTIONAL_PARAMETER_DECL,
- element: 'parameter(m#b)',
- constant: 42,
- index: 1),
+ element: 'parameter(m#b)', constant: 42, index: 1),
]),
const Test(
'''
@@ -79,15 +60,11 @@
''',
const [
const Visit(VisitKind.VISIT_TOP_LEVEL_FUNCTION_DECL,
- element: 'function(m)',
- parameters: '(a,{b})',
- body: '{}'),
+ element: 'function(m)', parameters: '(a,{b})', body: '{}'),
const Visit(VisitKind.VISIT_REQUIRED_PARAMETER_DECL,
- element: 'parameter(m#a)',
- index: 0),
+ element: 'parameter(m#a)', index: 0),
const Visit(VisitKind.VISIT_NAMED_PARAMETER_DECL,
- element: 'parameter(m#b)',
- constant: 'null'),
+ element: 'parameter(m#b)', constant: 'null'),
]),
const Test(
'''
@@ -95,15 +72,11 @@
''',
const [
const Visit(VisitKind.VISIT_TOP_LEVEL_FUNCTION_DECL,
- element: 'function(m)',
- parameters: '(a,{b: null})',
- body: '{}'),
+ element: 'function(m)', parameters: '(a,{b: null})', body: '{}'),
const Visit(VisitKind.VISIT_REQUIRED_PARAMETER_DECL,
- element: 'parameter(m#a)',
- index: 0),
+ element: 'parameter(m#a)', index: 0),
const Visit(VisitKind.VISIT_NAMED_PARAMETER_DECL,
- element: 'parameter(m#b)',
- constant: 'null'),
+ element: 'parameter(m#b)', constant: 'null'),
]),
const Test(
'''
@@ -111,15 +84,11 @@
''',
const [
const Visit(VisitKind.VISIT_TOP_LEVEL_FUNCTION_DECL,
- element: 'function(m)',
- parameters: '(a,{b: 42})',
- body: '{}'),
+ element: 'function(m)', parameters: '(a,{b: 42})', body: '{}'),
const Visit(VisitKind.VISIT_REQUIRED_PARAMETER_DECL,
- element: 'parameter(m#a)',
- index: 0),
+ element: 'parameter(m#a)', index: 0),
const Visit(VisitKind.VISIT_NAMED_PARAMETER_DECL,
- element: 'parameter(m#b)',
- constant: 42),
+ element: 'parameter(m#b)', constant: 42),
]),
const Test(
'''
@@ -127,8 +96,7 @@
''',
const [
const Visit(VisitKind.VISIT_TOP_LEVEL_GETTER_DECL,
- element: 'getter(m)',
- body: '=>null;'),
+ element: 'getter(m)', body: '=>null;'),
]),
const Test(
'''
@@ -136,12 +104,9 @@
''',
const [
const Visit(VisitKind.VISIT_TOP_LEVEL_SETTER_DECL,
- element: 'setter(m)',
- parameters: '(a)',
- body: '{}'),
+ element: 'setter(m)', parameters: '(a)', body: '{}'),
const Visit(VisitKind.VISIT_REQUIRED_PARAMETER_DECL,
- element: 'parameter(m#a)',
- index: 0),
+ element: 'parameter(m#a)', index: 0),
]),
const Test.clazz(
'''
@@ -151,15 +116,11 @@
''',
const [
const Visit(VisitKind.VISIT_STATIC_FUNCTION_DECL,
- element: 'function(C#m)',
- parameters: '(a,b)',
- body: '{}'),
+ element: 'function(C#m)', parameters: '(a,b)', body: '{}'),
const Visit(VisitKind.VISIT_REQUIRED_PARAMETER_DECL,
- element: 'parameter(m#a)',
- index: 0),
+ element: 'parameter(m#a)', index: 0),
const Visit(VisitKind.VISIT_REQUIRED_PARAMETER_DECL,
- element: 'parameter(m#b)',
- index: 1),
+ element: 'parameter(m#b)', index: 1),
]),
const Test.clazz(
'''
@@ -169,8 +130,7 @@
''',
const [
const Visit(VisitKind.VISIT_STATIC_GETTER_DECL,
- element: 'getter(C#m)',
- body: '=>null;'),
+ element: 'getter(C#m)', body: '=>null;'),
]),
const Test.clazz(
'''
@@ -180,12 +140,9 @@
''',
const [
const Visit(VisitKind.VISIT_STATIC_SETTER_DECL,
- element: 'setter(C#m)',
- parameters: '(a)',
- body: '{}'),
+ element: 'setter(C#m)', parameters: '(a)', body: '{}'),
const Visit(VisitKind.VISIT_REQUIRED_PARAMETER_DECL,
- element: 'parameter(m#a)',
- index: 0),
+ element: 'parameter(m#a)', index: 0),
]),
const Test.clazz(
'''
@@ -195,15 +152,11 @@
''',
const [
const Visit(VisitKind.VISIT_INSTANCE_METHOD_DECL,
- element: 'function(C#m)',
- parameters: '(a,b)',
- body: '{}'),
+ element: 'function(C#m)', parameters: '(a,b)', body: '{}'),
const Visit(VisitKind.VISIT_REQUIRED_PARAMETER_DECL,
- element: 'parameter(m#a)',
- index: 0),
+ element: 'parameter(m#a)', index: 0),
const Visit(VisitKind.VISIT_REQUIRED_PARAMETER_DECL,
- element: 'parameter(m#b)',
- index: 1),
+ element: 'parameter(m#b)', index: 1),
]),
const Test.clazz(
'''
@@ -213,8 +166,7 @@
''',
const [
const Visit(VisitKind.VISIT_INSTANCE_GETTER_DECL,
- element: 'getter(C#m)',
- body: '=>null;'),
+ element: 'getter(C#m)', body: '=>null;'),
]),
const Test.clazz(
'''
@@ -224,12 +176,9 @@
''',
const [
const Visit(VisitKind.VISIT_INSTANCE_SETTER_DECL,
- element: 'setter(C#m)',
- parameters: '(a)',
- body: '{}'),
+ element: 'setter(C#m)', parameters: '(a)', body: '{}'),
const Visit(VisitKind.VISIT_REQUIRED_PARAMETER_DECL,
- element: 'parameter(m#a)',
- index: 0),
+ element: 'parameter(m#a)', index: 0),
]),
const Test.clazz(
'''
@@ -239,14 +188,11 @@
''',
const [
const Visit(VisitKind.VISIT_ABSTRACT_METHOD_DECL,
- element: 'function(C#m)',
- parameters: '(a,b)'),
+ element: 'function(C#m)', parameters: '(a,b)'),
const Visit(VisitKind.VISIT_REQUIRED_PARAMETER_DECL,
- element: 'parameter(m#a)',
- index: 0),
+ element: 'parameter(m#a)', index: 0),
const Visit(VisitKind.VISIT_REQUIRED_PARAMETER_DECL,
- element: 'parameter(m#b)',
- index: 1),
+ element: 'parameter(m#b)', index: 1),
]),
const Test.clazz(
'''
@@ -266,11 +212,9 @@
''',
const [
const Visit(VisitKind.VISIT_ABSTRACT_SETTER_DECL,
- element: 'setter(C#m)',
- parameters: '(a)'),
+ element: 'setter(C#m)', parameters: '(a)'),
const Visit(VisitKind.VISIT_REQUIRED_PARAMETER_DECL,
- element: 'parameter(m#a)',
- index: 0),
+ element: 'parameter(m#a)', index: 0),
]),
const Test(
'''
@@ -278,15 +222,11 @@
''',
const [
const Visit(VisitKind.VISIT_TOP_LEVEL_FUNCTION_DECL,
- element: 'function(m)',
- parameters: '(a,b)',
- body: '{}'),
+ element: 'function(m)', parameters: '(a,b)', body: '{}'),
const Visit(VisitKind.VISIT_REQUIRED_PARAMETER_DECL,
- element: 'parameter(m#a)',
- index: 0),
+ element: 'parameter(m#a)', index: 0),
const Visit(VisitKind.VISIT_REQUIRED_PARAMETER_DECL,
- element: 'parameter(m#b)',
- index: 1),
+ element: 'parameter(m#b)', index: 1),
]),
const Test(
'''
@@ -296,19 +236,13 @@
''',
const [
const Visit(VisitKind.VISIT_TOP_LEVEL_FUNCTION_DECL,
- element: 'function(m)',
- parameters: '()',
- body: '{local(a,b){}}'),
+ element: 'function(m)', parameters: '()', body: '{local(a,b){}}'),
const Visit(VisitKind.VISIT_LOCAL_FUNCTION_DECL,
- element: 'function(m#local)',
- parameters: '(a,b)',
- body: '{}'),
+ element: 'function(m#local)', parameters: '(a,b)', body: '{}'),
const Visit(VisitKind.VISIT_REQUIRED_PARAMETER_DECL,
- element: 'parameter(local#a)',
- index: 0),
+ element: 'parameter(local#a)', index: 0),
const Visit(VisitKind.VISIT_REQUIRED_PARAMETER_DECL,
- element: 'parameter(local#b)',
- index: 1),
+ element: 'parameter(local#b)', index: 1),
]),
const Test(
'''
@@ -316,19 +250,13 @@
''',
const [
const Visit(VisitKind.VISIT_TOP_LEVEL_FUNCTION_DECL,
- element: 'function(m)',
- parameters: '()',
- body: '=>(a,b){};'),
+ element: 'function(m)', parameters: '()', body: '=>(a,b){};'),
const Visit(VisitKind.VISIT_CLOSURE_DECL,
- element: 'function(m#)',
- parameters: '(a,b)',
- body: '{}'),
+ element: 'function(m#)', parameters: '(a,b)', body: '{}'),
const Visit(VisitKind.VISIT_REQUIRED_PARAMETER_DECL,
- element: 'parameter(#a)',
- index: 0),
+ element: 'parameter(#a)', index: 0),
const Visit(VisitKind.VISIT_REQUIRED_PARAMETER_DECL,
- element: 'parameter(#b)',
- index: 1),
+ element: 'parameter(#b)', index: 1),
]),
],
'Constructor declarations': const [
@@ -344,14 +272,11 @@
parameters: '(a,b)',
body: ';'),
const Visit(VisitKind.VISIT_REQUIRED_PARAMETER_DECL,
- element: 'parameter(#a)',
- index: 0),
+ element: 'parameter(#a)', index: 0),
const Visit(VisitKind.VISIT_REQUIRED_PARAMETER_DECL,
- element: 'parameter(#b)',
- index: 1),
+ element: 'parameter(#b)', index: 1),
const Visit(VisitKind.VISIT_IMPLICIT_SUPER_CONSTRUCTOR_INVOKE,
- element: 'generative_constructor(Object#)',
- type: 'Object'),
+ element: 'generative_constructor(Object#)', type: 'Object'),
],
method: ''),
const Test.clazz(
@@ -367,14 +292,11 @@
parameters: '(a,this.b)',
body: ';'),
const Visit(VisitKind.VISIT_REQUIRED_PARAMETER_DECL,
- element: 'parameter(#a)',
- index: 0),
+ element: 'parameter(#a)', index: 0),
const Visit(VisitKind.VISIT_REQUIRED_INITIALIZING_FORMAL_DECL,
- element: 'initializing_formal(#b)',
- index: 1),
+ element: 'initializing_formal(#b)', index: 1),
const Visit(VisitKind.VISIT_IMPLICIT_SUPER_CONSTRUCTOR_INVOKE,
- element: 'generative_constructor(Object#)',
- type: 'Object'),
+ element: 'generative_constructor(Object#)', type: 'Object'),
],
method: ''),
const Test.clazz(
@@ -390,15 +312,11 @@
parameters: '(a,[this.b=42])',
body: ';'),
const Visit(VisitKind.VISIT_REQUIRED_PARAMETER_DECL,
- element: 'parameter(#a)',
- index: 0),
+ element: 'parameter(#a)', index: 0),
const Visit(VisitKind.VISIT_OPTIONAL_INITIALIZING_FORMAL_DECL,
- element: 'initializing_formal(#b)',
- constant: 42,
- index: 1),
+ element: 'initializing_formal(#b)', constant: 42, index: 1),
const Visit(VisitKind.VISIT_IMPLICIT_SUPER_CONSTRUCTOR_INVOKE,
- element: 'generative_constructor(Object#)',
- type: 'Object'),
+ element: 'generative_constructor(Object#)', type: 'Object'),
],
method: ''),
const Test.clazz(
@@ -414,14 +332,11 @@
parameters: '(a,{this.b: 42})',
body: ';'),
const Visit(VisitKind.VISIT_REQUIRED_PARAMETER_DECL,
- element: 'parameter(#a)',
- index: 0),
+ element: 'parameter(#a)', index: 0),
const Visit(VisitKind.VISIT_NAMED_INITIALIZING_FORMAL_DECL,
- element: 'initializing_formal(#b)',
- constant: 42),
+ element: 'initializing_formal(#b)', constant: 42),
const Visit(VisitKind.VISIT_IMPLICIT_SUPER_CONSTRUCTOR_INVOKE,
- element: 'generative_constructor(Object#)',
- type: 'Object'),
+ element: 'generative_constructor(Object#)', type: 'Object'),
],
method: ''),
const Test.clazz(
@@ -436,11 +351,9 @@
parameters: '(a,b)',
body: ';'),
const Visit(VisitKind.VISIT_REQUIRED_PARAMETER_DECL,
- element: 'parameter(#a)',
- index: 0),
+ element: 'parameter(#a)', index: 0),
const Visit(VisitKind.VISIT_REQUIRED_PARAMETER_DECL,
- element: 'parameter(#b)',
- index: 1),
+ element: 'parameter(#b)', index: 1),
const Visit(VisitKind.VISIT_SUPER_CONSTRUCTOR_INVOKE,
element: 'generative_constructor(Object#)',
type: 'Object',
@@ -461,17 +374,13 @@
parameters: '(a,b)',
body: ';'),
const Visit(VisitKind.VISIT_REQUIRED_PARAMETER_DECL,
- element: 'parameter(#a)',
- index: 0),
+ element: 'parameter(#a)', index: 0),
const Visit(VisitKind.VISIT_REQUIRED_PARAMETER_DECL,
- element: 'parameter(#b)',
- index: 1),
+ element: 'parameter(#b)', index: 1),
const Visit(VisitKind.VISIT_FIELD_INITIALIZER,
- element: 'field(C#field)',
- rhs: 'a'),
+ element: 'field(C#field)', rhs: 'a'),
const Visit(VisitKind.VISIT_IMPLICIT_SUPER_CONSTRUCTOR_INVOKE,
- element: 'generative_constructor(Object#)',
- type: 'Object'),
+ element: 'generative_constructor(Object#)', type: 'Object'),
],
method: ''),
const Test.clazz(
@@ -488,20 +397,15 @@
parameters: '(a,b)',
body: ';'),
const Visit(VisitKind.VISIT_REQUIRED_PARAMETER_DECL,
- element: 'parameter(#a)',
- index: 0),
+ element: 'parameter(#a)', index: 0),
const Visit(VisitKind.VISIT_REQUIRED_PARAMETER_DECL,
- element: 'parameter(#b)',
- index: 1),
+ element: 'parameter(#b)', index: 1),
const Visit(VisitKind.VISIT_FIELD_INITIALIZER,
- element: 'field(C#field1)',
- rhs: 'a'),
+ element: 'field(C#field1)', rhs: 'a'),
const Visit(VisitKind.VISIT_FIELD_INITIALIZER,
- element: 'field(C#field2)',
- rhs: 'b'),
+ element: 'field(C#field2)', rhs: 'b'),
const Visit(VisitKind.VISIT_IMPLICIT_SUPER_CONSTRUCTOR_INVOKE,
- element: 'generative_constructor(Object#)',
- type: 'Object'),
+ element: 'generative_constructor(Object#)', type: 'Object'),
],
method: ''),
const Test.clazz(
@@ -517,11 +421,9 @@
parameters: '(a,b)',
initializers: ':this._(a,b)'),
const Visit(VisitKind.VISIT_REQUIRED_PARAMETER_DECL,
- element: 'parameter(#a)',
- index: 0),
+ element: 'parameter(#a)', index: 0),
const Visit(VisitKind.VISIT_REQUIRED_PARAMETER_DECL,
- element: 'parameter(#b)',
- index: 1),
+ element: 'parameter(#b)', index: 1),
const Visit(VisitKind.VISIT_THIS_CONSTRUCTOR_INVOKE,
element: 'generative_constructor(C#_)',
arguments: '(a,b)',
@@ -540,11 +442,9 @@
parameters: '(a,b)',
body: '=>null;'),
const Visit(VisitKind.VISIT_REQUIRED_PARAMETER_DECL,
- element: 'parameter(#a)',
- index: 0),
+ element: 'parameter(#a)', index: 0),
const Visit(VisitKind.VISIT_REQUIRED_PARAMETER_DECL,
- element: 'parameter(#b)',
- index: 1),
+ element: 'parameter(#b)', index: 1),
],
method: ''),
const Test.clazz(
@@ -561,11 +461,9 @@
target: 'generative_constructor(C#_)',
type: 'C'),
const Visit(VisitKind.VISIT_REQUIRED_PARAMETER_DECL,
- element: 'parameter(#a)',
- index: 0),
+ element: 'parameter(#a)', index: 0),
const Visit(VisitKind.VISIT_REQUIRED_PARAMETER_DECL,
- element: 'parameter(#b)',
- index: 1),
+ element: 'parameter(#b)', index: 1),
],
method: ''),
const Test.clazz(
@@ -584,11 +482,9 @@
target: 'generative_constructor(D#)',
type: 'D'),
const Visit(VisitKind.VISIT_REQUIRED_PARAMETER_DECL,
- element: 'parameter(#a)',
- index: 0),
+ element: 'parameter(#a)', index: 0),
const Visit(VisitKind.VISIT_REQUIRED_PARAMETER_DECL,
- element: 'parameter(#b)',
- index: 1),
+ element: 'parameter(#b)', index: 1),
],
method: ''),
const Test.clazz(
@@ -607,11 +503,9 @@
target: 'generative_constructor(D#)',
type: 'D<int>'),
const Visit(VisitKind.VISIT_REQUIRED_PARAMETER_DECL,
- element: 'parameter(#a)',
- index: 0),
+ element: 'parameter(#a)', index: 0),
const Visit(VisitKind.VISIT_REQUIRED_PARAMETER_DECL,
- element: 'parameter(#b)',
- index: 1),
+ element: 'parameter(#b)', index: 1),
],
method: ''),
const Test.clazz(
@@ -633,11 +527,9 @@
target: 'factory_constructor(D#)',
type: 'D<int>'),
const Visit(VisitKind.VISIT_REQUIRED_PARAMETER_DECL,
- element: 'parameter(#a)',
- index: 0),
+ element: 'parameter(#a)', index: 0),
const Visit(VisitKind.VISIT_REQUIRED_PARAMETER_DECL,
- element: 'parameter(#b)',
- index: 1),
+ element: 'parameter(#b)', index: 1),
],
method: ''),
],
@@ -672,8 +564,7 @@
''',
const [
const Visit(VisitKind.VISIT_INSTANCE_FIELD_DECL,
- element: 'field(C#m)',
- rhs: 42),
+ element: 'field(C#m)', rhs: 42),
]),
const Test(
'''
@@ -683,9 +574,7 @@
''',
const [
const Visit(VisitKind.VISIT_TOP_LEVEL_FUNCTION_DECL,
- element: 'function(m)',
- parameters: '()',
- body: '{var local;}'),
+ element: 'function(m)', parameters: '()', body: '{var local;}'),
const Visit(VisitKind.VISIT_LOCAL_VARIABLE_DECL,
element: 'variable(m#local)'),
]),
@@ -701,8 +590,7 @@
parameters: '()',
body: '{var local=42;}'),
const Visit(VisitKind.VISIT_LOCAL_VARIABLE_DECL,
- element: 'variable(m#local)',
- rhs: 42),
+ element: 'variable(m#local)', rhs: 42),
]),
const Test(
'''
@@ -716,8 +604,7 @@
parameters: '()',
body: '{const local=42;}'),
const Visit(VisitKind.VISIT_LOCAL_CONSTANT_DECL,
- element: 'variable(m#local)',
- constant: 42),
+ element: 'variable(m#local)', constant: 42),
]),
const Test(
'''
@@ -747,11 +634,9 @@
parameters: '()',
body: '{var local1=42,local2=true;}'),
const Visit(VisitKind.VISIT_LOCAL_VARIABLE_DECL,
- element: 'variable(m#local1)',
- rhs: 42),
+ element: 'variable(m#local1)', rhs: 42),
const Visit(VisitKind.VISIT_LOCAL_VARIABLE_DECL,
- element: 'variable(m#local2)',
- rhs: true),
+ element: 'variable(m#local2)', rhs: true),
]),
const Test(
'''
@@ -765,11 +650,9 @@
parameters: '()',
body: '{const local1=42,local2=true;}'),
const Visit(VisitKind.VISIT_LOCAL_CONSTANT_DECL,
- element: 'variable(m#local1)',
- constant: 42),
+ element: 'variable(m#local1)', constant: 42),
const Visit(VisitKind.VISIT_LOCAL_CONSTANT_DECL,
- element: 'variable(m#local2)',
- constant: true),
+ element: 'variable(m#local2)', constant: true),
]),
const Test.clazz(
'''
@@ -778,8 +661,7 @@
}
''',
const [
- const Visit(VisitKind.VISIT_STATIC_FIELD_DECL,
- element: 'field(C#m)'),
+ const Visit(VisitKind.VISIT_STATIC_FIELD_DECL, element: 'field(C#m)'),
]),
const Test.clazz(
'''
@@ -788,10 +670,8 @@
}
''',
const [
- const Visit(VisitKind.VISIT_STATIC_FIELD_DECL,
- element: 'field(C#m)'),
- const Visit(VisitKind.VISIT_STATIC_FIELD_DECL,
- element: 'field(C#n)'),
+ const Visit(VisitKind.VISIT_STATIC_FIELD_DECL, element: 'field(C#m)'),
+ const Visit(VisitKind.VISIT_STATIC_FIELD_DECL, element: 'field(C#n)'),
]),
const Test.clazz(
'''
@@ -800,14 +680,10 @@
}
''',
const [
- const Visit(VisitKind.VISIT_STATIC_FIELD_DECL,
- element: 'field(C#k)'),
- const Visit(VisitKind.VISIT_STATIC_FIELD_DECL,
- element: 'field(C#l)'),
- const Visit(VisitKind.VISIT_STATIC_FIELD_DECL,
- element: 'field(C#m)'),
- const Visit(VisitKind.VISIT_STATIC_FIELD_DECL,
- element: 'field(C#n)'),
+ const Visit(VisitKind.VISIT_STATIC_FIELD_DECL, element: 'field(C#k)'),
+ const Visit(VisitKind.VISIT_STATIC_FIELD_DECL, element: 'field(C#l)'),
+ const Visit(VisitKind.VISIT_STATIC_FIELD_DECL, element: 'field(C#m)'),
+ const Visit(VisitKind.VISIT_STATIC_FIELD_DECL, element: 'field(C#n)'),
]),
const Test.clazz(
'''
@@ -817,8 +693,7 @@
''',
const [
const Visit(VisitKind.VISIT_STATIC_FIELD_DECL,
- element: 'field(C#m)',
- rhs: 42),
+ element: 'field(C#m)', rhs: 42),
]),
const Test.clazz(
'''
@@ -828,11 +703,9 @@
''',
const [
const Visit(VisitKind.VISIT_STATIC_FIELD_DECL,
- element: 'field(C#m)',
- rhs: 42),
+ element: 'field(C#m)', rhs: 42),
const Visit(VisitKind.VISIT_STATIC_FIELD_DECL,
- element: 'field(C#n)',
- rhs: true),
+ element: 'field(C#n)', rhs: true),
]),
const Test.clazz(
'''
@@ -842,8 +715,7 @@
''',
const [
const Visit(VisitKind.VISIT_STATIC_CONSTANT_DECL,
- element: 'field(C#m)',
- constant: 42),
+ element: 'field(C#m)', constant: 42),
]),
const Test(
'''
@@ -851,7 +723,7 @@
''',
const [
const Visit(VisitKind.VISIT_TOP_LEVEL_FIELD_DECL,
- element: 'field(m)'),
+ element: 'field(m)'),
]),
const Test(
'''
@@ -869,8 +741,7 @@
''',
const [
const Visit(VisitKind.VISIT_TOP_LEVEL_FIELD_DECL,
- element: 'field(m)',
- rhs: 42),
+ element: 'field(m)', rhs: 42),
]),
const Test(
'''
@@ -878,8 +749,7 @@
''',
const [
const Visit(VisitKind.VISIT_TOP_LEVEL_CONSTANT_DECL,
- element: 'field(m)',
- constant: 42),
+ element: 'field(m)', constant: 42),
]),
],
};
diff --git a/tests/compiler/dart2js/semantic_visitor_test_decl_visitor.dart b/tests/compiler/dart2js/semantic_visitor_test_decl_visitor.dart
index a5e4e20..86b1a3f 100644
--- a/tests/compiler/dart2js/semantic_visitor_test_decl_visitor.dart
+++ b/tests/compiler/dart2js/semantic_visitor_test_decl_visitor.dart
@@ -5,47 +5,31 @@
part of dart2js.semantics_visitor_test;
class SemanticDeclarationTestVisitor extends SemanticTestVisitor {
-
SemanticDeclarationTestVisitor(TreeElements elements) : super(elements);
@override
errorUnresolvedSuperConstructorInvoke(
- Send node,
- Element element,
- NodeList arguments,
- Selector selector,
- arg) {
+ Send node, Element element, NodeList arguments, Selector selector, arg) {
// TODO: implement errorUnresolvedSuperConstructorInvoke
}
@override
errorUnresolvedThisConstructorInvoke(
- Send node,
- Element element,
- NodeList arguments,
- Selector selector,
- arg) {
+ Send node, Element element, NodeList arguments, Selector selector, arg) {
// TODO: implement errorUnresolvedThisConstructorInvoke
}
@override
visitAbstractMethodDeclaration(
- FunctionExpression node,
- MethodElement method,
- NodeList parameters,
- arg) {
+ FunctionExpression node, MethodElement method, NodeList parameters, arg) {
visits.add(new Visit(VisitKind.VISIT_ABSTRACT_METHOD_DECL,
element: method, parameters: parameters));
applyParameters(parameters, arg);
}
@override
- visitClosureDeclaration(
- FunctionExpression node,
- LocalFunctionElement function,
- NodeList parameters,
- Node body,
- arg) {
+ visitClosureDeclaration(FunctionExpression node,
+ LocalFunctionElement function, NodeList parameters, Node body, arg) {
visits.add(new Visit(VisitKind.VISIT_CLOSURE_DECL,
element: function, parameters: parameters, body: body));
applyParameters(parameters, arg);
@@ -53,12 +37,8 @@
}
@override
- visitFactoryConstructorDeclaration(
- FunctionExpression node,
- ConstructorElement constructor,
- NodeList parameters,
- Node body,
- arg) {
+ visitFactoryConstructorDeclaration(FunctionExpression node,
+ ConstructorElement constructor, NodeList parameters, Node body, arg) {
visits.add(new Visit(VisitKind.VISIT_FACTORY_CONSTRUCTOR_DECL,
element: constructor, parameters: parameters, body: body));
applyParameters(parameters, arg);
@@ -67,10 +47,7 @@
@override
visitFieldInitializer(
- SendSet node,
- FieldElement field,
- Node initializer,
- arg) {
+ SendSet node, FieldElement field, Node initializer, arg) {
visits.add(new Visit(VisitKind.VISIT_FIELD_INITIALIZER,
element: field, rhs: initializer));
apply(initializer, arg);
@@ -92,12 +69,8 @@
}
@override
- visitInstanceMethodDeclaration(
- FunctionExpression node,
- MethodElement method,
- NodeList parameters,
- Node body,
- arg) {
+ visitInstanceMethodDeclaration(FunctionExpression node, MethodElement method,
+ NodeList parameters, Node body, arg) {
visits.add(new Visit(VisitKind.VISIT_INSTANCE_METHOD_DECL,
element: method, parameters: parameters, body: body));
applyParameters(parameters, arg);
@@ -105,12 +78,8 @@
}
@override
- visitLocalFunctionDeclaration(
- FunctionExpression node,
- LocalFunctionElement function,
- NodeList parameters,
- Node body,
- arg) {
+ visitLocalFunctionDeclaration(FunctionExpression node,
+ LocalFunctionElement function, NodeList parameters, Node body, arg) {
visits.add(new Visit(VisitKind.VISIT_LOCAL_FUNCTION_DECL,
element: function, parameters: parameters, body: body));
applyParameters(parameters, arg);
@@ -125,8 +94,7 @@
InterfaceType redirectionType,
ConstructorElement redirectionTarget,
arg) {
- visits.add(new Visit(
- VisitKind.VISIT_REDIRECTING_FACTORY_CONSTRUCTOR_DECL,
+ visits.add(new Visit(VisitKind.VISIT_REDIRECTING_FACTORY_CONSTRUCTOR_DECL,
element: constructor,
parameters: parameters,
target: redirectionTarget,
@@ -151,12 +119,8 @@
}
@override
- visitStaticFunctionDeclaration(
- FunctionExpression node,
- MethodElement function,
- NodeList parameters,
- Node body,
- arg) {
+ visitStaticFunctionDeclaration(FunctionExpression node,
+ MethodElement function, NodeList parameters, Node body, arg) {
visits.add(new Visit(VisitKind.VISIT_STATIC_FUNCTION_DECL,
element: function, parameters: parameters, body: body));
applyParameters(parameters, arg);
@@ -172,45 +136,37 @@
CallStructure callStructure,
arg) {
visits.add(new Visit(VisitKind.VISIT_SUPER_CONSTRUCTOR_INVOKE,
- element: superConstructor, type: type,
- arguments: arguments, selector: callStructure));
+ element: superConstructor,
+ type: type,
+ arguments: arguments,
+ selector: callStructure));
super.visitSuperConstructorInvoke(
node, superConstructor, type, arguments, callStructure, arg);
}
@override
- visitImplicitSuperConstructorInvoke(
- FunctionExpression node,
- ConstructorElement superConstructor,
- InterfaceType type,
- arg) {
+ visitImplicitSuperConstructorInvoke(FunctionExpression node,
+ ConstructorElement superConstructor, InterfaceType type, arg) {
visits.add(new Visit(VisitKind.VISIT_IMPLICIT_SUPER_CONSTRUCTOR_INVOKE,
element: superConstructor, type: type));
- super.visitImplicitSuperConstructorInvoke(
- node, superConstructor, type, arg);
+ super
+ .visitImplicitSuperConstructorInvoke(node, superConstructor, type, arg);
}
@override
- visitThisConstructorInvoke(
- Send node,
- ConstructorElement thisConstructor,
- NodeList arguments,
- CallStructure callStructure,
- arg) {
+ visitThisConstructorInvoke(Send node, ConstructorElement thisConstructor,
+ NodeList arguments, CallStructure callStructure, arg) {
visits.add(new Visit(VisitKind.VISIT_THIS_CONSTRUCTOR_INVOKE,
element: thisConstructor,
- arguments: arguments, selector: callStructure));
+ arguments: arguments,
+ selector: callStructure));
super.visitThisConstructorInvoke(
node, thisConstructor, arguments, callStructure, arg);
}
@override
- visitTopLevelFunctionDeclaration(
- FunctionExpression node,
- MethodElement function,
- NodeList parameters,
- Node body,
- arg) {
+ visitTopLevelFunctionDeclaration(FunctionExpression node,
+ MethodElement function, NodeList parameters, Node body, arg) {
visits.add(new Visit(VisitKind.VISIT_TOP_LEVEL_FUNCTION_DECL,
element: function, parameters: parameters, body: body));
applyParameters(parameters, arg);
@@ -219,10 +175,7 @@
@override
errorUnresolvedFieldInitializer(
- SendSet node,
- Element element,
- Node initializer,
- arg) {
+ SendSet node, Element element, Node initializer, arg) {
// TODO: implement errorUnresolvedFieldInitializer
}
@@ -241,34 +194,22 @@
}
@override
- visitParameterDeclaration(
- VariableDefinitions node,
- Node definition,
- ParameterElement parameter,
- int index,
- arg) {
+ visitParameterDeclaration(VariableDefinitions node, Node definition,
+ ParameterElement parameter, int index, arg) {
visits.add(new Visit(VisitKind.VISIT_REQUIRED_PARAMETER_DECL,
element: parameter, index: index));
}
@override
- visitInitializingFormalDeclaration(
- VariableDefinitions node,
- Node definition,
- InitializingFormalElement initializingFormal,
- int index,
- arg) {
+ visitInitializingFormalDeclaration(VariableDefinitions node, Node definition,
+ InitializingFormalElement initializingFormal, int index, arg) {
visits.add(new Visit(VisitKind.VISIT_REQUIRED_INITIALIZING_FORMAL_DECL,
element: initializingFormal, index: index));
}
@override
- visitLocalVariableDeclaration(
- VariableDefinitions node,
- Node definition,
- LocalVariableElement variable,
- Node initializer,
- arg) {
+ visitLocalVariableDeclaration(VariableDefinitions node, Node definition,
+ LocalVariableElement variable, Node initializer, arg) {
visits.add(new Visit(VisitKind.VISIT_LOCAL_VARIABLE_DECL,
element: variable, rhs: initializer));
if (initializer != null) {
@@ -277,12 +218,8 @@
}
@override
- visitLocalConstantDeclaration(
- VariableDefinitions node,
- Node definition,
- LocalVariableElement variable,
- ConstantExpression constant,
- arg) {
+ visitLocalConstantDeclaration(VariableDefinitions node, Node definition,
+ LocalVariableElement variable, ConstantExpression constant, arg) {
visits.add(new Visit(VisitKind.VISIT_LOCAL_CONSTANT_DECL,
element: variable, constant: constant.toDartText()));
}
@@ -300,12 +237,8 @@
}
@override
- visitNamedParameterDeclaration(
- VariableDefinitions node,
- Node definition,
- ParameterElement parameter,
- ConstantExpression defaultValue,
- arg) {
+ visitNamedParameterDeclaration(VariableDefinitions node, Node definition,
+ ParameterElement parameter, ConstantExpression defaultValue, arg) {
visits.add(new Visit(VisitKind.VISIT_NAMED_PARAMETER_DECL,
element: parameter,
constant: defaultValue != null ? defaultValue.toDartText() : null));
@@ -326,12 +259,8 @@
}
@override
- visitInstanceFieldDeclaration(
- VariableDefinitions node,
- Node definition,
- FieldElement field,
- Node initializer,
- arg) {
+ visitInstanceFieldDeclaration(VariableDefinitions node, Node definition,
+ FieldElement field, Node initializer, arg) {
visits.add(new Visit(VisitKind.VISIT_INSTANCE_FIELD_DECL,
element: field, rhs: initializer));
if (initializer != null) {
@@ -340,23 +269,15 @@
}
@override
- visitStaticConstantDeclaration(
- VariableDefinitions node,
- Node definition,
- FieldElement field,
- ConstantExpression constant,
- arg) {
+ visitStaticConstantDeclaration(VariableDefinitions node, Node definition,
+ FieldElement field, ConstantExpression constant, arg) {
visits.add(new Visit(VisitKind.VISIT_STATIC_CONSTANT_DECL,
element: field, constant: constant.toDartText()));
}
@override
- visitStaticFieldDeclaration(
- VariableDefinitions node,
- Node definition,
- FieldElement field,
- Node initializer,
- arg) {
+ visitStaticFieldDeclaration(VariableDefinitions node, Node definition,
+ FieldElement field, Node initializer, arg) {
visits.add(new Visit(VisitKind.VISIT_STATIC_FIELD_DECL,
element: field, rhs: initializer));
if (initializer != null) {
@@ -365,23 +286,15 @@
}
@override
- visitTopLevelConstantDeclaration(
- VariableDefinitions node,
- Node definition,
- FieldElement field,
- ConstantExpression constant,
- arg) {
+ visitTopLevelConstantDeclaration(VariableDefinitions node, Node definition,
+ FieldElement field, ConstantExpression constant, arg) {
visits.add(new Visit(VisitKind.VISIT_TOP_LEVEL_CONSTANT_DECL,
element: field, constant: constant.toDartText()));
}
@override
- visitTopLevelFieldDeclaration(
- VariableDefinitions node,
- Node definition,
- FieldElement field,
- Node initializer,
- arg) {
+ visitTopLevelFieldDeclaration(VariableDefinitions node, Node definition,
+ FieldElement field, Node initializer, arg) {
visits.add(new Visit(VisitKind.VISIT_TOP_LEVEL_FIELD_DECL,
element: field, rhs: initializer));
if (initializer != null) {
@@ -391,19 +304,14 @@
@override
visitAbstractGetterDeclaration(
- FunctionExpression node,
- MethodElement getter,
- arg) {
- visits.add(new Visit(VisitKind.VISIT_ABSTRACT_GETTER_DECL,
- element: getter));
+ FunctionExpression node, MethodElement getter, arg) {
+ visits
+ .add(new Visit(VisitKind.VISIT_ABSTRACT_GETTER_DECL, element: getter));
}
@override
visitAbstractSetterDeclaration(
- FunctionExpression node,
- MethodElement setter,
- NodeList parameters,
- arg) {
+ FunctionExpression node, MethodElement setter, NodeList parameters, arg) {
visits.add(new Visit(VisitKind.VISIT_ABSTRACT_SETTER_DECL,
element: setter, parameters: parameters));
applyParameters(parameters, arg);
@@ -411,22 +319,15 @@
@override
visitInstanceGetterDeclaration(
- FunctionExpression node,
- MethodElement getter,
- Node body,
- arg) {
+ FunctionExpression node, MethodElement getter, Node body, arg) {
visits.add(new Visit(VisitKind.VISIT_INSTANCE_GETTER_DECL,
element: getter, body: body));
apply(body, arg);
}
@override
- visitInstanceSetterDeclaration(
- FunctionExpression node,
- MethodElement setter,
- NodeList parameters,
- Node body,
- arg) {
+ visitInstanceSetterDeclaration(FunctionExpression node, MethodElement setter,
+ NodeList parameters, Node body, arg) {
visits.add(new Visit(VisitKind.VISIT_INSTANCE_SETTER_DECL,
element: setter, parameters: parameters, body: body));
applyParameters(parameters, arg);
@@ -435,22 +336,15 @@
@override
visitTopLevelGetterDeclaration(
- FunctionExpression node,
- MethodElement getter,
- Node body,
- arg) {
+ FunctionExpression node, MethodElement getter, Node body, arg) {
visits.add(new Visit(VisitKind.VISIT_TOP_LEVEL_GETTER_DECL,
element: getter, body: body));
apply(body, arg);
}
@override
- visitTopLevelSetterDeclaration(
- FunctionExpression node,
- MethodElement setter,
- NodeList parameters,
- Node body,
- arg) {
+ visitTopLevelSetterDeclaration(FunctionExpression node, MethodElement setter,
+ NodeList parameters, Node body, arg) {
visits.add(new Visit(VisitKind.VISIT_TOP_LEVEL_SETTER_DECL,
element: setter, parameters: parameters, body: body));
applyParameters(parameters, arg);
@@ -459,22 +353,15 @@
@override
visitStaticGetterDeclaration(
- FunctionExpression node,
- MethodElement getter,
- Node body,
- arg) {
+ FunctionExpression node, MethodElement getter, Node body, arg) {
visits.add(new Visit(VisitKind.VISIT_STATIC_GETTER_DECL,
element: getter, body: body));
apply(body, arg);
}
@override
- visitStaticSetterDeclaration(
- FunctionExpression node,
- MethodElement setter,
- NodeList parameters,
- Node body,
- arg) {
+ visitStaticSetterDeclaration(FunctionExpression node, MethodElement setter,
+ NodeList parameters, Node body, arg) {
visits.add(new Visit(VisitKind.VISIT_STATIC_SETTER_DECL,
element: setter, parameters: parameters, body: body));
applyParameters(parameters, arg);
diff --git a/tests/compiler/dart2js/semantic_visitor_test_send_data.dart b/tests/compiler/dart2js/semantic_visitor_test_send_data.dart
index 5ee48ff..47b55ca 100644
--- a/tests/compiler/dart2js/semantic_visitor_test_send_data.dart
+++ b/tests/compiler/dart2js/semantic_visitor_test_send_data.dart
@@ -8,64 +8,69 @@
'Parameters': const [
// Parameters
const Test('m(o) => o;',
- const Visit(VisitKind.VISIT_PARAMETER_GET,
- element: 'parameter(m#o)')),
- const Test('m(o) { o = 42; }',
+ const Visit(VisitKind.VISIT_PARAMETER_GET, element: 'parameter(m#o)')),
+ const Test(
+ 'm(o) { o = 42; }',
const Visit(VisitKind.VISIT_PARAMETER_SET,
- element: 'parameter(m#o)',
- rhs:'42')),
- const Test('m(o) { o(null, 42); }',
+ element: 'parameter(m#o)', rhs: '42')),
+ const Test(
+ 'm(o) { o(null, 42); }',
const Visit(VisitKind.VISIT_PARAMETER_INVOKE,
- element: 'parameter(m#o)',
- arguments: '(null,42)',
- selector: 'CallStructure(arity=2)')),
- const Test('m(final o) { o = 42; }',
+ element: 'parameter(m#o)',
+ arguments: '(null,42)',
+ selector: 'CallStructure(arity=2)')),
+ const Test(
+ 'm(final o) { o = 42; }',
const Visit(VisitKind.VISIT_FINAL_PARAMETER_SET,
- element: 'parameter(m#o)',
- rhs:'42')),
+ element: 'parameter(m#o)', rhs: '42')),
],
'Local variables': const [
// Local variables
- const Test('m() { var o; return o; }',
+ const Test(
+ 'm() { var o; return o; }',
const Visit(VisitKind.VISIT_LOCAL_VARIABLE_GET,
- element: 'variable(m#o)')),
- const Test('m() { var o; o = 42; }',
+ element: 'variable(m#o)')),
+ const Test(
+ 'm() { var o; o = 42; }',
const Visit(VisitKind.VISIT_LOCAL_VARIABLE_SET,
- element: 'variable(m#o)',
- rhs:'42')),
- const Test('m() { var o; o(null, 42); }',
+ element: 'variable(m#o)', rhs: '42')),
+ const Test(
+ 'm() { var o; o(null, 42); }',
const Visit(VisitKind.VISIT_LOCAL_VARIABLE_INVOKE,
- element: 'variable(m#o)',
- arguments: '(null,42)',
- selector: 'CallStructure(arity=2)')),
- const Test('m() { final o = 0; o = 42; }',
+ element: 'variable(m#o)',
+ arguments: '(null,42)',
+ selector: 'CallStructure(arity=2)')),
+ const Test(
+ 'm() { final o = 0; o = 42; }',
const Visit(VisitKind.VISIT_FINAL_LOCAL_VARIABLE_SET,
- element: 'variable(m#o)',
- rhs:'42')),
- const Test('m() { const o = 0; o = 42; }',
+ element: 'variable(m#o)', rhs: '42')),
+ const Test(
+ 'm() { const o = 0; o = 42; }',
const Visit(VisitKind.VISIT_FINAL_LOCAL_VARIABLE_SET,
- element: 'variable(m#o)',
- rhs:'42')),
+ element: 'variable(m#o)', rhs: '42')),
],
'Local functions': const [
// Local functions
- const Test('m() { o(a, b) {}; return o; }',
+ const Test(
+ 'm() { o(a, b) {}; return o; }',
const Visit(VisitKind.VISIT_LOCAL_FUNCTION_GET,
- element: 'function(m#o)')),
- const Test('m() { o(a, b) {}; o(null, 42); }',
+ element: 'function(m#o)')),
+ const Test(
+ 'm() { o(a, b) {}; o(null, 42); }',
const Visit(VisitKind.VISIT_LOCAL_FUNCTION_INVOKE,
- element: 'function(m#o)',
- arguments: '(null,42)',
- selector: 'CallStructure(arity=2)')),
- const Test('m() { o(a) {}; o(null, 42); }',
+ element: 'function(m#o)',
+ arguments: '(null,42)',
+ selector: 'CallStructure(arity=2)')),
+ const Test(
+ 'm() { o(a) {}; o(null, 42); }',
const Visit(VisitKind.VISIT_LOCAL_FUNCTION_INCOMPATIBLE_INVOKE,
- element: 'function(m#o)',
- arguments: '(null,42)',
- selector: 'CallStructure(arity=2)')),
- const Test('m() { o(a, b) {}; o = 42; }',
+ element: 'function(m#o)',
+ arguments: '(null,42)',
+ selector: 'CallStructure(arity=2)')),
+ const Test(
+ 'm() { o(a, b) {}; o = 42; }',
const Visit(VisitKind.VISIT_LOCAL_FUNCTION_SET,
- element: 'function(m#o)',
- rhs: '42')),
+ element: 'function(m#o)', rhs: '42')),
],
'Static fields': const [
// Static fields
@@ -74,8 +79,7 @@
class C { static var o; }
m() => C.o;
''',
- const Visit(VisitKind.VISIT_STATIC_FIELD_GET,
- element: 'field(C#o)')),
+ const Visit(VisitKind.VISIT_STATIC_FIELD_GET, element: 'field(C#o)')),
const Test.clazz(
'''
class C {
@@ -83,8 +87,7 @@
m() => o;
}
''',
- const Visit(VisitKind.VISIT_STATIC_FIELD_GET,
- element: 'field(C#o)')),
+ const Visit(VisitKind.VISIT_STATIC_FIELD_GET, element: 'field(C#o)')),
const Test.clazz(
'''
class C {
@@ -92,8 +95,7 @@
m() => C.o;
}
''',
- const Visit(VisitKind.VISIT_STATIC_FIELD_GET,
- element: 'field(C#o)')),
+ const Visit(VisitKind.VISIT_STATIC_FIELD_GET, element: 'field(C#o)')),
const Test.prefix(
'''
class C {
@@ -101,8 +103,7 @@
}
''',
'm() => p.C.o;',
- const Visit(VisitKind.VISIT_STATIC_FIELD_GET,
- element: 'field(C#o)')),
+ const Visit(VisitKind.VISIT_STATIC_FIELD_GET, element: 'field(C#o)')),
const Test.clazz(
'''
class C {
@@ -111,7 +112,7 @@
}
''',
const Visit(VisitKind.ERROR_INVALID_GET,
- error: MessageKind.NO_INSTANCE_AVAILABLE)),
+ error: MessageKind.NO_INSTANCE_AVAILABLE)),
const Test.prefix(
'''
class C {
@@ -120,10 +121,8 @@
''',
'm() => p.C.o;',
const [
- const Visit(VisitKind.PREVISIT_DEFERRED_ACCESS,
- element: 'prefix(p)'),
- const Visit(VisitKind.VISIT_STATIC_FIELD_GET,
- element: 'field(C#o)'),
+ const Visit(VisitKind.PREVISIT_DEFERRED_ACCESS, element: 'prefix(p)'),
+ const Visit(VisitKind.VISIT_STATIC_FIELD_GET, element: 'field(C#o)'),
],
isDeferred: true),
const Test(
@@ -133,8 +132,7 @@
}
m() => C.o;
''',
- const Visit(VisitKind.VISIT_UNRESOLVED_GET,
- name: 'o')),
+ const Visit(VisitKind.VISIT_UNRESOLVED_GET, name: 'o')),
const Test(
'''
class C {
@@ -142,9 +140,7 @@
}
m() { C.o = 42; }
''',
- const Visit(VisitKind.VISIT_UNRESOLVED_SET,
- name: 'o',
- rhs: '42')),
+ const Visit(VisitKind.VISIT_UNRESOLVED_SET, name: 'o', rhs: '42')),
const Test(
'''
class C {
@@ -152,15 +148,14 @@
}
m() => C.o;
''',
- const Visit(VisitKind.VISIT_UNRESOLVED_GET,
- name: 'o')),
+ const Visit(VisitKind.VISIT_UNRESOLVED_GET, name: 'o')),
const Test.prefix(
'''
''',
'm() => p.C.o;',
const [
const Visit(VisitKind.VISIT_DYNAMIC_PROPERTY_GET,
- receiver: 'p.C', name: 'o'),
+ receiver: 'p.C', name: 'o'),
const Visit(VisitKind.VISIT_UNRESOLVED_GET, name: 'C'),
]),
const Test.prefix(
@@ -176,11 +171,9 @@
'm() => p.C.o;',
const [
const Visit(VisitKind.VISIT_DYNAMIC_PROPERTY_GET,
- receiver: 'p.C', name: 'o'),
- const Visit(VisitKind.PREVISIT_DEFERRED_ACCESS,
- element: 'prefix(p)'),
- const Visit(VisitKind.VISIT_UNRESOLVED_GET,
- name: 'C'),
+ receiver: 'p.C', name: 'o'),
+ const Visit(VisitKind.PREVISIT_DEFERRED_ACCESS, element: 'prefix(p)'),
+ const Visit(VisitKind.VISIT_UNRESOLVED_GET, name: 'C'),
],
isDeferred: true),
const Test.prefix(
@@ -190,10 +183,8 @@
''',
'm() => p.C.o;',
const [
- const Visit(VisitKind.PREVISIT_DEFERRED_ACCESS,
- element: 'prefix(p)'),
- const Visit(VisitKind.VISIT_UNRESOLVED_GET,
- name: 'o'),
+ const Visit(VisitKind.PREVISIT_DEFERRED_ACCESS, element: 'prefix(p)'),
+ const Visit(VisitKind.VISIT_UNRESOLVED_GET, name: 'o'),
],
isDeferred: true),
const Test(
@@ -210,8 +201,7 @@
m() { C.o = 42; }
''',
const Visit(VisitKind.VISIT_STATIC_FIELD_SET,
- element: 'field(C#o)',
- rhs: '42')),
+ element: 'field(C#o)', rhs: '42')),
const Test.clazz(
'''
class C {
@@ -220,8 +210,7 @@
}
''',
const Visit(VisitKind.VISIT_STATIC_FIELD_SET,
- element: 'field(C#o)',
- rhs: '42')),
+ element: 'field(C#o)', rhs: '42')),
const Test.clazz(
'''
class C {
@@ -230,8 +219,7 @@
}
''',
const Visit(VisitKind.VISIT_STATIC_FIELD_SET,
- element: 'field(C#o)',
- rhs: '42')),
+ element: 'field(C#o)', rhs: '42')),
const Test.prefix(
'''
class C {
@@ -240,8 +228,7 @@
''',
'm() { p.C.o = 42; }',
const Visit(VisitKind.VISIT_STATIC_FIELD_SET,
- element: 'field(C#o)',
- rhs: '42')),
+ element: 'field(C#o)', rhs: '42')),
const Test.clazz(
'''
class C {
@@ -250,8 +237,7 @@
}
''',
const Visit(VisitKind.ERROR_INVALID_SET,
- error: MessageKind.NO_INSTANCE_AVAILABLE,
- rhs: '42')),
+ error: MessageKind.NO_INSTANCE_AVAILABLE, rhs: '42')),
const Test(
'''
class C {
@@ -260,8 +246,7 @@
m() { C.o(null, 42); }
''',
const Visit(VisitKind.VISIT_STATIC_FIELD_INVOKE,
- element: 'field(C#o)',
- arguments: '(null,42)')),
+ element: 'field(C#o)', arguments: '(null,42)')),
const Test.clazz(
'''
class C {
@@ -270,8 +255,7 @@
}
''',
const Visit(VisitKind.VISIT_STATIC_FIELD_INVOKE,
- element: 'field(C#o)',
- arguments: '(null,42)')),
+ element: 'field(C#o)', arguments: '(null,42)')),
const Test.clazz(
'''
class C {
@@ -280,8 +264,7 @@
}
''',
const Visit(VisitKind.VISIT_STATIC_FIELD_INVOKE,
- element: 'field(C#o)',
- arguments: '(null,42)')),
+ element: 'field(C#o)', arguments: '(null,42)')),
const Test.clazz(
'''
class C {
@@ -290,8 +273,7 @@
}
''',
const Visit(VisitKind.ERROR_INVALID_INVOKE,
- error: MessageKind.NO_INSTANCE_AVAILABLE,
- arguments: '(null,42)')),
+ error: MessageKind.NO_INSTANCE_AVAILABLE, arguments: '(null,42)')),
const Test.prefix(
'''
class C {
@@ -300,24 +282,21 @@
''',
'm() { p.C.o(null, 42); }',
const Visit(VisitKind.VISIT_STATIC_FIELD_INVOKE,
- element: 'field(C#o)',
- arguments: '(null,42)')),
+ element: 'field(C#o)', arguments: '(null,42)')),
const Test(
'''
class C {}
m() => C.this(null, 42);
''',
const Visit(VisitKind.ERROR_INVALID_INVOKE,
- error: MessageKind.THIS_PROPERTY,
- arguments: '(null,42)')),
+ error: MessageKind.THIS_PROPERTY, arguments: '(null,42)')),
const Test(
'''
class C { static final o = 0; }
m() { C.o = 42; }
''',
const Visit(VisitKind.VISIT_FINAL_STATIC_FIELD_SET,
- element: 'field(C#o)',
- rhs: '42')),
+ element: 'field(C#o)', rhs: '42')),
const Test.clazz(
'''
class C {
@@ -326,8 +305,7 @@
}
''',
const Visit(VisitKind.VISIT_FINAL_STATIC_FIELD_SET,
- element: 'field(C#o)',
- rhs: '42')),
+ element: 'field(C#o)', rhs: '42')),
const Test.clazz(
'''
class C {
@@ -336,8 +314,7 @@
}
''',
const Visit(VisitKind.VISIT_FINAL_STATIC_FIELD_SET,
- element: 'field(C#o)',
- rhs: '42')),
+ element: 'field(C#o)', rhs: '42')),
const Test.prefix(
'''
class C {
@@ -346,16 +323,14 @@
''',
'm() { p.C.o = 42; }',
const Visit(VisitKind.VISIT_FINAL_STATIC_FIELD_SET,
- element: 'field(C#o)',
- rhs: '42')),
+ element: 'field(C#o)', rhs: '42')),
const Test(
'''
class C { static const o = 0; }
m() { C.o = 42; }
''',
const Visit(VisitKind.VISIT_FINAL_STATIC_FIELD_SET,
- element: 'field(C#o)',
- rhs: '42')),
+ element: 'field(C#o)', rhs: '42')),
const Test.clazz(
'''
class C {
@@ -364,8 +339,7 @@
}
''',
const Visit(VisitKind.VISIT_FINAL_STATIC_FIELD_SET,
- element: 'field(C#o)',
- rhs: '42')),
+ element: 'field(C#o)', rhs: '42')),
const Test.clazz(
'''
class C {
@@ -374,8 +348,7 @@
}
''',
const Visit(VisitKind.VISIT_FINAL_STATIC_FIELD_SET,
- element: 'field(C#o)',
- rhs: '42')),
+ element: 'field(C#o)', rhs: '42')),
const Test.prefix(
'''
class C {
@@ -384,8 +357,7 @@
''',
'm() { p.C.o = 42; }',
const Visit(VisitKind.VISIT_FINAL_STATIC_FIELD_SET,
- element: 'field(C#o)',
- rhs: '42')),
+ element: 'field(C#o)', rhs: '42')),
],
'Static properties': const [
// Static properties
@@ -396,8 +368,7 @@
}
m() => C.o;
''',
- const Visit(VisitKind.VISIT_STATIC_GETTER_GET,
- element: 'getter(C#o)')),
+ const Visit(VisitKind.VISIT_STATIC_GETTER_GET, element: 'getter(C#o)')),
const Test.clazz(
'''
class C {
@@ -405,8 +376,7 @@
m() => o;
}
''',
- const Visit(VisitKind.VISIT_STATIC_GETTER_GET,
- element: 'getter(C#o)')),
+ const Visit(VisitKind.VISIT_STATIC_GETTER_GET, element: 'getter(C#o)')),
const Test.clazz(
'''
class C {
@@ -414,8 +384,7 @@
m() => C.o;
}
''',
- const Visit(VisitKind.VISIT_STATIC_GETTER_GET,
- element: 'getter(C#o)')),
+ const Visit(VisitKind.VISIT_STATIC_GETTER_GET, element: 'getter(C#o)')),
const Test.prefix(
'''
class C {
@@ -423,16 +392,14 @@
}
''',
'm() => p.C.o;',
- const Visit(VisitKind.VISIT_STATIC_GETTER_GET,
- element: 'getter(C#o)')),
+ const Visit(VisitKind.VISIT_STATIC_GETTER_GET, element: 'getter(C#o)')),
const Test(
'''
class C { static get o => 42; }
m() { C.o = 42; }
''',
const Visit(VisitKind.VISIT_STATIC_GETTER_SET,
- element: 'getter(C#o)',
- rhs: '42')),
+ element: 'getter(C#o)', rhs: '42')),
const Test.clazz(
'''
class C {
@@ -441,8 +408,7 @@
}
''',
const Visit(VisitKind.VISIT_STATIC_GETTER_SET,
- element: 'getter(C#o)',
- rhs: '42')),
+ element: 'getter(C#o)', rhs: '42')),
const Test.clazz(
'''
class C {
@@ -451,8 +417,7 @@
}
''',
const Visit(VisitKind.VISIT_STATIC_GETTER_SET,
- element: 'getter(C#o)',
- rhs: '42')),
+ element: 'getter(C#o)', rhs: '42')),
const Test.prefix(
'''
class C {
@@ -461,8 +426,7 @@
''',
'm() { p.C.o = 42; }',
const Visit(VisitKind.VISIT_STATIC_GETTER_SET,
- element: 'getter(C#o)',
- rhs: '42')),
+ element: 'getter(C#o)', rhs: '42')),
const Test(
'''
class C {
@@ -470,8 +434,7 @@
}
m() => C.o;
''',
- const Visit(VisitKind.VISIT_STATIC_SETTER_GET,
- element: 'setter(C#o)')),
+ const Visit(VisitKind.VISIT_STATIC_SETTER_GET, element: 'setter(C#o)')),
const Test.clazz(
'''
class C {
@@ -479,8 +442,7 @@
m() => o;
}
''',
- const Visit(VisitKind.VISIT_STATIC_SETTER_GET,
- element: 'setter(C#o)')),
+ const Visit(VisitKind.VISIT_STATIC_SETTER_GET, element: 'setter(C#o)')),
const Test.clazz(
'''
@@ -489,8 +451,7 @@
m() => C.o;
}
''',
- const Visit(VisitKind.VISIT_STATIC_SETTER_GET,
- element: 'setter(C#o)')),
+ const Visit(VisitKind.VISIT_STATIC_SETTER_GET, element: 'setter(C#o)')),
const Test.prefix(
'''
class C {
@@ -498,16 +459,14 @@
}
''',
'm() => p.C.o;',
- const Visit(VisitKind.VISIT_STATIC_SETTER_GET,
- element: 'setter(C#o)')),
+ const Visit(VisitKind.VISIT_STATIC_SETTER_GET, element: 'setter(C#o)')),
const Test(
'''
class C { static set o(_) {} }
m() { C.o = 42; }
''',
const Visit(VisitKind.VISIT_STATIC_SETTER_SET,
- element: 'setter(C#o)',
- rhs: '42')),
+ element: 'setter(C#o)', rhs: '42')),
const Test.clazz(
'''
class C {
@@ -516,8 +475,7 @@
}
''',
const Visit(VisitKind.VISIT_STATIC_SETTER_SET,
- element: 'setter(C#o)',
- rhs: '42')),
+ element: 'setter(C#o)', rhs: '42')),
const Test.clazz(
'''
class C {
@@ -526,8 +484,7 @@
}
''',
const Visit(VisitKind.VISIT_STATIC_SETTER_SET,
- element: 'setter(C#o)',
- rhs: '42')),
+ element: 'setter(C#o)', rhs: '42')),
const Test.prefix(
'''
class C {
@@ -536,16 +493,14 @@
''',
'm() { p.C.o = 42; }',
const Visit(VisitKind.VISIT_STATIC_SETTER_SET,
- element: 'setter(C#o)',
- rhs: '42')),
+ element: 'setter(C#o)', rhs: '42')),
const Test(
'''
class C { static get o => null; }
m() => C.o(null, 42);
''',
const Visit(VisitKind.VISIT_STATIC_GETTER_INVOKE,
- element: 'getter(C#o)',
- arguments: '(null,42)')),
+ element: 'getter(C#o)', arguments: '(null,42)')),
const Test.clazz(
'''
class C {
@@ -554,8 +509,7 @@
}
''',
const Visit(VisitKind.VISIT_STATIC_GETTER_INVOKE,
- element: 'getter(C#o)',
- arguments: '(null,42)')),
+ element: 'getter(C#o)', arguments: '(null,42)')),
const Test.clazz(
'''
class C {
@@ -564,8 +518,7 @@
}
''',
const Visit(VisitKind.VISIT_STATIC_GETTER_INVOKE,
- element: 'getter(C#o)',
- arguments: '(null,42)')),
+ element: 'getter(C#o)', arguments: '(null,42)')),
const Test.prefix(
'''
class C {
@@ -574,16 +527,14 @@
''',
'm() { p.C.o(null, 42); }',
const Visit(VisitKind.VISIT_STATIC_GETTER_INVOKE,
- element: 'getter(C#o)',
- arguments: '(null,42)')),
+ element: 'getter(C#o)', arguments: '(null,42)')),
const Test(
'''
class C { static set o(_) {} }
m() => C.o(null, 42);
''',
const Visit(VisitKind.VISIT_STATIC_SETTER_INVOKE,
- element: 'setter(C#o)',
- arguments: '(null,42)')),
+ element: 'setter(C#o)', arguments: '(null,42)')),
const Test.clazz(
'''
class C {
@@ -592,8 +543,7 @@
}
''',
const Visit(VisitKind.VISIT_STATIC_SETTER_INVOKE,
- element: 'setter(C#o)',
- arguments: '(null,42)')),
+ element: 'setter(C#o)', arguments: '(null,42)')),
const Test.clazz(
'''
class C {
@@ -602,8 +552,7 @@
}
''',
const Visit(VisitKind.VISIT_STATIC_SETTER_INVOKE,
- element: 'setter(C#o)',
- arguments: '(null,42)')),
+ element: 'setter(C#o)', arguments: '(null,42)')),
const Test.prefix(
'''
class C {
@@ -612,8 +561,7 @@
''',
'm() { p.C.o(null, 42); }',
const Visit(VisitKind.VISIT_STATIC_SETTER_INVOKE,
- element: 'setter(C#o)',
- arguments: '(null,42)')),
+ element: 'setter(C#o)', arguments: '(null,42)')),
],
'Static functions': const [
// Static functions
@@ -623,7 +571,7 @@
m() => C.o;
''',
const Visit(VisitKind.VISIT_STATIC_FUNCTION_GET,
- element: 'function(C#o)')),
+ element: 'function(C#o)')),
const Test.clazz(
'''
class C {
@@ -632,7 +580,7 @@
}
''',
const Visit(VisitKind.VISIT_STATIC_FUNCTION_GET,
- element: 'function(C#o)')),
+ element: 'function(C#o)')),
const Test.clazz(
'''
class C {
@@ -641,7 +589,7 @@
}
''',
const Visit(VisitKind.VISIT_STATIC_FUNCTION_GET,
- element: 'function(C#o)')),
+ element: 'function(C#o)')),
const Test.prefix(
'''
class C { static o(a, b) {} }
@@ -650,15 +598,14 @@
m() => p.C.o;
''',
const Visit(VisitKind.VISIT_STATIC_FUNCTION_GET,
- element: 'function(C#o)')),
+ element: 'function(C#o)')),
const Test(
'''
class C { static o(a, b) {} }
m() { C.o = 42; }
''',
const Visit(VisitKind.VISIT_STATIC_FUNCTION_SET,
- element: 'function(C#o)',
- rhs: '42')),
+ element: 'function(C#o)', rhs: '42')),
const Test.clazz(
'''
class C {
@@ -667,8 +614,7 @@
}
''',
const Visit(VisitKind.VISIT_STATIC_FUNCTION_SET,
- element: 'function(C#o)',
- rhs: '42')),
+ element: 'function(C#o)', rhs: '42')),
const Test.clazz(
'''
class C {
@@ -677,8 +623,7 @@
}
''',
const Visit(VisitKind.VISIT_STATIC_FUNCTION_SET,
- element: 'function(C#o)',
- rhs: '42')),
+ element: 'function(C#o)', rhs: '42')),
const Test.prefix(
'''
class C { static o(a, b) {} }
@@ -687,16 +632,14 @@
m() { p.C.o = 42; }
''',
const Visit(VisitKind.VISIT_STATIC_FUNCTION_SET,
- element: 'function(C#o)',
- rhs: '42')),
+ element: 'function(C#o)', rhs: '42')),
const Test(
'''
class C { static o(a, b) {} }
m() => C.o(null, 42);
''',
const Visit(VisitKind.VISIT_STATIC_FUNCTION_INVOKE,
- element: 'function(C#o)',
- arguments: '(null,42)')),
+ element: 'function(C#o)', arguments: '(null,42)')),
const Test.clazz(
'''
class C {
@@ -705,8 +648,7 @@
}
''',
const Visit(VisitKind.VISIT_STATIC_FUNCTION_INVOKE,
- element: 'function(C#o)',
- arguments: '(null,42)')),
+ element: 'function(C#o)', arguments: '(null,42)')),
const Test.clazz(
'''
class C {
@@ -715,8 +657,7 @@
}
''',
const Visit(VisitKind.VISIT_STATIC_FUNCTION_INVOKE,
- element: 'function(C#o)',
- arguments: '(null,42)')),
+ element: 'function(C#o)', arguments: '(null,42)')),
const Test.prefix(
'''
class C {
@@ -725,16 +666,14 @@
''',
'm() { p.C.o(null, 42); }',
const Visit(VisitKind.VISIT_STATIC_FUNCTION_INVOKE,
- element: 'function(C#o)',
- arguments: '(null,42)')),
+ element: 'function(C#o)', arguments: '(null,42)')),
const Test(
'''
class C { static o(a, b) {} }
m() => C.o(null);
''',
const Visit(VisitKind.VISIT_STATIC_FUNCTION_INCOMPATIBLE_INVOKE,
- element: 'function(C#o)',
- arguments: '(null)')),
+ element: 'function(C#o)', arguments: '(null)')),
],
'Top level fields': const [
// Top level fields
@@ -743,42 +682,35 @@
var o;
m() => o;
''',
- const Visit(VisitKind.VISIT_TOP_LEVEL_FIELD_GET,
- element: 'field(o)')),
+ const Visit(VisitKind.VISIT_TOP_LEVEL_FIELD_GET, element: 'field(o)')),
const Test.prefix(
'''
var o;
''',
'm() => p.o;',
- const Visit(VisitKind.VISIT_TOP_LEVEL_FIELD_GET,
- element: 'field(o)')),
+ const Visit(VisitKind.VISIT_TOP_LEVEL_FIELD_GET, element: 'field(o)')),
const Test.prefix(
'''
var o;
''',
'm() => p.o;',
const [
- const Visit(VisitKind.PREVISIT_DEFERRED_ACCESS,
- element: 'prefix(p)'),
- const Visit(VisitKind.VISIT_TOP_LEVEL_FIELD_GET,
- element: 'field(o)'),
+ const Visit(VisitKind.PREVISIT_DEFERRED_ACCESS, element: 'prefix(p)'),
+ const Visit(VisitKind.VISIT_TOP_LEVEL_FIELD_GET, element: 'field(o)'),
],
isDeferred: true),
const Test.prefix(
'''
''',
'm() => p.o;',
- const Visit(VisitKind.VISIT_UNRESOLVED_GET,
- name: 'o')),
+ const Visit(VisitKind.VISIT_UNRESOLVED_GET, name: 'o')),
const Test.prefix(
'''
''',
'm() => p.o;',
const [
- const Visit(VisitKind.PREVISIT_DEFERRED_ACCESS,
- element: 'prefix(p)'),
- const Visit(VisitKind.VISIT_UNRESOLVED_GET,
- name: 'o'),
+ const Visit(VisitKind.PREVISIT_DEFERRED_ACCESS, element: 'prefix(p)'),
+ const Visit(VisitKind.VISIT_UNRESOLVED_GET, name: 'o'),
],
isDeferred: true),
const Test.prefix(
@@ -786,98 +718,85 @@
''',
'm() => p;',
const Visit(VisitKind.ERROR_INVALID_GET,
- error: MessageKind.PREFIX_AS_EXPRESSION)),
+ error: MessageKind.PREFIX_AS_EXPRESSION)),
const Test(
'''
var o;
m() { o = 42; }
''',
const Visit(VisitKind.VISIT_TOP_LEVEL_FIELD_SET,
- element: 'field(o)',
- rhs: '42')),
+ element: 'field(o)', rhs: '42')),
const Test.prefix(
'''
var o;
''',
'm() { p.o = 42; }',
const Visit(VisitKind.VISIT_TOP_LEVEL_FIELD_SET,
- element: 'field(o)',
- rhs: '42')),
+ element: 'field(o)', rhs: '42')),
const Test.prefix(
'''
''',
'm() { p = 42; }',
const Visit(VisitKind.ERROR_INVALID_SET,
- error: MessageKind.PREFIX_AS_EXPRESSION,
- rhs: '42')),
+ error: MessageKind.PREFIX_AS_EXPRESSION, rhs: '42')),
const Test(
'''
final o = 0;
m() { o = 42; }
''',
const Visit(VisitKind.VISIT_FINAL_TOP_LEVEL_FIELD_SET,
- element: 'field(o)',
- rhs: '42')),
+ element: 'field(o)', rhs: '42')),
const Test.prefix(
'''
final o = 0;
''',
'm() { p.o = 42; }',
const Visit(VisitKind.VISIT_FINAL_TOP_LEVEL_FIELD_SET,
- element: 'field(o)',
- rhs: '42')),
+ element: 'field(o)', rhs: '42')),
const Test(
'''
const o = 0;
m() { o = 42; }
''',
const Visit(VisitKind.VISIT_FINAL_TOP_LEVEL_FIELD_SET,
- element: 'field(o)',
- rhs: '42')),
+ element: 'field(o)', rhs: '42')),
const Test.prefix(
'''
const o = 0;
''',
'm() { p.o = 42; }',
const Visit(VisitKind.VISIT_FINAL_TOP_LEVEL_FIELD_SET,
- element: 'field(o)',
- rhs: '42')),
+ element: 'field(o)', rhs: '42')),
const Test(
'''
var o;
m() { o(null, 42); }
''',
const Visit(VisitKind.VISIT_TOP_LEVEL_FIELD_INVOKE,
- element: 'field(o)',
- arguments: '(null,42)')),
+ element: 'field(o)', arguments: '(null,42)')),
const Test.prefix(
'''
var o;
''',
'm() { p.o(null, 42); }',
const Visit(VisitKind.VISIT_TOP_LEVEL_FIELD_INVOKE,
- element: 'field(o)',
- arguments: '(null,42)')),
+ element: 'field(o)', arguments: '(null,42)')),
const Test.prefix(
'''
''',
'm() { p(null, 42); }',
const Visit(VisitKind.ERROR_INVALID_INVOKE,
- error: MessageKind.PREFIX_AS_EXPRESSION,
- arguments: '(null,42)')),
+ error: MessageKind.PREFIX_AS_EXPRESSION, arguments: '(null,42)')),
const Test(
'''
m() => o;
''',
- const Visit(VisitKind.VISIT_UNRESOLVED_GET,
- name: 'o')),
+ const Visit(VisitKind.VISIT_UNRESOLVED_GET, name: 'o')),
const Test(
'''
m() { o = 42; }
''',
- const Visit(VisitKind.VISIT_UNRESOLVED_SET,
- name: 'o',
- rhs: '42')),
+ const Visit(VisitKind.VISIT_UNRESOLVED_SET, name: 'o', rhs: '42')),
],
'Top level properties': const [
// Top level properties
@@ -887,7 +806,7 @@
m() => o;
''',
const Visit(VisitKind.VISIT_TOP_LEVEL_GETTER_GET,
- element: 'getter(o)')),
+ element: 'getter(o)')),
const Test.prefix(
'''
get o => null;
@@ -896,14 +815,14 @@
m() => p.o;
''',
const Visit(VisitKind.VISIT_TOP_LEVEL_GETTER_GET,
- element: 'getter(o)')),
+ element: 'getter(o)')),
const Test(
'''
set o(_) {}
m() => o;
''',
const Visit(VisitKind.VISIT_TOP_LEVEL_SETTER_GET,
- element: 'setter(o)')),
+ element: 'setter(o)')),
const Test.prefix(
'''
set o(_) {}
@@ -912,71 +831,63 @@
m() => p.o;
''',
const Visit(VisitKind.VISIT_TOP_LEVEL_SETTER_GET,
- element: 'setter(o)')),
+ element: 'setter(o)')),
const Test(
'''
get o => null;
m() { o = 42; }
''',
const Visit(VisitKind.VISIT_TOP_LEVEL_GETTER_SET,
- element: 'getter(o)',
- rhs: '42')),
+ element: 'getter(o)', rhs: '42')),
const Test.prefix(
'''
get o => null;
''',
'm() { p.o = 42; }',
const Visit(VisitKind.VISIT_TOP_LEVEL_GETTER_SET,
- element: 'getter(o)',
- rhs: '42')),
+ element: 'getter(o)', rhs: '42')),
const Test(
'''
set o(_) {}
m() { o = 42; }
''',
const Visit(VisitKind.VISIT_TOP_LEVEL_SETTER_SET,
- element: 'setter(o)',
- rhs: '42')),
+ element: 'setter(o)', rhs: '42')),
const Test.prefix(
'''
set o(_) {}
''',
'm() { p.o = 42; }',
const Visit(VisitKind.VISIT_TOP_LEVEL_SETTER_SET,
- element: 'setter(o)',
- rhs: '42')),
+ element: 'setter(o)', rhs: '42')),
const Test(
'''
get o => null;
m() => o(null, 42);
''',
const Visit(VisitKind.VISIT_TOP_LEVEL_GETTER_INVOKE,
- element: 'getter(o)',
- arguments: '(null,42)')),
+ element: 'getter(o)', arguments: '(null,42)')),
const Test.prefix(
'''
get o => null;
''',
'm() { p.o(null, 42); }',
const Visit(VisitKind.VISIT_TOP_LEVEL_GETTER_INVOKE,
- element: 'getter(o)',
- arguments: '(null,42)')),
+ element: 'getter(o)', arguments: '(null,42)')),
const Test(
'''
set o(_) {}
m() => o(null, 42);
''',
const Visit(VisitKind.VISIT_TOP_LEVEL_SETTER_INVOKE,
- element: 'setter(o)',
- arguments: '(null,42)')),
+ element: 'setter(o)', arguments: '(null,42)')),
const Test.prefix(
'''
set o(_) {}
''',
'm() { p.o(null, 42); }',
const Visit(VisitKind.VISIT_TOP_LEVEL_SETTER_INVOKE,
- element: 'setter(o)',
- arguments: '(null,42)')),
+ element: 'setter(o)', arguments: '(null,42)')),
],
'Top level functions': const [
// Top level functions
@@ -986,49 +897,43 @@
m() => o;
''',
const Visit(VisitKind.VISIT_TOP_LEVEL_FUNCTION_GET,
- element: 'function(o)')),
+ element: 'function(o)')),
const Test(
'''
o(a, b) {}
m() => o(null, 42);
''',
const Visit(VisitKind.VISIT_TOP_LEVEL_FUNCTION_INVOKE,
- element: 'function(o)',
- arguments: '(null,42)')),
+ element: 'function(o)', arguments: '(null,42)')),
const Test(
'''
o(a, b) {}
m() => o(null);
''',
const Visit(VisitKind.VISIT_TOP_LEVEL_FUNCTION_INCOMPATIBLE_INVOKE,
- element: 'function(o)',
- arguments: '(null)')),
+ element: 'function(o)', arguments: '(null)')),
const Test.prefix(
'''
o(a, b) {}
''',
'm() { p.o(null, 42); }',
const Visit(VisitKind.VISIT_TOP_LEVEL_FUNCTION_INVOKE,
- element: 'function(o)',
- arguments: '(null,42)')),
+ element: 'function(o)', arguments: '(null,42)')),
const Test(
'''
m() => o(null, 42);
''',
const Visit(VisitKind.VISIT_UNRESOLVED_INVOKE,
- name: 'o',
- arguments: '(null,42)')),
+ name: 'o', arguments: '(null,42)')),
const Test.prefix(
'''
o(a, b) {}
''',
'm() => p.o(null, 42);',
const [
- const Visit(VisitKind.PREVISIT_DEFERRED_ACCESS,
- element: 'prefix(p)'),
+ const Visit(VisitKind.PREVISIT_DEFERRED_ACCESS, element: 'prefix(p)'),
const Visit(VisitKind.VISIT_TOP_LEVEL_FUNCTION_INVOKE,
- element: 'function(o)',
- arguments: '(null,42)'),
+ element: 'function(o)', arguments: '(null,42)'),
],
isDeferred: true),
const Test.prefix(
@@ -1036,18 +941,15 @@
''',
'm() => p.o(null, 42);',
const Visit(VisitKind.VISIT_UNRESOLVED_INVOKE,
- name: 'o',
- arguments: '(null,42)')),
+ name: 'o', arguments: '(null,42)')),
const Test.prefix(
'''
''',
'm() => p.o(null, 42);',
const [
- const Visit(VisitKind.PREVISIT_DEFERRED_ACCESS,
- element: 'prefix(p)'),
+ const Visit(VisitKind.PREVISIT_DEFERRED_ACCESS, element: 'prefix(p)'),
const Visit(VisitKind.VISIT_UNRESOLVED_INVOKE,
- name: 'o',
- arguments: '(null,42)'),
+ name: 'o', arguments: '(null,42)'),
],
isDeferred: true),
const Test.prefix(
@@ -1055,53 +957,39 @@
''',
'm() => p(null, 42);',
const Visit(VisitKind.ERROR_INVALID_INVOKE,
- error: MessageKind.PREFIX_AS_EXPRESSION,
- arguments: '(null,42)')),
+ error: MessageKind.PREFIX_AS_EXPRESSION, arguments: '(null,42)')),
const Test(
'''
o(a, b) {}
m() { o = 42; }
''',
const Visit(VisitKind.VISIT_TOP_LEVEL_FUNCTION_SET,
- element: 'function(o)',
- rhs: '42')),
+ element: 'function(o)', rhs: '42')),
const Test.prefix(
'''
o(a, b) {}
''',
'm() { p.o = 42; }',
const Visit(VisitKind.VISIT_TOP_LEVEL_FUNCTION_SET,
- element: 'function(o)',
- rhs: '42')),
+ element: 'function(o)', rhs: '42')),
],
'Dynamic properties': const [
// Dynamic properties
- const Test('m(o) => o.foo;',
- const [
- const Visit(VisitKind.VISIT_DYNAMIC_PROPERTY_GET,
- receiver: 'o',
- name: 'foo'),
- const Visit(VisitKind.VISIT_PARAMETER_GET,
- element: 'parameter(m#o)'),
- ]),
- const Test('m(o) { o.foo = 42; }',
- const [
- const Visit(VisitKind.VISIT_DYNAMIC_PROPERTY_SET,
- receiver: 'o',
- name: 'foo',
- rhs: '42'),
- const Visit(VisitKind.VISIT_PARAMETER_GET,
- element: 'parameter(m#o)'),
- ]),
- const Test('m(o) { o.foo(null, 42); }',
- const [
- const Visit(VisitKind.VISIT_DYNAMIC_PROPERTY_INVOKE,
- receiver: 'o',
- name: 'foo',
- arguments: '(null,42)'),
- const Visit(VisitKind.VISIT_PARAMETER_GET,
- element: 'parameter(m#o)'),
- ]),
+ const Test('m(o) => o.foo;', const [
+ const Visit(VisitKind.VISIT_DYNAMIC_PROPERTY_GET,
+ receiver: 'o', name: 'foo'),
+ const Visit(VisitKind.VISIT_PARAMETER_GET, element: 'parameter(m#o)'),
+ ]),
+ const Test('m(o) { o.foo = 42; }', const [
+ const Visit(VisitKind.VISIT_DYNAMIC_PROPERTY_SET,
+ receiver: 'o', name: 'foo', rhs: '42'),
+ const Visit(VisitKind.VISIT_PARAMETER_GET, element: 'parameter(m#o)'),
+ ]),
+ const Test('m(o) { o.foo(null, 42); }', const [
+ const Visit(VisitKind.VISIT_DYNAMIC_PROPERTY_INVOKE,
+ receiver: 'o', name: 'foo', arguments: '(null,42)'),
+ const Visit(VisitKind.VISIT_PARAMETER_GET, element: 'parameter(m#o)'),
+ ]),
],
'This access': const [
// This access
@@ -1119,8 +1007,7 @@
m() { this(null, 42); }
}
''',
- const Visit(VisitKind.VISIT_THIS_INVOKE,
- arguments: '(null,42)')),
+ const Visit(VisitKind.VISIT_THIS_INVOKE, arguments: '(null,42)')),
const Test.clazz(
'''
class C {
@@ -1129,8 +1016,7 @@
}
''',
const Visit(VisitKind.ERROR_INVALID_INVOKE,
- error: MessageKind.NO_THIS_AVAILABLE,
- arguments: '(null,42)')),
+ error: MessageKind.NO_THIS_AVAILABLE, arguments: '(null,42)')),
],
'This properties': const [
// This properties
@@ -1141,8 +1027,7 @@
m() => foo;
}
''',
- const Visit(VisitKind.VISIT_THIS_PROPERTY_GET,
- name: 'foo')),
+ const Visit(VisitKind.VISIT_THIS_PROPERTY_GET, name: 'foo')),
const Test.clazz(
'''
class C {
@@ -1150,8 +1035,7 @@
m() => this.foo;
}
''',
- const Visit(VisitKind.VISIT_THIS_PROPERTY_GET,
- name: 'foo')),
+ const Visit(VisitKind.VISIT_THIS_PROPERTY_GET, name: 'foo')),
const Test.clazz(
'''
class C {
@@ -1159,8 +1043,7 @@
m() => foo;
}
''',
- const Visit(VisitKind.VISIT_THIS_PROPERTY_GET,
- name: 'foo')),
+ const Visit(VisitKind.VISIT_THIS_PROPERTY_GET, name: 'foo')),
const Test.clazz(
'''
class C {
@@ -1169,7 +1052,7 @@
}
''',
const Visit(VisitKind.ERROR_INVALID_GET,
- error: MessageKind.NO_THIS_AVAILABLE)),
+ error: MessageKind.NO_THIS_AVAILABLE)),
const Test.clazz(
'''
class C {
@@ -1177,8 +1060,7 @@
m() => this.foo;
}
''',
- const Visit(VisitKind.VISIT_THIS_PROPERTY_GET,
- name: 'foo')),
+ const Visit(VisitKind.VISIT_THIS_PROPERTY_GET, name: 'foo')),
const Test.clazz(
'''
class C {
@@ -1186,9 +1068,7 @@
m() { foo = 42; }
}
''',
- const Visit(VisitKind.VISIT_THIS_PROPERTY_SET,
- name: 'foo',
- rhs: '42')),
+ const Visit(VisitKind.VISIT_THIS_PROPERTY_SET, name: 'foo', rhs: '42')),
const Test.clazz(
'''
class C {
@@ -1196,9 +1076,7 @@
m() { this.foo = 42; }
}
''',
- const Visit(VisitKind.VISIT_THIS_PROPERTY_SET,
- name: 'foo',
- rhs: '42')),
+ const Visit(VisitKind.VISIT_THIS_PROPERTY_SET, name: 'foo', rhs: '42')),
const Test.clazz(
'''
class C {
@@ -1206,9 +1084,7 @@
m() { foo = 42; }
}
''',
- const Visit(VisitKind.VISIT_THIS_PROPERTY_SET,
- name: 'foo',
- rhs: '42')),
+ const Visit(VisitKind.VISIT_THIS_PROPERTY_SET, name: 'foo', rhs: '42')),
const Test.clazz(
'''
class C {
@@ -1216,9 +1092,7 @@
m() { this.foo = 42; }
}
''',
- const Visit(VisitKind.VISIT_THIS_PROPERTY_SET,
- name: 'foo',
- rhs: '42')),
+ const Visit(VisitKind.VISIT_THIS_PROPERTY_SET, name: 'foo', rhs: '42')),
const Test.clazz(
'''
class C {
@@ -1227,8 +1101,7 @@
}
''',
const Visit(VisitKind.VISIT_THIS_PROPERTY_INVOKE,
- name: 'foo',
- arguments: '(null,42)')),
+ name: 'foo', arguments: '(null,42)')),
const Test.clazz(
'''
class C {
@@ -1237,8 +1110,7 @@
}
''',
const Visit(VisitKind.VISIT_THIS_PROPERTY_INVOKE,
- name: 'foo',
- arguments: '(null,42)')),
+ name: 'foo', arguments: '(null,42)')),
const Test.clazz(
'''
class C {
@@ -1247,8 +1119,7 @@
}
''',
const Visit(VisitKind.ERROR_INVALID_INVOKE,
- error: MessageKind.NO_THIS_AVAILABLE,
- arguments: '(null,42)')),
+ error: MessageKind.NO_THIS_AVAILABLE, arguments: '(null,42)')),
],
'Super fields': const [
// Super fields
@@ -1261,8 +1132,7 @@
m() => super.o;
}
''',
- const Visit(VisitKind.VISIT_SUPER_FIELD_GET,
- element: 'field(B#o)')),
+ const Visit(VisitKind.VISIT_SUPER_FIELD_GET, element: 'field(B#o)')),
const Test.clazz(
'''
class B {
@@ -1273,8 +1143,7 @@
}
''',
const Visit(VisitKind.VISIT_SUPER_FIELD_SET,
- element: 'field(B#o)',
- rhs: '42')),
+ element: 'field(B#o)', rhs: '42')),
const Test.clazz(
'''
class B {
@@ -1285,8 +1154,7 @@
}
''',
const Visit(VisitKind.VISIT_FINAL_SUPER_FIELD_SET,
- element: 'field(B#o)',
- rhs: '42')),
+ element: 'field(B#o)', rhs: '42')),
const Test.clazz(
'''
class B {
@@ -1297,10 +1165,9 @@
}
''',
const Visit(VisitKind.VISIT_SUPER_FIELD_INVOKE,
- element: 'field(B#o)',
- arguments: '(null,42)')),
+ element: 'field(B#o)', arguments: '(null,42)')),
const Test.clazz(
- '''
+ '''
class B {
}
class C extends B {
@@ -1309,15 +1176,14 @@
''',
const Visit(VisitKind.VISIT_UNRESOLVED_SUPER_GET)),
const Test.clazz(
- '''
+ '''
class B {
}
class C extends B {
m() => super.o = 42;
}
''',
- const Visit(VisitKind.VISIT_UNRESOLVED_SUPER_SET,
- rhs: '42')),
+ const Visit(VisitKind.VISIT_UNRESOLVED_SUPER_SET, rhs: '42')),
],
'Super properties': const [
// Super properties
@@ -1330,8 +1196,7 @@
m() => super.o;
}
''',
- const Visit(VisitKind.VISIT_SUPER_GETTER_GET,
- element: 'getter(B#o)')),
+ const Visit(VisitKind.VISIT_SUPER_GETTER_GET, element: 'getter(B#o)')),
const Test.clazz(
'''
class B {
@@ -1341,8 +1206,7 @@
m() => super.o;
}
''',
- const Visit(VisitKind.VISIT_SUPER_SETTER_GET,
- element: 'setter(B#o)')),
+ const Visit(VisitKind.VISIT_SUPER_SETTER_GET, element: 'setter(B#o)')),
const Test.clazz(
'''
class B {
@@ -1353,8 +1217,7 @@
}
''',
const Visit(VisitKind.VISIT_SUPER_GETTER_SET,
- element: 'getter(B#o)',
- rhs: '42')),
+ element: 'getter(B#o)', rhs: '42')),
const Test.clazz(
'''
class B {
@@ -1365,8 +1228,7 @@
}
''',
const Visit(VisitKind.VISIT_SUPER_SETTER_SET,
- element: 'setter(B#o)',
- rhs: '42')),
+ element: 'setter(B#o)', rhs: '42')),
const Test.clazz(
'''
class B {
@@ -1377,8 +1239,7 @@
}
''',
const Visit(VisitKind.VISIT_SUPER_GETTER_INVOKE,
- element: 'getter(B#o)',
- arguments: '(null,42)')),
+ element: 'getter(B#o)', arguments: '(null,42)')),
const Test.clazz(
'''
class B {
@@ -1389,8 +1250,7 @@
}
''',
const Visit(VisitKind.VISIT_SUPER_SETTER_INVOKE,
- element: 'setter(B#o)',
- arguments: '(null,42)')),
+ element: 'setter(B#o)', arguments: '(null,42)')),
],
'Super methods': const [
// Super methods
@@ -1404,7 +1264,7 @@
}
''',
const Visit(VisitKind.VISIT_SUPER_METHOD_GET,
- element: 'function(B#o)')),
+ element: 'function(B#o)')),
const Test.clazz(
'''
class B {
@@ -1415,8 +1275,7 @@
}
''',
const Visit(VisitKind.VISIT_SUPER_METHOD_SET,
- element: 'function(B#o)',
- rhs: '42')),
+ element: 'function(B#o)', rhs: '42')),
const Test.clazz(
'''
class B {
@@ -1427,8 +1286,7 @@
}
''',
const Visit(VisitKind.VISIT_SUPER_METHOD_INVOKE,
- element: 'function(B#o)',
- arguments: '(null,42)')),
+ element: 'function(B#o)', arguments: '(null,42)')),
const Test.clazz(
'''
class B {
@@ -1439,10 +1297,9 @@
}
''',
const Visit(VisitKind.VISIT_SUPER_METHOD_INCOMPATIBLE_INVOKE,
- element: 'function(B#o)',
- arguments: '(null)')),
+ element: 'function(B#o)', arguments: '(null)')),
const Test.clazz(
- '''
+ '''
class B {
}
class C extends B {
@@ -1450,14 +1307,14 @@
}
''',
const Visit(VisitKind.VISIT_UNRESOLVED_SUPER_INVOKE,
- arguments: '(null,42)')),
+ arguments: '(null,42)')),
],
'Expression invoke': const [
// Expression invoke
- const Test('m() => (a, b){}(null, 42);',
+ const Test(
+ 'm() => (a, b){}(null, 42);',
const Visit(VisitKind.VISIT_EXPRESSION_INVOKE,
- receiver: '(a,b){}',
- arguments: '(null,42)')),
+ receiver: '(a,b){}', arguments: '(null,42)')),
],
'Class type literals': const [
// Class type literals
@@ -1466,57 +1323,49 @@
class C {}
m() => C;
''',
- const Visit(VisitKind.VISIT_CLASS_TYPE_LITERAL_GET,
- constant: 'C')),
+ const Visit(VisitKind.VISIT_CLASS_TYPE_LITERAL_GET, constant: 'C')),
const Test(
'''
class C {}
m() => C(null, 42);
''',
const Visit(VisitKind.VISIT_CLASS_TYPE_LITERAL_INVOKE,
- constant: 'C',
- arguments: '(null,42)')),
+ constant: 'C', arguments: '(null,42)')),
const Test(
'''
class C {}
m() => C = 42;
''',
const Visit(VisitKind.VISIT_CLASS_TYPE_LITERAL_SET,
- constant: 'C',
- rhs: '42')),
+ constant: 'C', rhs: '42')),
const Test(
'''
class C {}
m() => C += 42;
''',
const Visit(VisitKind.VISIT_CLASS_TYPE_LITERAL_COMPOUND,
- constant: 'C',
- operator: '+=',
- rhs: '42')),
+ constant: 'C', operator: '+=', rhs: '42')),
const Test(
'''
class C {}
m() => C ??= 42;
''',
const Visit(VisitKind.VISIT_CLASS_TYPE_LITERAL_SET_IF_NULL,
- constant: 'C',
- rhs: '42')),
+ constant: 'C', rhs: '42')),
const Test(
'''
class C {}
m() => ++C;
''',
const Visit(VisitKind.VISIT_CLASS_TYPE_LITERAL_PREFIX,
- constant: 'C',
- operator: '++')),
+ constant: 'C', operator: '++')),
const Test(
'''
class C {}
m() => C--;
''',
const Visit(VisitKind.VISIT_CLASS_TYPE_LITERAL_POSTFIX,
- constant: 'C',
- operator: '--')),
+ constant: 'C', operator: '--')),
const Test(
'''
class C {}
@@ -1524,9 +1373,8 @@
''',
const [
const Visit(VisitKind.VISIT_DYNAMIC_PROPERTY_GET,
- receiver: '(C)', name: 'hashCode'),
- const Visit(VisitKind.VISIT_CLASS_TYPE_LITERAL_GET,
- constant: 'C'),
+ receiver: '(C)', name: 'hashCode'),
+ const Visit(VisitKind.VISIT_CLASS_TYPE_LITERAL_GET, constant: 'C'),
]),
],
'Typedef type literals': const [
@@ -1536,57 +1384,49 @@
typedef F();
m() => F;
''',
- const Visit(VisitKind.VISIT_TYPEDEF_TYPE_LITERAL_GET,
- constant: 'F')),
+ const Visit(VisitKind.VISIT_TYPEDEF_TYPE_LITERAL_GET, constant: 'F')),
const Test(
'''
typedef F();
m() => F(null, 42);
''',
const Visit(VisitKind.VISIT_TYPEDEF_TYPE_LITERAL_INVOKE,
- constant: 'F',
- arguments: '(null,42)')),
+ constant: 'F', arguments: '(null,42)')),
const Test(
'''
typedef F();
m() => F = 42;
''',
const Visit(VisitKind.VISIT_TYPEDEF_TYPE_LITERAL_SET,
- constant: 'F',
- rhs: '42')),
+ constant: 'F', rhs: '42')),
const Test(
'''
typedef F();
m() => F += 42;
''',
const Visit(VisitKind.VISIT_TYPEDEF_TYPE_LITERAL_COMPOUND,
- constant: 'F',
- operator: '+=',
- rhs: '42')),
+ constant: 'F', operator: '+=', rhs: '42')),
const Test(
'''
typedef F();
m() => F ??= 42;
''',
const Visit(VisitKind.VISIT_TYPEDEF_TYPE_LITERAL_SET_IF_NULL,
- constant: 'F',
- rhs: '42')),
+ constant: 'F', rhs: '42')),
const Test(
'''
typedef F();
m() => ++F;
''',
const Visit(VisitKind.VISIT_TYPEDEF_TYPE_LITERAL_PREFIX,
- constant: 'F',
- operator: '++')),
+ constant: 'F', operator: '++')),
const Test(
'''
typedef F();
m() => F--;
''',
const Visit(VisitKind.VISIT_TYPEDEF_TYPE_LITERAL_POSTFIX,
- constant: 'F',
- operator: '--')),
+ constant: 'F', operator: '--')),
],
'Type variable type literals': const [
// Type variable type literals
@@ -1597,7 +1437,7 @@
}
''',
const Visit(VisitKind.VISIT_TYPE_VARIABLE_TYPE_LITERAL_GET,
- element: 'type_variable(C#T)')),
+ element: 'type_variable(C#T)')),
const Test.clazz(
'''
class C<T> {
@@ -1605,8 +1445,7 @@
}
''',
const Visit(VisitKind.VISIT_TYPE_VARIABLE_TYPE_LITERAL_INVOKE,
- element: 'type_variable(C#T)',
- arguments: '(null,42)')),
+ element: 'type_variable(C#T)', arguments: '(null,42)')),
const Test.clazz(
'''
class C<T> {
@@ -1614,8 +1453,7 @@
}
''',
const Visit(VisitKind.VISIT_TYPE_VARIABLE_TYPE_LITERAL_SET,
- element: 'type_variable(C#T)',
- rhs: '42')),
+ element: 'type_variable(C#T)', rhs: '42')),
const Test.clazz(
'''
class C<T> {
@@ -1623,9 +1461,7 @@
}
''',
const Visit(VisitKind.VISIT_TYPE_VARIABLE_TYPE_LITERAL_COMPOUND,
- element: 'type_variable(C#T)',
- operator: '+=',
- rhs: '42')),
+ element: 'type_variable(C#T)', operator: '+=', rhs: '42')),
const Test.clazz(
'''
class C<T> {
@@ -1633,8 +1469,7 @@
}
''',
const Visit(VisitKind.VISIT_TYPE_VARIABLE_TYPE_LITERAL_SET_IF_NULL,
- element: 'type_variable(C#T)',
- rhs: '42')),
+ element: 'type_variable(C#T)', rhs: '42')),
const Test.clazz(
'''
class C<T> {
@@ -1642,8 +1477,7 @@
}
''',
const Visit(VisitKind.VISIT_TYPE_VARIABLE_TYPE_LITERAL_PREFIX,
- element: 'type_variable(C#T)',
- operator: '++')),
+ element: 'type_variable(C#T)', operator: '++')),
const Test.clazz(
'''
class C<T> {
@@ -1651,8 +1485,7 @@
}
''',
const Visit(VisitKind.VISIT_TYPE_VARIABLE_TYPE_LITERAL_POSTFIX,
- element: 'type_variable(C#T)',
- operator: '--')),
+ element: 'type_variable(C#T)', operator: '--')),
const Test.clazz(
'''
class C<T> {
@@ -1660,7 +1493,7 @@
}
''',
const Visit(VisitKind.ERROR_INVALID_GET,
- error: MessageKind.TYPE_VARIABLE_WITHIN_STATIC_MEMBER)),
+ error: MessageKind.TYPE_VARIABLE_WITHIN_STATIC_MEMBER)),
const Test.clazz(
'''
class C<T> {
@@ -1668,8 +1501,8 @@
}
''',
const Visit(VisitKind.ERROR_INVALID_INVOKE,
- error: MessageKind.TYPE_VARIABLE_WITHIN_STATIC_MEMBER,
- arguments: '(null,42)')),
+ error: MessageKind.TYPE_VARIABLE_WITHIN_STATIC_MEMBER,
+ arguments: '(null,42)')),
const Test.clazz(
'''
class C<T> {
@@ -1677,8 +1510,7 @@
}
''',
const Visit(VisitKind.ERROR_INVALID_SET_IF_NULL,
- error: MessageKind.TYPE_VARIABLE_WITHIN_STATIC_MEMBER,
- rhs: '42')),
+ error: MessageKind.TYPE_VARIABLE_WITHIN_STATIC_MEMBER, rhs: '42')),
const Test.clazz(
'''
class C<T> {
@@ -1686,8 +1518,7 @@
}
''',
const Visit(VisitKind.ERROR_INVALID_SET_IF_NULL,
- error: MessageKind.TYPE_VARIABLE_WITHIN_STATIC_MEMBER,
- rhs: '42')),
+ error: MessageKind.TYPE_VARIABLE_WITHIN_STATIC_MEMBER, rhs: '42')),
const Test.clazz(
'''
class C<T> {
@@ -1695,8 +1526,8 @@
}
''',
const Visit(VisitKind.ERROR_INVALID_PREFIX,
- error: MessageKind.TYPE_VARIABLE_WITHIN_STATIC_MEMBER,
- operator: '++')),
+ error: MessageKind.TYPE_VARIABLE_WITHIN_STATIC_MEMBER,
+ operator: '++')),
const Test.clazz(
'''
class C<T> {
@@ -1704,8 +1535,8 @@
}
''',
const Visit(VisitKind.ERROR_INVALID_POSTFIX,
- error: MessageKind.TYPE_VARIABLE_WITHIN_STATIC_MEMBER,
- operator: '--')),
+ error: MessageKind.TYPE_VARIABLE_WITHIN_STATIC_MEMBER,
+ operator: '--')),
],
'Dynamic type literals': const [
// Dynamic type literals
@@ -1714,7 +1545,7 @@
m() => dynamic;
''',
const Visit(VisitKind.VISIT_DYNAMIC_TYPE_LITERAL_GET,
- constant: 'dynamic')),
+ constant: 'dynamic')),
// TODO(johnniwinther): Update these to expect the constant to be `dynamic`
// instead of `Type`. Currently the compile time constant evaluator cannot
// detect `dynamic` as a constant subexpression.
@@ -1723,44 +1554,37 @@
m() { dynamic(null, 42); }
''',
const Visit(VisitKind.VISIT_DYNAMIC_TYPE_LITERAL_INVOKE,
- constant: 'Type',
- arguments: '(null,42)')),
+ constant: 'Type', arguments: '(null,42)')),
const Test(
'''
m() => dynamic = 42;
''',
const Visit(VisitKind.VISIT_DYNAMIC_TYPE_LITERAL_SET,
- constant: 'dynamic',
- rhs: '42')),
+ constant: 'dynamic', rhs: '42')),
const Test(
'''
m() => dynamic += 42;
''',
const Visit(VisitKind.VISIT_DYNAMIC_TYPE_LITERAL_COMPOUND,
- constant: 'dynamic',
- operator: '+=',
- rhs: '42')),
+ constant: 'dynamic', operator: '+=', rhs: '42')),
const Test(
'''
m() => dynamic ??= 42;
''',
const Visit(VisitKind.VISIT_DYNAMIC_TYPE_LITERAL_SET_IF_NULL,
- constant: 'dynamic',
- rhs: '42')),
+ constant: 'dynamic', rhs: '42')),
const Test(
'''
m() => ++dynamic;
''',
const Visit(VisitKind.VISIT_DYNAMIC_TYPE_LITERAL_PREFIX,
- constant: 'dynamic',
- operator: '++')),
+ constant: 'dynamic', operator: '++')),
const Test(
'''
m() => dynamic--;
''',
const Visit(VisitKind.VISIT_DYNAMIC_TYPE_LITERAL_POSTFIX,
- constant: 'dynamic',
- operator: '--')),
+ constant: 'dynamic', operator: '--')),
],
'Assert': const [
// Assert
@@ -1769,8 +1593,7 @@
m() { assert(m()); }
''',
const Visit(VisitKind.VISIT_TOP_LEVEL_FUNCTION_INVOKE,
- element: 'function(m)',
- arguments: '()')),
+ element: 'function(m)', arguments: '()')),
],
'Logical and': const [
// Logical and
@@ -1822,91 +1645,91 @@
m() => 2 + 3;
''',
const Visit(VisitKind.VISIT_BINARY,
- left: '2', operator: '+', right: '3')),
+ left: '2', operator: '+', right: '3')),
const Test(
'''
m() => 2 - 3;
''',
const Visit(VisitKind.VISIT_BINARY,
- left: '2', operator: '-', right: '3')),
+ left: '2', operator: '-', right: '3')),
const Test(
'''
m() => 2 * 3;
''',
const Visit(VisitKind.VISIT_BINARY,
- left: '2', operator: '*', right: '3')),
+ left: '2', operator: '*', right: '3')),
const Test(
'''
m() => 2 / 3;
''',
const Visit(VisitKind.VISIT_BINARY,
- left: '2', operator: '/', right: '3')),
+ left: '2', operator: '/', right: '3')),
const Test(
'''
m() => 2 ~/ 3;
''',
const Visit(VisitKind.VISIT_BINARY,
- left: '2', operator: '~/', right: '3')),
+ left: '2', operator: '~/', right: '3')),
const Test(
'''
m() => 2 % 3;
''',
const Visit(VisitKind.VISIT_BINARY,
- left: '2', operator: '%', right: '3')),
+ left: '2', operator: '%', right: '3')),
const Test(
'''
m() => 2 << 3;
''',
const Visit(VisitKind.VISIT_BINARY,
- left: '2', operator: '<<', right: '3')),
+ left: '2', operator: '<<', right: '3')),
const Test(
'''
m() => 2 >> 3;
''',
const Visit(VisitKind.VISIT_BINARY,
- left: '2', operator: '>>', right: '3')),
+ left: '2', operator: '>>', right: '3')),
const Test(
'''
m() => 2 <= 3;
''',
const Visit(VisitKind.VISIT_BINARY,
- left: '2', operator: '<=', right: '3')),
+ left: '2', operator: '<=', right: '3')),
const Test(
'''
m() => 2 < 3;
''',
const Visit(VisitKind.VISIT_BINARY,
- left: '2', operator: '<', right: '3')),
+ left: '2', operator: '<', right: '3')),
const Test(
'''
m() => 2 >= 3;
''',
const Visit(VisitKind.VISIT_BINARY,
- left: '2', operator: '>=', right: '3')),
+ left: '2', operator: '>=', right: '3')),
const Test(
'''
m() => 2 > 3;
''',
const Visit(VisitKind.VISIT_BINARY,
- left: '2', operator: '>', right: '3')),
+ left: '2', operator: '>', right: '3')),
const Test(
'''
m() => 2 & 3;
''',
const Visit(VisitKind.VISIT_BINARY,
- left: '2', operator: '&', right: '3')),
+ left: '2', operator: '&', right: '3')),
const Test(
'''
m() => 2 | 3;
''',
const Visit(VisitKind.VISIT_BINARY,
- left: '2', operator: '|', right: '3')),
+ left: '2', operator: '|', right: '3')),
const Test(
'''
m() => 2 ^ 3;
''',
const Visit(VisitKind.VISIT_BINARY,
- left: '2', operator: '^', right: '3')),
+ left: '2', operator: '^', right: '3')),
const Test.clazz(
'''
class B {
@@ -1917,9 +1740,7 @@
}
''',
const Visit(VisitKind.VISIT_SUPER_BINARY,
- element: 'function(B#+)',
- operator: '+',
- right: '42')),
+ element: 'function(B#+)', operator: '+', right: '42')),
const Test.clazz(
'''
class B {}
@@ -1928,20 +1749,19 @@
}
''',
const Visit(VisitKind.VISIT_UNRESOLVED_SUPER_BINARY,
- operator: '+',
- right: '42')),
+ operator: '+', right: '42')),
const Test(
'''
m() => 2 === 3;
''',
const Visit(VisitKind.ERROR_UNDEFINED_BINARY_EXPRESSION,
- left: '2', operator: '===', right: '3')),
+ left: '2', operator: '===', right: '3')),
const Test(
'''
m() => 2 !== 3;
''',
const Visit(VisitKind.ERROR_UNDEFINED_BINARY_EXPRESSION,
- left: '2', operator: '!==', right: '3')),
+ left: '2', operator: '!==', right: '3')),
const Test.clazz(
'''
class B {
@@ -1952,9 +1772,7 @@
}
''',
const Visit(VisitKind.ERROR_INVALID_BINARY,
- error: MessageKind.NO_SUPER_IN_STATIC,
- operator: '+',
- right: '42')),
+ error: MessageKind.NO_SUPER_IN_STATIC, operator: '+', right: '42')),
],
'Index': const [
// Index
@@ -1962,20 +1780,19 @@
'''
m() => 2[3];
''',
- const Visit(VisitKind.VISIT_INDEX,
- receiver: '2', index: '3')),
+ const Visit(VisitKind.VISIT_INDEX, receiver: '2', index: '3')),
const Test(
'''
m() => --2[3];
''',
const Visit(VisitKind.VISIT_INDEX_PREFIX,
- receiver: '2', index: '3', operator: '--')),
+ receiver: '2', index: '3', operator: '--')),
const Test(
'''
m() => 2[3]++;
''',
const Visit(VisitKind.VISIT_INDEX_POSTFIX,
- receiver: '2', index: '3', operator: '++')),
+ receiver: '2', index: '3', operator: '++')),
const Test.clazz(
'''
class B {
@@ -1986,8 +1803,7 @@
}
''',
const Visit(VisitKind.VISIT_SUPER_INDEX,
- element: 'function(B#[])',
- index: '42')),
+ element: 'function(B#[])', index: '42')),
const Test.clazz(
'''
class B {
@@ -1996,8 +1812,7 @@
m() => super[42];
}
''',
- const Visit(VisitKind.VISIT_UNRESOLVED_SUPER_INDEX,
- index: '42')),
+ const Visit(VisitKind.VISIT_UNRESOLVED_SUPER_INDEX, index: '42')),
const Test.clazz(
'''
class B {
@@ -2008,8 +1823,7 @@
}
''',
const Visit(VisitKind.ERROR_INVALID_INDEX,
- error: MessageKind.NO_SUPER_IN_STATIC,
- index: '42')),
+ error: MessageKind.NO_SUPER_IN_STATIC, index: '42')),
const Test.clazz(
'''
class B {
@@ -2021,10 +1835,10 @@
}
''',
const Visit(VisitKind.VISIT_SUPER_INDEX_PREFIX,
- getter: 'function(B#[])',
- setter: 'function(B#[]=)',
- index: '42',
- operator: '++')),
+ getter: 'function(B#[])',
+ setter: 'function(B#[]=)',
+ index: '42',
+ operator: '++')),
const Test.clazz(
'''
class B {
@@ -2035,9 +1849,7 @@
}
''',
const Visit(VisitKind.VISIT_UNRESOLVED_SUPER_GETTER_INDEX_PREFIX,
- setter: 'function(B#[]=)',
- index: '42',
- operator: '++')),
+ setter: 'function(B#[]=)', index: '42', operator: '++')),
const Test.clazz(
'''
class B {
@@ -2047,8 +1859,7 @@
}
''',
const Visit(VisitKind.VISIT_UNRESOLVED_SUPER_INDEX_PREFIX,
- index: '42',
- operator: '++')),
+ index: '42', operator: '++')),
const Test.clazz(
'''
class B {
@@ -2059,9 +1870,7 @@
}
''',
const Visit(VisitKind.VISIT_UNRESOLVED_SUPER_SETTER_INDEX_PREFIX,
- getter: 'function(B#[])',
- index: '42',
- operator: '++')),
+ getter: 'function(B#[])', index: '42', operator: '++')),
const Test.clazz(
'''
class B {
@@ -2073,9 +1882,9 @@
}
''',
const Visit(VisitKind.ERROR_INVALID_INDEX_PREFIX,
- error: MessageKind.NO_SUPER_IN_STATIC,
- index: '42',
- operator: '++')),
+ error: MessageKind.NO_SUPER_IN_STATIC,
+ index: '42',
+ operator: '++')),
const Test.clazz(
'''
class B {
@@ -2087,10 +1896,10 @@
}
''',
const Visit(VisitKind.VISIT_SUPER_INDEX_POSTFIX,
- getter: 'function(B#[])',
- setter: 'function(B#[]=)',
- index: '42',
- operator: '--')),
+ getter: 'function(B#[])',
+ setter: 'function(B#[]=)',
+ index: '42',
+ operator: '--')),
const Test.clazz(
'''
class B {
@@ -2101,9 +1910,7 @@
}
''',
const Visit(VisitKind.VISIT_UNRESOLVED_SUPER_GETTER_INDEX_POSTFIX,
- setter: 'function(B#[]=)',
- index: '42',
- operator: '--')),
+ setter: 'function(B#[]=)', index: '42', operator: '--')),
const Test.clazz(
'''
class B {
@@ -2113,8 +1920,7 @@
}
''',
const Visit(VisitKind.VISIT_UNRESOLVED_SUPER_INDEX_POSTFIX,
- index: '42',
- operator: '--')),
+ index: '42', operator: '--')),
const Test.clazz(
'''
class B {
@@ -2125,9 +1931,7 @@
}
''',
const Visit(VisitKind.VISIT_UNRESOLVED_SUPER_SETTER_INDEX_POSTFIX,
- getter: 'function(B#[])',
- index: '42',
- operator: '--')),
+ getter: 'function(B#[])', index: '42', operator: '--')),
const Test.clazz(
'''
class B {
@@ -2139,17 +1943,15 @@
}
''',
const Visit(VisitKind.ERROR_INVALID_INDEX_POSTFIX,
- error: MessageKind.NO_SUPER_IN_STATIC,
- index: '42',
- operator: '--')),
+ error: MessageKind.NO_SUPER_IN_STATIC,
+ index: '42',
+ operator: '--')),
const Test(
'''
m() => [][42] ??= 0;
''',
const Visit(VisitKind.VISIT_INDEX_SET_IF_NULL,
- receiver: '[] ',
- index: '42',
- rhs: '0')),
+ receiver: '[] ', index: '42', rhs: '0')),
const Test.clazz(
'''
class B {
@@ -2161,10 +1963,10 @@
}
''',
const Visit(VisitKind.VISIT_SUPER_INDEX_SET_IF_NULL,
- getter: 'function(B#[])',
- setter: 'function(B#[]=)',
- index: '42',
- rhs: '0')),
+ getter: 'function(B#[])',
+ setter: 'function(B#[]=)',
+ index: '42',
+ rhs: '0')),
const Test.clazz(
'''
class B {
@@ -2175,9 +1977,7 @@
}
''',
const Visit(VisitKind.VISIT_UNRESOLVED_SUPER_GETTER_INDEX_SET_IF_NULL,
- setter: 'function(B#[]=)',
- index: '42',
- rhs: '0')),
+ setter: 'function(B#[]=)', index: '42', rhs: '0')),
const Test.clazz(
'''
class B {
@@ -2188,9 +1988,7 @@
}
''',
const Visit(VisitKind.VISIT_UNRESOLVED_SUPER_SETTER_INDEX_SET_IF_NULL,
- getter: 'function(B#[])',
- index: '42',
- rhs: '0')),
+ getter: 'function(B#[])', index: '42', rhs: '0')),
const Test.clazz(
'''
class B {
@@ -2200,8 +1998,7 @@
}
''',
const Visit(VisitKind.VISIT_UNRESOLVED_SUPER_INDEX_SET_IF_NULL,
- index: '42',
- rhs: '0')),
+ index: '42', rhs: '0')),
],
'Equals': const [
// Equals
@@ -2209,8 +2006,7 @@
'''
m() => 2 == 3;
''',
- const Visit(VisitKind.VISIT_EQUALS,
- left: '2', right: '3')),
+ const Visit(VisitKind.VISIT_EQUALS, left: '2', right: '3')),
const Test.clazz(
'''
class B {
@@ -2221,8 +2017,7 @@
}
''',
const Visit(VisitKind.VISIT_SUPER_EQUALS,
- element: 'function(B#==)',
- right: '42')),
+ element: 'function(B#==)', right: '42')),
const Test.clazz(
'''
class B {
@@ -2233,8 +2028,7 @@
}
''',
const Visit(VisitKind.ERROR_INVALID_EQUALS,
- error: MessageKind.NO_SUPER_IN_STATIC,
- right: '42')),
+ error: MessageKind.NO_SUPER_IN_STATIC, right: '42')),
],
'Not equals': const [
// Not equals
@@ -2242,8 +2036,7 @@
'''
m() => 2 != 3;
''',
- const Visit(VisitKind.VISIT_NOT_EQUALS,
- left: '2', right: '3')),
+ const Visit(VisitKind.VISIT_NOT_EQUALS, left: '2', right: '3')),
const Test.clazz(
'''
class B {
@@ -2254,8 +2047,7 @@
}
''',
const Visit(VisitKind.VISIT_SUPER_NOT_EQUALS,
- element: 'function(B#==)',
- right: '42')),
+ element: 'function(B#==)', right: '42')),
const Test.clazz(
'''
class B {
@@ -2266,8 +2058,7 @@
}
''',
const Visit(VisitKind.ERROR_INVALID_NOT_EQUALS,
- error: MessageKind.NO_SUPER_IN_STATIC,
- right: '42')),
+ error: MessageKind.NO_SUPER_IN_STATIC, right: '42')),
],
'Unary expression': const [
// Unary expression
@@ -2275,14 +2066,12 @@
'''
m() => -false;
''',
- const Visit(VisitKind.VISIT_UNARY,
- expression: 'false', operator: '-')),
+ const Visit(VisitKind.VISIT_UNARY, expression: 'false', operator: '-')),
const Test(
'''
m() => ~false;
''',
- const Visit(VisitKind.VISIT_UNARY,
- expression: 'false', operator: '~')),
+ const Visit(VisitKind.VISIT_UNARY, expression: 'false', operator: '~')),
const Test.clazz(
'''
class B {
@@ -2293,7 +2082,7 @@
}
''',
const Visit(VisitKind.VISIT_SUPER_UNARY,
- element: 'function(B#unary-)', operator: '-')),
+ element: 'function(B#unary-)', operator: '-')),
const Test.clazz(
'''
class B {
@@ -2302,8 +2091,7 @@
m() => -super;
}
''',
- const Visit(VisitKind.VISIT_UNRESOLVED_SUPER_UNARY,
- operator: '-')),
+ const Visit(VisitKind.VISIT_UNRESOLVED_SUPER_UNARY, operator: '-')),
const Test.clazz(
'''
class B {
@@ -2314,7 +2102,7 @@
}
''',
const Visit(VisitKind.VISIT_SUPER_UNARY,
- element: 'function(B#~)', operator: '~')),
+ element: 'function(B#~)', operator: '~')),
const Test.clazz(
'''
class B {
@@ -2325,8 +2113,7 @@
}
''',
const Visit(VisitKind.ERROR_INVALID_UNARY,
- error: MessageKind.NO_SUPER_IN_STATIC,
- operator: '-')),
+ error: MessageKind.NO_SUPER_IN_STATIC, operator: '-')),
const Test(
'''
m() => !0;
@@ -2391,8 +2178,7 @@
const [
const Visit(VisitKind.VISIT_DYNAMIC_PROPERTY_COMPOUND,
receiver: 'a', name: 'b', operator: '+=', rhs: '42'),
- const Visit(VisitKind.VISIT_PARAMETER_GET,
- element: 'parameter(m#a)')
+ const Visit(VisitKind.VISIT_PARAMETER_GET, element: 'parameter(m#a)')
]),
const Test(
'''
@@ -2447,8 +2233,10 @@
m() => a += 42;
''',
const Visit(VisitKind.VISIT_TOP_LEVEL_GETTER_SETTER_COMPOUND,
- getter: 'getter(a)', setter: 'setter(a)',
- operator: '+=', rhs: '42')),
+ getter: 'getter(a)',
+ setter: 'setter(a)',
+ operator: '+=',
+ rhs: '42')),
const Test(
'''
class C {
@@ -2495,9 +2283,9 @@
}
''',
const Visit(VisitKind.ERROR_INVALID_COMPOUND,
- error: MessageKind.NO_INSTANCE_AVAILABLE,
- operator: '+=',
- rhs: '42')),
+ error: MessageKind.NO_INSTANCE_AVAILABLE,
+ operator: '+=',
+ rhs: '42')),
const Test.prefix(
'''
''',
@@ -2505,9 +2293,9 @@
m() { p += 42; }
''',
const Visit(VisitKind.ERROR_INVALID_COMPOUND,
- error: MessageKind.PREFIX_AS_EXPRESSION,
- operator: '+=',
- rhs: '42')),
+ error: MessageKind.PREFIX_AS_EXPRESSION,
+ operator: '+=',
+ rhs: '42')),
const Test(
'''
class C {
@@ -2517,8 +2305,10 @@
m() => C.a += 42;
''',
const Visit(VisitKind.VISIT_STATIC_GETTER_SETTER_COMPOUND,
- getter: 'getter(C#a)', setter: 'setter(C#a)',
- operator: '+=', rhs: '42')),
+ getter: 'getter(C#a)',
+ setter: 'setter(C#a)',
+ operator: '+=',
+ rhs: '42')),
const Test.clazz(
'''
class C {
@@ -2528,8 +2318,10 @@
}
''',
const Visit(VisitKind.VISIT_STATIC_GETTER_SETTER_COMPOUND,
- getter: 'getter(C#a)', setter: 'setter(C#a)',
- operator: '+=', rhs: '42')),
+ getter: 'getter(C#a)',
+ setter: 'setter(C#a)',
+ operator: '+=',
+ rhs: '42')),
const Test.clazz(
'''
class C {
@@ -2539,8 +2331,10 @@
}
''',
const Visit(VisitKind.VISIT_STATIC_GETTER_SETTER_COMPOUND,
- getter: 'getter(C#a)', setter: 'setter(C#a)',
- operator: '+=', rhs: '42')),
+ getter: 'getter(C#a)',
+ setter: 'setter(C#a)',
+ operator: '+=',
+ rhs: '42')),
const Test.prefix(
'''
class C {
@@ -2552,8 +2346,10 @@
m() => p.C.a += 42;
''',
const Visit(VisitKind.VISIT_STATIC_GETTER_SETTER_COMPOUND,
- getter: 'getter(C#a)', setter: 'setter(C#a)',
- operator: '+=', rhs: '42')),
+ getter: 'getter(C#a)',
+ setter: 'setter(C#a)',
+ operator: '+=',
+ rhs: '42')),
// TODO(johnniwinther): Enable these when dart2js supports method and setter
// with the same name.
/*const Test(
@@ -2653,8 +2449,10 @@
}
''',
const Visit(VisitKind.VISIT_SUPER_GETTER_SETTER_COMPOUND,
- getter: 'getter(B#a)', setter: 'setter(B#a)',
- operator: '+=', rhs: '42')),
+ getter: 'getter(B#a)',
+ setter: 'setter(B#a)',
+ operator: '+=',
+ rhs: '42')),
const Test.clazz(
'''
class A {
@@ -2668,8 +2466,10 @@
}
''',
const Visit(VisitKind.VISIT_SUPER_GETTER_SETTER_COMPOUND,
- getter: 'getter(A#a)', setter: 'setter(B#a)',
- operator: '+=', rhs: '42')),
+ getter: 'getter(A#a)',
+ setter: 'setter(B#a)',
+ operator: '+=',
+ rhs: '42')),
const Test.clazz(
'''
class A {
@@ -2684,8 +2484,10 @@
}
''',
const Visit(VisitKind.VISIT_SUPER_GETTER_FIELD_COMPOUND,
- getter: 'getter(B#a)', setter: 'field(A#a)',
- operator: '+=', rhs: '42')),
+ getter: 'getter(B#a)',
+ setter: 'field(A#a)',
+ operator: '+=',
+ rhs: '42')),
const Test.clazz(
'''
class A {
@@ -2700,8 +2502,10 @@
}
''',
const Visit(VisitKind.VISIT_SUPER_FIELD_SETTER_COMPOUND,
- getter: 'field(A#a)', setter: 'setter(B#a)',
- operator: '+=', rhs: '42')),
+ getter: 'field(A#a)',
+ setter: 'setter(B#a)',
+ operator: '+=',
+ rhs: '42')),
const Test.clazz(
'''
class A {
@@ -2719,8 +2523,7 @@
// [VISIT_SUPER_FIELD_FIELD_COMPOUND] when dart2js supports shadow
// setters.
const Visit(VisitKind.VISIT_SUPER_FINAL_FIELD_COMPOUND,
- element: 'field(B#a)',
- operator: '+=', rhs: '42')),
+ element: 'field(B#a)', operator: '+=', rhs: '42')),
const Test.clazz(
'''
class B {
@@ -2731,8 +2534,7 @@
}
''',
const Visit(VisitKind.VISIT_SUPER_METHOD_COMPOUND,
- element: 'function(B#a)',
- operator: '+=', rhs: '42')),
+ element: 'function(B#a)', operator: '+=', rhs: '42')),
const Test.clazz(
'''
class B {
@@ -2864,8 +2666,11 @@
}
''',
const Visit(VisitKind.VISIT_SUPER_COMPOUND_INDEX_SET,
- getter: 'function(B#[])', setter: 'function(B#[]=)',
- index: '1', operator: '+=', rhs: '42')),
+ getter: 'function(B#[])',
+ setter: 'function(B#[]=)',
+ index: '1',
+ operator: '+=',
+ rhs: '42')),
const Test.clazz(
'''
class B {
@@ -2876,8 +2681,7 @@
}
''',
const Visit(VisitKind.VISIT_UNRESOLVED_SUPER_GETTER_COMPOUND_INDEX_SET,
- setter: 'function(B#[]=)',
- index: '1', operator: '+=', rhs: '42')),
+ setter: 'function(B#[]=)', index: '1', operator: '+=', rhs: '42')),
const Test.clazz(
'''
class B {
@@ -2898,8 +2702,7 @@
}
''',
const Visit(VisitKind.VISIT_UNRESOLVED_SUPER_SETTER_COMPOUND_INDEX_SET,
- getter: 'function(B#[])',
- index: '1', operator: '+=', rhs: '42')),
+ getter: 'function(B#[])', index: '1', operator: '+=', rhs: '42')),
const Test.clazz(
'''
class B {
@@ -2912,7 +2715,9 @@
''',
const Visit(VisitKind.ERROR_INVALID_COMPOUND_INDEX_SET,
error: MessageKind.NO_SUPER_IN_STATIC,
- index: '1', operator: '+=', rhs: '42')),
+ index: '1',
+ operator: '+=',
+ rhs: '42')),
],
'Prefix expression': const [
// Prefix expression
@@ -2923,8 +2728,7 @@
const [
const Visit(VisitKind.VISIT_DYNAMIC_PROPERTY_PREFIX,
receiver: 'a', name: 'b', operator: '--'),
- const Visit(VisitKind.VISIT_PARAMETER_GET,
- element: 'parameter(m#a)')
+ const Visit(VisitKind.VISIT_PARAMETER_GET, element: 'parameter(m#a)')
]),
const Test(
'''
@@ -2979,8 +2783,7 @@
m() => --a;
''',
const Visit(VisitKind.VISIT_TOP_LEVEL_GETTER_SETTER_PREFIX,
- getter: 'getter(a)', setter: 'setter(a)',
- operator: '--')),
+ getter: 'getter(a)', setter: 'setter(a)', operator: '--')),
const Test(
'''
class C {
@@ -3027,8 +2830,7 @@
}
''',
const Visit(VisitKind.ERROR_INVALID_PREFIX,
- error: MessageKind.NO_INSTANCE_AVAILABLE,
- operator: '++')),
+ error: MessageKind.NO_INSTANCE_AVAILABLE, operator: '++')),
const Test.prefix(
'''
''',
@@ -3036,8 +2838,7 @@
m() { ++p; }
''',
const Visit(VisitKind.ERROR_INVALID_PREFIX,
- error: MessageKind.PREFIX_AS_EXPRESSION,
- operator: '++')),
+ error: MessageKind.PREFIX_AS_EXPRESSION, operator: '++')),
const Test(
'''
class C {
@@ -3047,8 +2848,7 @@
m() => ++C.a;
''',
const Visit(VisitKind.VISIT_STATIC_GETTER_SETTER_PREFIX,
- getter: 'getter(C#a)', setter: 'setter(C#a)',
- operator: '++')),
+ getter: 'getter(C#a)', setter: 'setter(C#a)', operator: '++')),
const Test.clazz(
'''
class C {
@@ -3058,8 +2858,7 @@
}
''',
const Visit(VisitKind.VISIT_STATIC_GETTER_SETTER_PREFIX,
- getter: 'getter(C#a)', setter: 'setter(C#a)',
- operator: '--')),
+ getter: 'getter(C#a)', setter: 'setter(C#a)', operator: '--')),
const Test.clazz(
'''
class C {
@@ -3069,8 +2868,7 @@
}
''',
const Visit(VisitKind.VISIT_STATIC_GETTER_SETTER_PREFIX,
- getter: 'getter(C#a)', setter: 'setter(C#a)',
- operator: '--')),
+ getter: 'getter(C#a)', setter: 'setter(C#a)', operator: '--')),
const Test.prefix(
'''
class C {
@@ -3082,8 +2880,7 @@
m() => ++p.C.a;
''',
const Visit(VisitKind.VISIT_STATIC_GETTER_SETTER_PREFIX,
- getter: 'getter(C#a)', setter: 'setter(C#a)',
- operator: '++')),
+ getter: 'getter(C#a)', setter: 'setter(C#a)', operator: '++')),
const Test.clazz(
'''
class C {
@@ -3135,8 +2932,7 @@
}
''',
const Visit(VisitKind.VISIT_SUPER_GETTER_SETTER_PREFIX,
- getter: 'getter(B#a)', setter: 'setter(B#a)',
- operator: '--')),
+ getter: 'getter(B#a)', setter: 'setter(B#a)', operator: '--')),
const Test.clazz(
'''
class A {
@@ -3150,8 +2946,7 @@
}
''',
const Visit(VisitKind.VISIT_SUPER_GETTER_SETTER_PREFIX,
- getter: 'getter(A#a)', setter: 'setter(B#a)',
- operator: '++')),
+ getter: 'getter(A#a)', setter: 'setter(B#a)', operator: '++')),
const Test.clazz(
'''
class A {
@@ -3166,8 +2961,7 @@
}
''',
const Visit(VisitKind.VISIT_SUPER_GETTER_FIELD_PREFIX,
- getter: 'getter(B#a)', setter: 'field(A#a)',
- operator: '--')),
+ getter: 'getter(B#a)', setter: 'field(A#a)', operator: '--')),
const Test.clazz(
'''
class A {
@@ -3182,8 +2976,7 @@
}
''',
const Visit(VisitKind.VISIT_SUPER_FIELD_SETTER_PREFIX,
- getter: 'field(A#a)', setter: 'setter(B#a)',
- operator: '++')),
+ getter: 'field(A#a)', setter: 'setter(B#a)', operator: '++')),
const Test.clazz(
'''
class B {
@@ -3194,8 +2987,7 @@
}
''',
const Visit(VisitKind.VISIT_SUPER_METHOD_PREFIX,
- element: 'function(B#a)',
- operator: '++')),
+ element: 'function(B#a)', operator: '++')),
const Test.clazz(
'''
class B {
@@ -3204,8 +2996,7 @@
m() => ++super.a;
}
''',
- const Visit(VisitKind.VISIT_UNRESOLVED_SUPER_PREFIX,
- operator: '++')),
+ const Visit(VisitKind.VISIT_UNRESOLVED_SUPER_PREFIX, operator: '++')),
const Test.clazz(
'''
class B {
@@ -3305,8 +3096,7 @@
'''
m() => ++unresolved;
''',
- const Visit(VisitKind.VISIT_UNRESOLVED_PREFIX,
- operator: '++')),
+ const Visit(VisitKind.VISIT_UNRESOLVED_PREFIX, operator: '++')),
],
'Postfix expression': const [
// Postfix expression
@@ -3317,8 +3107,7 @@
const [
const Visit(VisitKind.VISIT_DYNAMIC_PROPERTY_POSTFIX,
receiver: 'a', name: 'b', operator: '--'),
- const Visit(VisitKind.VISIT_PARAMETER_GET,
- element: 'parameter(m#a)')
+ const Visit(VisitKind.VISIT_PARAMETER_GET, element: 'parameter(m#a)')
]),
const Test(
'''
@@ -3373,8 +3162,7 @@
m() => a--;
''',
const Visit(VisitKind.VISIT_TOP_LEVEL_GETTER_SETTER_POSTFIX,
- getter: 'getter(a)', setter: 'setter(a)',
- operator: '--')),
+ getter: 'getter(a)', setter: 'setter(a)', operator: '--')),
const Test(
'''
class C {
@@ -3421,8 +3209,7 @@
}
''',
const Visit(VisitKind.ERROR_INVALID_POSTFIX,
- error: MessageKind.NO_INSTANCE_AVAILABLE,
- operator: '--')),
+ error: MessageKind.NO_INSTANCE_AVAILABLE, operator: '--')),
const Test.prefix(
'''
''',
@@ -3430,8 +3217,7 @@
m() { p--; }
''',
const Visit(VisitKind.ERROR_INVALID_POSTFIX,
- error: MessageKind.PREFIX_AS_EXPRESSION,
- operator: '--')),
+ error: MessageKind.PREFIX_AS_EXPRESSION, operator: '--')),
const Test(
'''
class C {
@@ -3441,8 +3227,7 @@
m() => C.a++;
''',
const Visit(VisitKind.VISIT_STATIC_GETTER_SETTER_POSTFIX,
- getter: 'getter(C#a)', setter: 'setter(C#a)',
- operator: '++')),
+ getter: 'getter(C#a)', setter: 'setter(C#a)', operator: '++')),
const Test.clazz(
'''
class C {
@@ -3452,8 +3237,7 @@
}
''',
const Visit(VisitKind.VISIT_STATIC_GETTER_SETTER_POSTFIX,
- getter: 'getter(C#a)', setter: 'setter(C#a)',
- operator: '--')),
+ getter: 'getter(C#a)', setter: 'setter(C#a)', operator: '--')),
const Test.clazz(
'''
class C {
@@ -3463,8 +3247,7 @@
}
''',
const Visit(VisitKind.VISIT_STATIC_GETTER_SETTER_POSTFIX,
- getter: 'getter(C#a)', setter: 'setter(C#a)',
- operator: '--')),
+ getter: 'getter(C#a)', setter: 'setter(C#a)', operator: '--')),
const Test.prefix(
'''
class C {
@@ -3476,8 +3259,7 @@
m() => p.C.a++;
''',
const Visit(VisitKind.VISIT_STATIC_GETTER_SETTER_POSTFIX,
- getter: 'getter(C#a)', setter: 'setter(C#a)',
- operator: '++')),
+ getter: 'getter(C#a)', setter: 'setter(C#a)', operator: '++')),
const Test.clazz(
'''
class C {
@@ -3529,8 +3311,7 @@
}
''',
const Visit(VisitKind.VISIT_SUPER_GETTER_SETTER_POSTFIX,
- getter: 'getter(B#a)', setter: 'setter(B#a)',
- operator: '--')),
+ getter: 'getter(B#a)', setter: 'setter(B#a)', operator: '--')),
const Test.clazz(
'''
class A {
@@ -3544,8 +3325,7 @@
}
''',
const Visit(VisitKind.VISIT_SUPER_GETTER_SETTER_POSTFIX,
- getter: 'getter(A#a)', setter: 'setter(B#a)',
- operator: '++')),
+ getter: 'getter(A#a)', setter: 'setter(B#a)', operator: '++')),
const Test.clazz(
'''
class A {
@@ -3560,8 +3340,7 @@
}
''',
const Visit(VisitKind.VISIT_SUPER_GETTER_FIELD_POSTFIX,
- getter: 'getter(B#a)', setter: 'field(A#a)',
- operator: '--')),
+ getter: 'getter(B#a)', setter: 'field(A#a)', operator: '--')),
const Test.clazz(
'''
class A {
@@ -3576,8 +3355,7 @@
}
''',
const Visit(VisitKind.VISIT_SUPER_FIELD_SETTER_POSTFIX,
- getter: 'field(A#a)', setter: 'setter(B#a)',
- operator: '++')),
+ getter: 'field(A#a)', setter: 'setter(B#a)', operator: '++')),
const Test.clazz(
'''
class B {
@@ -3588,8 +3366,7 @@
}
''',
const Visit(VisitKind.VISIT_SUPER_METHOD_POSTFIX,
- element: 'function(B#a)',
- operator: '++')),
+ element: 'function(B#a)', operator: '++')),
const Test.clazz(
'''
class B {
@@ -3598,8 +3375,7 @@
m() => super.a++;
}
''',
- const Visit(VisitKind.VISIT_UNRESOLVED_SUPER_POSTFIX,
- operator: '++')),
+ const Visit(VisitKind.VISIT_UNRESOLVED_SUPER_POSTFIX, operator: '++')),
const Test.clazz(
'''
class B {
@@ -3699,8 +3475,7 @@
'''
m() => unresolved++;
''',
- const Visit(VisitKind.VISIT_UNRESOLVED_POSTFIX,
- operator: '++')),
+ const Visit(VisitKind.VISIT_UNRESOLVED_POSTFIX, operator: '++')),
],
'Constructor invocations': const [
const Test(
@@ -3717,8 +3492,7 @@
m() => const bool.fromEnvironment('foo');
''',
const Visit(VisitKind.VISIT_BOOL_FROM_ENVIRONMENT_CONSTRUCTOR_INVOKE,
- constant:
- 'const bool.fromEnvironment("foo")')),
+ constant: 'const bool.fromEnvironment("foo")')),
const Test(
'''
m() => const bool.fromEnvironment('foo', defaultValue: true);
@@ -3736,8 +3510,7 @@
m() => const String.fromEnvironment('foo');
''',
const Visit(VisitKind.VISIT_STRING_FROM_ENVIRONMENT_CONSTRUCTOR_INVOKE,
- constant:
- 'const String.fromEnvironment("foo")')),
+ constant: 'const String.fromEnvironment("foo")')),
const Test(
'''
class Class {
@@ -3914,23 +3687,20 @@
}
m() => new Class.unresolved(true, 42);
''',
- const Visit(
- VisitKind.VISIT_UNRESOLVED_CONSTRUCTOR_INVOKE,
+ const Visit(VisitKind.VISIT_UNRESOLVED_CONSTRUCTOR_INVOKE,
arguments: '(true,42)')),
const Test(
'''
m() => new Unresolved(true, 42);
''',
- const Visit(
- VisitKind.VISIT_UNRESOLVED_CLASS_CONSTRUCTOR_INVOKE,
+ const Visit(VisitKind.VISIT_UNRESOLVED_CLASS_CONSTRUCTOR_INVOKE,
arguments: '(true,42)')),
const Test(
'''
abstract class AbstractClass {}
m() => new AbstractClass();
''',
- const Visit(
- VisitKind.VISIT_ABSTRACT_CLASS_CONSTRUCTOR_INVOKE,
+ const Visit(VisitKind.VISIT_ABSTRACT_CLASS_CONSTRUCTOR_INVOKE,
element: 'generative_constructor(AbstractClass#)',
type: 'AbstractClass',
arguments: '()',
@@ -3998,13 +3768,9 @@
m(a) => a?.b;
''',
const [
- const Visit(
- VisitKind.VISIT_IF_NOT_NULL_DYNAMIC_PROPERTY_GET,
- receiver: 'a',
- name: 'b'),
- const Visit(
- VisitKind.VISIT_PARAMETER_GET,
- element: 'parameter(m#a)'),
+ const Visit(VisitKind.VISIT_IF_NOT_NULL_DYNAMIC_PROPERTY_GET,
+ receiver: 'a', name: 'b'),
+ const Visit(VisitKind.VISIT_PARAMETER_GET, element: 'parameter(m#a)'),
]),
const Test(
'''
@@ -4013,107 +3779,78 @@
}
m(a) => C?.b;
''',
- const Visit(
- VisitKind.VISIT_STATIC_FIELD_GET,
- element: 'field(C#b)')),
+ const Visit(VisitKind.VISIT_STATIC_FIELD_GET, element: 'field(C#b)')),
const Test(
'''
m(a) => a?.b = 42;
''',
const [
- const Visit(
- VisitKind.VISIT_IF_NOT_NULL_DYNAMIC_PROPERTY_SET,
- receiver: 'a',
- name: 'b',
- rhs: '42'),
- const Visit(
- VisitKind.VISIT_PARAMETER_GET,
- element: 'parameter(m#a)'),
+ const Visit(VisitKind.VISIT_IF_NOT_NULL_DYNAMIC_PROPERTY_SET,
+ receiver: 'a', name: 'b', rhs: '42'),
+ const Visit(VisitKind.VISIT_PARAMETER_GET, element: 'parameter(m#a)'),
]),
const Test(
'''
m(a) => a?.b(42, true);
''',
const [
- const Visit(
- VisitKind.VISIT_IF_NOT_NULL_DYNAMIC_PROPERTY_INVOKE,
+ const Visit(VisitKind.VISIT_IF_NOT_NULL_DYNAMIC_PROPERTY_INVOKE,
receiver: 'a',
arguments: '(42,true)',
selector: 'Selector(call, b, arity=2)'),
- const Visit(
- VisitKind.VISIT_PARAMETER_GET,
- element: 'parameter(m#a)'),
+ const Visit(VisitKind.VISIT_PARAMETER_GET, element: 'parameter(m#a)'),
]),
const Test(
'''
m(a) => ++a?.b;
''',
const [
- const Visit(
- VisitKind.VISIT_IF_NOT_NULL_DYNAMIC_PROPERTY_PREFIX,
+ const Visit(VisitKind.VISIT_IF_NOT_NULL_DYNAMIC_PROPERTY_PREFIX,
receiver: 'a', name: 'b', operator: '++'),
- const Visit(
- VisitKind.VISIT_PARAMETER_GET,
- element: 'parameter(m#a)'),
+ const Visit(VisitKind.VISIT_PARAMETER_GET, element: 'parameter(m#a)'),
]),
const Test(
'''
m(a) => a?.b--;
''',
const [
- const Visit(
- VisitKind.VISIT_IF_NOT_NULL_DYNAMIC_PROPERTY_POSTFIX,
+ const Visit(VisitKind.VISIT_IF_NOT_NULL_DYNAMIC_PROPERTY_POSTFIX,
receiver: 'a', name: 'b', operator: '--'),
- const Visit(
- VisitKind.VISIT_PARAMETER_GET,
- element: 'parameter(m#a)'),
+ const Visit(VisitKind.VISIT_PARAMETER_GET, element: 'parameter(m#a)'),
]),
const Test(
'''
m(a) => a?.b *= 42;
''',
const [
- const Visit(
- VisitKind.VISIT_IF_NOT_NULL_DYNAMIC_PROPERTY_COMPOUND,
+ const Visit(VisitKind.VISIT_IF_NOT_NULL_DYNAMIC_PROPERTY_COMPOUND,
receiver: 'a', name: 'b', operator: '*=', rhs: '42'),
- const Visit(
- VisitKind.VISIT_PARAMETER_GET,
- element: 'parameter(m#a)'),
+ const Visit(VisitKind.VISIT_PARAMETER_GET, element: 'parameter(m#a)'),
]),
const Test(
'''
m(a) => a?.b ??= 42;
''',
const [
- const Visit(
- VisitKind.VISIT_IF_NOT_NULL_DYNAMIC_PROPERTY_SET_IF_NULL,
+ const Visit(VisitKind.VISIT_IF_NOT_NULL_DYNAMIC_PROPERTY_SET_IF_NULL,
receiver: 'a', name: 'b', rhs: '42'),
- const Visit(
- VisitKind.VISIT_PARAMETER_GET,
- element: 'parameter(m#a)'),
+ const Visit(VisitKind.VISIT_PARAMETER_GET, element: 'parameter(m#a)'),
]),
const Test(
'''
m(a, b) => a ?? b;
''',
const [
- const Visit(VisitKind.VISIT_IF_NULL,
- left: 'a', right: 'b'),
- const Visit(
- VisitKind.VISIT_PARAMETER_GET,
- element: 'parameter(m#a)'),
- const Visit(
- VisitKind.VISIT_PARAMETER_GET,
- element: 'parameter(m#b)'),
- ]),
+ const Visit(VisitKind.VISIT_IF_NULL, left: 'a', right: 'b'),
+ const Visit(VisitKind.VISIT_PARAMETER_GET, element: 'parameter(m#a)'),
+ const Visit(VisitKind.VISIT_PARAMETER_GET, element: 'parameter(m#b)'),
+ ]),
const Test(
'''
m(a) => a ??= 42;
''',
- const Visit(
- VisitKind.VISIT_PARAMETER_SET_IF_NULL,
- element: 'parameter(m#a)',
- rhs: '42')),
+ const Visit(VisitKind.VISIT_PARAMETER_SET_IF_NULL,
+ element: 'parameter(m#a)', rhs: '42')),
const Test.prefix(
'''
var o;
@@ -4130,8 +3867,7 @@
const [
const Visit(VisitKind.VISIT_DYNAMIC_PROPERTY_SET_IF_NULL,
receiver: 'a', name: 'b', rhs: '42'),
- const Visit(VisitKind.VISIT_PARAMETER_GET,
- element: 'parameter(m#a)')
+ const Visit(VisitKind.VISIT_PARAMETER_GET, element: 'parameter(m#a)')
]),
const Test(
'''
@@ -4186,8 +3922,7 @@
m() => a ??= 42;
''',
const Visit(VisitKind.VISIT_TOP_LEVEL_GETTER_SETTER_SET_IF_NULL,
- getter: 'getter(a)', setter: 'setter(a)',
- rhs: '42')),
+ getter: 'getter(a)', setter: 'setter(a)', rhs: '42')),
const Test(
'''
class C {
@@ -4234,8 +3969,7 @@
}
''',
const Visit(VisitKind.ERROR_INVALID_SET_IF_NULL,
- error: MessageKind.NO_INSTANCE_AVAILABLE,
- rhs: '42')),
+ error: MessageKind.NO_INSTANCE_AVAILABLE, rhs: '42')),
const Test.prefix(
'''
''',
@@ -4243,8 +3977,7 @@
m() { p ??= 42; }
''',
const Visit(VisitKind.ERROR_INVALID_SET_IF_NULL,
- error: MessageKind.PREFIX_AS_EXPRESSION,
- rhs: '42')),
+ error: MessageKind.PREFIX_AS_EXPRESSION, rhs: '42')),
const Test(
'''
class C {
@@ -4254,8 +3987,7 @@
m() => C.a ??= 42;
''',
const Visit(VisitKind.VISIT_STATIC_GETTER_SETTER_SET_IF_NULL,
- getter: 'getter(C#a)', setter: 'setter(C#a)',
- rhs: '42')),
+ getter: 'getter(C#a)', setter: 'setter(C#a)', rhs: '42')),
const Test.clazz(
'''
class C {
@@ -4265,8 +3997,7 @@
}
''',
const Visit(VisitKind.VISIT_STATIC_GETTER_SETTER_SET_IF_NULL,
- getter: 'getter(C#a)', setter: 'setter(C#a)',
- rhs: '42')),
+ getter: 'getter(C#a)', setter: 'setter(C#a)', rhs: '42')),
const Test.clazz(
'''
class C {
@@ -4276,8 +4007,7 @@
}
''',
const Visit(VisitKind.VISIT_STATIC_GETTER_SETTER_SET_IF_NULL,
- getter: 'getter(C#a)', setter: 'setter(C#a)',
- rhs: '42')),
+ getter: 'getter(C#a)', setter: 'setter(C#a)', rhs: '42')),
const Test.prefix(
'''
class C {
@@ -4289,8 +4019,7 @@
m() => p.C.a ??= 42;
''',
const Visit(VisitKind.VISIT_STATIC_GETTER_SETTER_SET_IF_NULL,
- getter: 'getter(C#a)', setter: 'setter(C#a)',
- rhs: '42')),
+ getter: 'getter(C#a)', setter: 'setter(C#a)', rhs: '42')),
// TODO(johnniwinther): Enable these when dart2js supports method and setter
// with the same name.
/*const Test(
@@ -4390,8 +4119,7 @@
}
''',
const Visit(VisitKind.VISIT_SUPER_GETTER_SETTER_SET_IF_NULL,
- getter: 'getter(B#a)', setter: 'setter(B#a)',
- rhs: '42')),
+ getter: 'getter(B#a)', setter: 'setter(B#a)', rhs: '42')),
const Test.clazz(
'''
class A {
@@ -4405,8 +4133,7 @@
}
''',
const Visit(VisitKind.VISIT_SUPER_GETTER_SETTER_SET_IF_NULL,
- getter: 'getter(A#a)', setter: 'setter(B#a)',
- rhs: '42')),
+ getter: 'getter(A#a)', setter: 'setter(B#a)', rhs: '42')),
const Test.clazz(
'''
class A {
@@ -4421,8 +4148,7 @@
}
''',
const Visit(VisitKind.VISIT_SUPER_GETTER_FIELD_SET_IF_NULL,
- getter: 'getter(B#a)', setter: 'field(A#a)',
- rhs: '42')),
+ getter: 'getter(B#a)', setter: 'field(A#a)', rhs: '42')),
const Test.clazz(
'''
class A {
@@ -4437,8 +4163,7 @@
}
''',
const Visit(VisitKind.VISIT_SUPER_FIELD_SETTER_SET_IF_NULL,
- getter: 'field(A#a)', setter: 'setter(B#a)',
- rhs: '42')),
+ getter: 'field(A#a)', setter: 'setter(B#a)', rhs: '42')),
const Test.clazz(
'''
class A {
@@ -4456,8 +4181,7 @@
// [VISIT_SUPER_FIELD_FIELD_SET_IF_NULL] when dart2js supports shadow
// setters.
const Visit(VisitKind.VISIT_SUPER_FINAL_FIELD_SET_IF_NULL,
- element: 'field(B#a)',
- rhs: '42')),
+ element: 'field(B#a)', rhs: '42')),
const Test.clazz(
'''
class B {
@@ -4468,8 +4192,7 @@
}
''',
const Visit(VisitKind.VISIT_SUPER_METHOD_SET_IF_NULL,
- element: 'function(B#a)',
- rhs: '42')),
+ element: 'function(B#a)', rhs: '42')),
const Test.clazz(
'''
class B {
diff --git a/tests/compiler/dart2js/semantic_visitor_test_send_visitor.dart b/tests/compiler/dart2js/semantic_visitor_test_send_visitor.dart
index 9ded3ea..c16454e 100644
--- a/tests/compiler/dart2js/semantic_visitor_test_send_visitor.dart
+++ b/tests/compiler/dart2js/semantic_visitor_test_send_visitor.dart
@@ -5,49 +5,33 @@
part of dart2js.semantics_visitor_test;
class SemanticSendTestVisitor extends SemanticTestVisitor {
-
SemanticSendTestVisitor(TreeElements elements) : super(elements);
@override
- visitAs(
- Send node,
- Node expression,
- DartType type,
- arg) {
- visits.add(new Visit(VisitKind.VISIT_AS,
- expression: expression, type: type));
+ visitAs(Send node, Node expression, DartType type, arg) {
+ visits
+ .add(new Visit(VisitKind.VISIT_AS, expression: expression, type: type));
apply(expression, arg);
}
@override
- errorInvalidCompound(
- Send node,
- ErroneousElement error,
- AssignmentOperator operator,
- Node rhs,
- arg) {
+ errorInvalidCompound(Send node, ErroneousElement error,
+ AssignmentOperator operator, Node rhs, arg) {
visits.add(new Visit(VisitKind.ERROR_INVALID_COMPOUND,
error: error.messageKind, operator: operator, rhs: rhs));
super.errorInvalidCompound(node, error, operator, rhs, arg);
}
@override
- errorInvalidGet(
- Send node,
- ErroneousElement error,
- arg) {
- visits.add(new Visit(VisitKind.ERROR_INVALID_GET,
- error: error.messageKind));
+ errorInvalidGet(Send node, ErroneousElement error, arg) {
+ visits
+ .add(new Visit(VisitKind.ERROR_INVALID_GET, error: error.messageKind));
super.errorInvalidGet(node, error, arg);
}
@override
- errorInvalidInvoke(
- Send node,
- ErroneousElement error,
- NodeList arguments,
- Selector selector,
- arg) {
+ errorInvalidInvoke(Send node, ErroneousElement error, NodeList arguments,
+ Selector selector, arg) {
visits.add(new Visit(VisitKind.ERROR_INVALID_INVOKE,
error: error.messageKind, arguments: arguments));
super.errorInvalidInvoke(node, error, arguments, selector, arg);
@@ -55,10 +39,7 @@
@override
errorInvalidPostfix(
- Send node,
- ErroneousElement error,
- IncDecOperator operator,
- arg) {
+ Send node, ErroneousElement error, IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.ERROR_INVALID_POSTFIX,
error: error.messageKind, operator: operator));
super.errorInvalidPostfix(node, error, operator, arg);
@@ -66,32 +47,21 @@
@override
errorInvalidPrefix(
- Send node,
- ErroneousElement error,
- IncDecOperator operator,
- arg) {
+ Send node, ErroneousElement error, IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.ERROR_INVALID_PREFIX,
error: error.messageKind, operator: operator));
super.errorInvalidPrefix(node, error, operator, arg);
}
@override
- errorInvalidSet(
- Send node,
- ErroneousElement error,
- Node rhs,
- arg) {
+ errorInvalidSet(Send node, ErroneousElement error, Node rhs, arg) {
visits.add(new Visit(VisitKind.ERROR_INVALID_SET,
error: error.messageKind, rhs: rhs));
super.errorInvalidSet(node, error, rhs, arg);
}
@override
- errorInvalidSetIfNull(
- Send node,
- ErroneousElement error,
- Node rhs,
- arg) {
+ errorInvalidSetIfNull(Send node, ErroneousElement error, Node rhs, arg) {
visits.add(new Visit(VisitKind.ERROR_INVALID_SET_IF_NULL,
error: error.messageKind, rhs: rhs));
super.errorInvalidSetIfNull(node, error, rhs, arg);
@@ -99,55 +69,36 @@
@override
errorInvalidUnary(
- Send node,
- UnaryOperator operator,
- ErroneousElement error,
- arg) {
+ Send node, UnaryOperator operator, ErroneousElement error, arg) {
visits.add(new Visit(VisitKind.ERROR_INVALID_UNARY,
error: error.messageKind, operator: operator));
super.errorInvalidUnary(node, operator, error, arg);
}
@override
- errorInvalidEquals(
- Send node,
- ErroneousElement error,
- Node right,
- arg) {
+ errorInvalidEquals(Send node, ErroneousElement error, Node right, arg) {
visits.add(new Visit(VisitKind.ERROR_INVALID_EQUALS,
error: error.messageKind, right: right));
super.errorInvalidEquals(node, error, right, arg);
}
@override
- errorInvalidNotEquals(
- Send node,
- ErroneousElement error,
- Node right,
- arg) {
+ errorInvalidNotEquals(Send node, ErroneousElement error, Node right, arg) {
visits.add(new Visit(VisitKind.ERROR_INVALID_NOT_EQUALS,
error: error.messageKind, right: right));
super.errorInvalidNotEquals(node, error, right, arg);
}
@override
- errorInvalidBinary(
- Send node,
- ErroneousElement error,
- BinaryOperator operator,
- Node right,
- arg) {
+ errorInvalidBinary(Send node, ErroneousElement error, BinaryOperator operator,
+ Node right, arg) {
visits.add(new Visit(VisitKind.ERROR_INVALID_BINARY,
error: error.messageKind, operator: operator, right: right));
super.errorInvalidBinary(node, error, operator, right, arg);
}
@override
- errorInvalidIndex(
- Send node,
- ErroneousElement error,
- Node index,
- arg) {
+ errorInvalidIndex(Send node, ErroneousElement error, Node index, arg) {
visits.add(new Visit(VisitKind.ERROR_INVALID_INDEX,
error: error.messageKind, index: index));
super.errorInvalidIndex(node, error, index, arg);
@@ -155,60 +106,38 @@
@override
errorInvalidIndexSet(
- Send node,
- ErroneousElement error,
- Node index,
- Node rhs,
- arg) {
+ Send node, ErroneousElement error, Node index, Node rhs, arg) {
visits.add(new Visit(VisitKind.ERROR_INVALID_INDEX_SET,
error: error.messageKind, index: index, rhs: rhs));
super.errorInvalidIndexSet(node, error, index, rhs, arg);
}
@override
- errorInvalidCompoundIndexSet(
- Send node,
- ErroneousElement error,
- Node index,
- AssignmentOperator operator,
- Node rhs,
- arg) {
+ errorInvalidCompoundIndexSet(Send node, ErroneousElement error, Node index,
+ AssignmentOperator operator, Node rhs, arg) {
visits.add(new Visit(VisitKind.ERROR_INVALID_COMPOUND_INDEX_SET,
error: error.messageKind, index: index, operator: operator, rhs: rhs));
super.errorInvalidCompoundIndexSet(node, error, index, operator, rhs, arg);
}
@override
- errorInvalidIndexPrefix(
- Send node,
- ErroneousElement error,
- Node index,
- IncDecOperator operator,
- arg) {
+ errorInvalidIndexPrefix(Send node, ErroneousElement error, Node index,
+ IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.ERROR_INVALID_INDEX_PREFIX,
error: error.messageKind, index: index, operator: operator));
super.errorInvalidIndexPrefix(node, error, index, operator, arg);
}
@override
- errorInvalidIndexPostfix(
- Send node,
- ErroneousElement error,
- Node index,
- IncDecOperator operator,
- arg) {
+ errorInvalidIndexPostfix(Send node, ErroneousElement error, Node index,
+ IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.ERROR_INVALID_INDEX_POSTFIX,
error: error.messageKind, index: index, operator: operator));
super.errorInvalidIndexPostfix(node, error, index, operator, arg);
}
@override
- visitBinary(
- Send node,
- Node left,
- BinaryOperator operator,
- Node right,
- arg) {
+ visitBinary(Send node, Node left, BinaryOperator operator, Node right, arg) {
visits.add(new Visit(VisitKind.VISIT_BINARY,
left: left, operator: operator, right: right));
super.visitBinary(node, left, operator, right, arg);
@@ -216,44 +145,29 @@
@override
errorUndefinedBinaryExpression(
- Send node,
- Node left,
- Operator operator,
- Node right,
- arg) {
+ Send node, Node left, Operator operator, Node right, arg) {
visits.add(new Visit(VisitKind.ERROR_UNDEFINED_BINARY_EXPRESSION,
left: left, operator: operator, right: right));
super.errorUndefinedBinaryExpression(node, left, operator, right, arg);
}
@override
- visitIndex(
- Send node,
- Node receiver,
- Node index,
- arg) {
- visits.add(new Visit(VisitKind.VISIT_INDEX,
- receiver: receiver, index: index));
+ visitIndex(Send node, Node receiver, Node index, arg) {
+ visits.add(
+ new Visit(VisitKind.VISIT_INDEX, receiver: receiver, index: index));
apply(receiver, arg);
apply(index, arg);
}
@override
- visitClassTypeLiteralGet(
- Send node,
- ConstantExpression constant,
- arg) {
+ visitClassTypeLiteralGet(Send node, ConstantExpression constant, arg) {
visits.add(new Visit(VisitKind.VISIT_CLASS_TYPE_LITERAL_GET,
constant: constant.toDartText()));
}
@override
- visitClassTypeLiteralInvoke(
- Send node,
- ConstantExpression constant,
- NodeList arguments,
- CallStructure callStructure,
- arg) {
+ visitClassTypeLiteralInvoke(Send node, ConstantExpression constant,
+ NodeList arguments, CallStructure callStructure, arg) {
visits.add(new Visit(VisitKind.VISIT_CLASS_TYPE_LITERAL_INVOKE,
constant: constant.toDartText(), arguments: arguments));
apply(arguments, arg);
@@ -261,34 +175,22 @@
@override
visitClassTypeLiteralSet(
- SendSet node,
- ConstantExpression constant,
- Node rhs,
- arg) {
+ SendSet node, ConstantExpression constant, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_CLASS_TYPE_LITERAL_SET,
constant: constant.toDartText(), rhs: rhs));
super.visitClassTypeLiteralSet(node, constant, rhs, arg);
}
@override
- visitNotEquals(
- Send node,
- Node left,
- Node right,
- arg) {
- visits.add(new Visit(VisitKind.VISIT_NOT_EQUALS,
- left: left, right: right));
+ visitNotEquals(Send node, Node left, Node right, arg) {
+ visits.add(new Visit(VisitKind.VISIT_NOT_EQUALS, left: left, right: right));
apply(left, arg);
apply(right, arg);
}
@override
visitDynamicPropertyPrefix(
- Send node,
- Node receiver,
- Name name,
- IncDecOperator operator,
- arg) {
+ Send node, Node receiver, Name name, IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.VISIT_DYNAMIC_PROPERTY_PREFIX,
receiver: receiver, operator: operator, name: name));
super.visitDynamicPropertyPrefix(node, receiver, name, operator, arg);
@@ -296,22 +198,14 @@
@override
visitDynamicPropertyPostfix(
- Send node,
- Node receiver,
- Name name,
- IncDecOperator operator,
- arg) {
+ Send node, Node receiver, Name name, IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.VISIT_DYNAMIC_PROPERTY_POSTFIX,
receiver: receiver, operator: operator, name: name));
super.visitDynamicPropertyPostfix(node, receiver, name, operator, arg);
}
@override
- visitDynamicPropertyGet(
- Send node,
- Node receiver,
- Name name,
- arg) {
+ visitDynamicPropertyGet(Send node, Node receiver, Name name, arg) {
visits.add(new Visit(VisitKind.VISIT_DYNAMIC_PROPERTY_GET,
receiver: receiver, name: name));
super.visitDynamicPropertyGet(node, receiver, name, arg);
@@ -319,11 +213,7 @@
@override
visitDynamicPropertyInvoke(
- Send node,
- Node receiver,
- NodeList arguments,
- Selector selector,
- arg) {
+ Send node, Node receiver, NodeList arguments, Selector selector, arg) {
visits.add(new Visit(VisitKind.VISIT_DYNAMIC_PROPERTY_INVOKE,
receiver: receiver, name: selector.name, arguments: arguments));
super.visitDynamicPropertyInvoke(node, receiver, arguments, selector, arg);
@@ -331,131 +221,86 @@
@override
visitDynamicPropertySet(
- SendSet node,
- Node receiver,
- Name name,
- Node rhs,
- arg) {
+ SendSet node, Node receiver, Name name, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_DYNAMIC_PROPERTY_SET,
receiver: receiver, name: name, rhs: rhs));
super.visitDynamicPropertySet(node, receiver, name, rhs, arg);
}
@override
- visitDynamicTypeLiteralGet(
- Send node,
- ConstantExpression constant,
- arg) {
+ visitDynamicTypeLiteralGet(Send node, ConstantExpression constant, arg) {
visits.add(new Visit(VisitKind.VISIT_DYNAMIC_TYPE_LITERAL_GET,
constant: constant.toDartText()));
}
@override
- visitDynamicTypeLiteralInvoke(
- Send node,
- ConstantExpression constant,
- NodeList arguments,
- CallStructure callStructure,
- arg) {
+ visitDynamicTypeLiteralInvoke(Send node, ConstantExpression constant,
+ NodeList arguments, CallStructure callStructure, arg) {
visits.add(new Visit(VisitKind.VISIT_DYNAMIC_TYPE_LITERAL_INVOKE,
constant: constant.toDartText(), arguments: arguments));
}
@override
visitDynamicTypeLiteralSet(
- Send node,
- ConstantExpression constant,
- Node rhs,
- arg) {
+ Send node, ConstantExpression constant, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_DYNAMIC_TYPE_LITERAL_SET,
constant: constant.toDartText(), rhs: rhs));
super.visitDynamicTypeLiteralSet(node, constant, rhs, arg);
}
@override
- visitExpressionInvoke(
- Send node,
- Node expression,
- NodeList arguments,
- CallStructure callStructure,
- arg) {
+ visitExpressionInvoke(Send node, Node expression, NodeList arguments,
+ CallStructure callStructure, arg) {
visits.add(new Visit(VisitKind.VISIT_EXPRESSION_INVOKE,
receiver: expression, arguments: arguments));
}
@override
- visitIs(
- Send node,
- Node expression,
- DartType type,
- arg) {
- visits.add(new Visit(VisitKind.VISIT_IS,
- expression: expression, type: type));
+ visitIs(Send node, Node expression, DartType type, arg) {
+ visits
+ .add(new Visit(VisitKind.VISIT_IS, expression: expression, type: type));
apply(expression, arg);
}
@override
- visitIsNot(
- Send node,
- Node expression,
- DartType type,
- arg) {
- visits.add(new Visit(VisitKind.VISIT_IS_NOT,
- expression: expression, type: type));
+ visitIsNot(Send node, Node expression, DartType type, arg) {
+ visits.add(
+ new Visit(VisitKind.VISIT_IS_NOT, expression: expression, type: type));
apply(expression, arg);
}
@override
- visitLogicalAnd(
- Send node,
- Node left,
- Node right,
- arg) {
- visits.add(new Visit(VisitKind.VISIT_LOGICAL_AND,
- left: left, right: right));
+ visitLogicalAnd(Send node, Node left, Node right, arg) {
+ visits
+ .add(new Visit(VisitKind.VISIT_LOGICAL_AND, left: left, right: right));
apply(left, arg);
apply(right, arg);
}
@override
- visitLogicalOr(
- Send node,
- Node left,
- Node right,
- arg) {
- visits.add(new Visit(VisitKind.VISIT_LOGICAL_OR,
- left: left, right: right));
+ visitLogicalOr(Send node, Node left, Node right, arg) {
+ visits.add(new Visit(VisitKind.VISIT_LOGICAL_OR, left: left, right: right));
apply(left, arg);
apply(right, arg);
}
@override
- visitLocalFunctionGet(
- Send node,
- LocalFunctionElement function,
- arg) {
- visits.add(new Visit(VisitKind.VISIT_LOCAL_FUNCTION_GET,
- element: function));
+ visitLocalFunctionGet(Send node, LocalFunctionElement function, arg) {
+ visits
+ .add(new Visit(VisitKind.VISIT_LOCAL_FUNCTION_GET, element: function));
}
@override
visitLocalFunctionSet(
- SendSet node,
- LocalFunctionElement function,
- Node rhs,
- arg) {
+ SendSet node, LocalFunctionElement function, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_LOCAL_FUNCTION_SET,
element: function, rhs: rhs));
super.visitLocalFunctionSet(node, function, rhs, arg);
}
@override
- visitLocalFunctionInvoke(
- Send node,
- LocalFunctionElement function,
- NodeList arguments,
- CallStructure callStructure,
- arg) {
+ visitLocalFunctionInvoke(Send node, LocalFunctionElement function,
+ NodeList arguments, CallStructure callStructure, arg) {
visits.add(new Visit(VisitKind.VISIT_LOCAL_FUNCTION_INVOKE,
element: function, arguments: arguments, selector: callStructure));
super.visitLocalFunctionInvoke(
@@ -463,12 +308,8 @@
}
@override
- visitLocalFunctionIncompatibleInvoke(
- Send node,
- LocalFunctionElement function,
- NodeList arguments,
- CallStructure callStructure,
- arg) {
+ visitLocalFunctionIncompatibleInvoke(Send node, LocalFunctionElement function,
+ NodeList arguments, CallStructure callStructure, arg) {
visits.add(new Visit(VisitKind.VISIT_LOCAL_FUNCTION_INCOMPATIBLE_INVOKE,
element: function, arguments: arguments, selector: callStructure));
super.visitLocalFunctionInvoke(
@@ -476,21 +317,14 @@
}
@override
- visitLocalVariableGet(
- Send node,
- LocalVariableElement variable,
- arg) {
- visits.add(new Visit(VisitKind.VISIT_LOCAL_VARIABLE_GET,
- element: variable));
+ visitLocalVariableGet(Send node, LocalVariableElement variable, arg) {
+ visits
+ .add(new Visit(VisitKind.VISIT_LOCAL_VARIABLE_GET, element: variable));
}
@override
- visitLocalVariableInvoke(
- Send node,
- LocalVariableElement variable,
- NodeList arguments,
- CallStructure callStructure,
- arg) {
+ visitLocalVariableInvoke(Send node, LocalVariableElement variable,
+ NodeList arguments, CallStructure callStructure, arg) {
visits.add(new Visit(VisitKind.VISIT_LOCAL_VARIABLE_INVOKE,
element: variable, arguments: arguments, selector: callStructure));
apply(arguments, arg);
@@ -498,10 +332,7 @@
@override
visitLocalVariableSet(
- SendSet node,
- LocalVariableElement variable,
- Node rhs,
- arg) {
+ SendSet node, LocalVariableElement variable, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_LOCAL_VARIABLE_SET,
element: variable, rhs: rhs));
super.visitLocalVariableSet(node, variable, rhs, arg);
@@ -509,126 +340,83 @@
@override
visitFinalLocalVariableSet(
- SendSet node,
- LocalVariableElement variable,
- Node rhs,
- arg) {
+ SendSet node, LocalVariableElement variable, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_FINAL_LOCAL_VARIABLE_SET,
element: variable, rhs: rhs));
super.visitFinalLocalVariableSet(node, variable, rhs, arg);
}
@override
- visitParameterGet(
- Send node,
- ParameterElement parameter,
- arg) {
+ visitParameterGet(Send node, ParameterElement parameter, arg) {
visits.add(new Visit(VisitKind.VISIT_PARAMETER_GET, element: parameter));
}
@override
- visitParameterInvoke(
- Send node,
- ParameterElement parameter,
- NodeList arguments,
- CallStructure callStructure,
- arg) {
+ visitParameterInvoke(Send node, ParameterElement parameter,
+ NodeList arguments, CallStructure callStructure, arg) {
visits.add(new Visit(VisitKind.VISIT_PARAMETER_INVOKE,
element: parameter, arguments: arguments, selector: callStructure));
apply(arguments, arg);
}
@override
- visitParameterSet(
- SendSet node,
- ParameterElement parameter,
- Node rhs,
- arg) {
- visits.add(new Visit(VisitKind.VISIT_PARAMETER_SET,
- element: parameter, rhs: rhs));
+ visitParameterSet(SendSet node, ParameterElement parameter, Node rhs, arg) {
+ visits.add(
+ new Visit(VisitKind.VISIT_PARAMETER_SET, element: parameter, rhs: rhs));
super.visitParameterSet(node, parameter, rhs, arg);
}
@override
visitFinalParameterSet(
- SendSet node,
- ParameterElement parameter,
- Node rhs,
- arg) {
+ SendSet node, ParameterElement parameter, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_FINAL_PARAMETER_SET,
- element: parameter, rhs: rhs));
+ element: parameter, rhs: rhs));
super.visitFinalParameterSet(node, parameter, rhs, arg);
}
@override
- visitStaticFieldGet(
- Send node,
- FieldElement field,
- arg) {
+ visitStaticFieldGet(Send node, FieldElement field, arg) {
visits.add(new Visit(VisitKind.VISIT_STATIC_FIELD_GET, element: field));
}
@override
- visitStaticFieldInvoke(
- Send node,
- FieldElement field,
- NodeList arguments,
- CallStructure callStructure,
- arg) {
+ visitStaticFieldInvoke(Send node, FieldElement field, NodeList arguments,
+ CallStructure callStructure, arg) {
visits.add(new Visit(VisitKind.VISIT_STATIC_FIELD_INVOKE,
element: field, arguments: arguments));
apply(arguments, arg);
}
@override
- visitStaticFieldSet(
- SendSet node,
- FieldElement field,
- Node rhs,
- arg) {
- visits.add(new Visit(VisitKind.VISIT_STATIC_FIELD_SET,
- element: field, rhs: rhs));
+ visitStaticFieldSet(SendSet node, FieldElement field, Node rhs, arg) {
+ visits.add(
+ new Visit(VisitKind.VISIT_STATIC_FIELD_SET, element: field, rhs: rhs));
super.visitStaticFieldSet(node, field, rhs, arg);
}
@override
- visitFinalStaticFieldSet(
- SendSet node,
- FieldElement field,
- Node rhs,
- arg) {
+ visitFinalStaticFieldSet(SendSet node, FieldElement field, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_FINAL_STATIC_FIELD_SET,
element: field, rhs: rhs));
super.visitFinalStaticFieldSet(node, field, rhs, arg);
}
@override
- visitStaticFunctionGet(
- Send node,
- MethodElement function,
- arg) {
- visits.add(new Visit(VisitKind.VISIT_STATIC_FUNCTION_GET,
- element: function));
+ visitStaticFunctionGet(Send node, MethodElement function, arg) {
+ visits
+ .add(new Visit(VisitKind.VISIT_STATIC_FUNCTION_GET, element: function));
}
@override
- visitStaticFunctionSet(
- SendSet node,
- MethodElement function,
- Node rhs,
- arg) {
+ visitStaticFunctionSet(SendSet node, MethodElement function, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_STATIC_FUNCTION_SET,
element: function, rhs: rhs));
super.visitStaticFunctionSet(node, function, rhs, arg);
}
@override
- visitStaticFunctionInvoke(
- Send node,
- MethodElement function,
- NodeList arguments,
- CallStructure callStructure,
- arg) {
+ visitStaticFunctionInvoke(Send node, MethodElement function,
+ NodeList arguments, CallStructure callStructure, arg) {
visits.add(new Visit(VisitKind.VISIT_STATIC_FUNCTION_INVOKE,
element: function, arguments: arguments));
super.visitStaticFunctionInvoke(
@@ -636,90 +424,58 @@
}
@override
- visitStaticFunctionIncompatibleInvoke(
- Send node,
- MethodElement function,
- NodeList arguments,
- CallStructure callStructure,
- arg) {
+ visitStaticFunctionIncompatibleInvoke(Send node, MethodElement function,
+ NodeList arguments, CallStructure callStructure, arg) {
visits.add(new Visit(VisitKind.VISIT_STATIC_FUNCTION_INCOMPATIBLE_INVOKE,
element: function, arguments: arguments));
apply(arguments, arg);
}
@override
- visitStaticGetterGet(
- Send node,
- FunctionElement getter,
- arg) {
- visits.add(new Visit(VisitKind.VISIT_STATIC_GETTER_GET,
- element: getter));
+ visitStaticGetterGet(Send node, FunctionElement getter, arg) {
+ visits.add(new Visit(VisitKind.VISIT_STATIC_GETTER_GET, element: getter));
super.visitStaticGetterGet(node, getter, arg);
}
@override
- visitStaticGetterSet(
- SendSet node,
- MethodElement getter,
- Node rhs,
- arg) {
+ visitStaticGetterSet(SendSet node, MethodElement getter, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_STATIC_GETTER_SET,
element: getter, rhs: rhs));
super.visitStaticGetterSet(node, getter, rhs, arg);
}
@override
- visitStaticGetterInvoke(
- Send node,
- FunctionElement getter,
- NodeList arguments,
- CallStructure callStructure,
- arg) {
+ visitStaticGetterInvoke(Send node, FunctionElement getter, NodeList arguments,
+ CallStructure callStructure, arg) {
visits.add(new Visit(VisitKind.VISIT_STATIC_GETTER_INVOKE,
element: getter, arguments: arguments));
super.visitStaticGetterInvoke(node, getter, arguments, callStructure, arg);
}
@override
- visitStaticSetterInvoke(
- Send node,
- FunctionElement setter,
- NodeList arguments,
- CallStructure callStructure,
- arg) {
+ visitStaticSetterInvoke(Send node, FunctionElement setter, NodeList arguments,
+ CallStructure callStructure, arg) {
visits.add(new Visit(VisitKind.VISIT_STATIC_SETTER_INVOKE,
element: setter, arguments: arguments));
super.visitStaticSetterInvoke(node, setter, arguments, callStructure, arg);
}
@override
- visitStaticSetterGet(
- Send node,
- FunctionElement getter,
- arg) {
- visits.add(new Visit(VisitKind.VISIT_STATIC_SETTER_GET,
- element: getter));
+ visitStaticSetterGet(Send node, FunctionElement getter, arg) {
+ visits.add(new Visit(VisitKind.VISIT_STATIC_SETTER_GET, element: getter));
super.visitStaticSetterGet(node, getter, arg);
}
@override
- visitStaticSetterSet(
- SendSet node,
- FunctionElement setter,
- Node rhs,
- arg) {
+ visitStaticSetterSet(SendSet node, FunctionElement setter, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_STATIC_SETTER_SET,
element: setter, rhs: rhs));
super.visitStaticSetterSet(node, setter, rhs, arg);
}
@override
- visitSuperBinary(
- Send node,
- FunctionElement function,
- BinaryOperator operator,
- Node argument,
- arg) {
+ visitSuperBinary(Send node, FunctionElement function, BinaryOperator operator,
+ Node argument, arg) {
visits.add(new Visit(VisitKind.VISIT_SUPER_BINARY,
element: function, operator: operator, right: argument));
apply(argument, arg);
@@ -727,46 +483,29 @@
@override
visitUnresolvedSuperBinary(
- Send node,
- Element element,
- BinaryOperator operator,
- Node argument,
- arg) {
+ Send node, Element element, BinaryOperator operator, Node argument, arg) {
visits.add(new Visit(VisitKind.VISIT_UNRESOLVED_SUPER_BINARY,
operator: operator, right: argument));
apply(argument, arg);
}
@override
- visitSuperIndex(
- Send node,
- FunctionElement function,
- Node index,
- arg) {
+ visitSuperIndex(Send node, FunctionElement function, Node index, arg) {
visits.add(new Visit(VisitKind.VISIT_SUPER_INDEX,
- element: function, index: index));
+ element: function, index: index));
apply(index, arg);
}
@override
- visitUnresolvedSuperIndex(
- Send node,
- Element element,
- Node index,
- arg) {
- visits.add(new Visit(VisitKind.VISIT_UNRESOLVED_SUPER_INDEX,
- index: index));
+ visitUnresolvedSuperIndex(Send node, Element element, Node index, arg) {
+ visits.add(new Visit(VisitKind.VISIT_UNRESOLVED_SUPER_INDEX, index: index));
apply(index, arg);
}
@override
- visitSuperNotEquals(
- Send node,
- FunctionElement function,
- Node argument,
- arg) {
+ visitSuperNotEquals(Send node, FunctionElement function, Node argument, arg) {
visits.add(new Visit(VisitKind.VISIT_SUPER_NOT_EQUALS,
- element: function, right: argument));
+ element: function, right: argument));
apply(argument, arg);
}
@@ -777,216 +516,144 @@
@override
visitThisInvoke(
- Send node,
- NodeList arguments,
- CallStructure callStructure,
- arg) {
+ Send node, NodeList arguments, CallStructure callStructure, arg) {
visits.add(new Visit(VisitKind.VISIT_THIS_INVOKE, arguments: arguments));
apply(arguments, arg);
}
@override
- visitThisPropertyGet(
- Send node,
- Name name,
- arg) {
- visits.add(new Visit(VisitKind.VISIT_THIS_PROPERTY_GET,
- name: name));
+ visitThisPropertyGet(Send node, Name name, arg) {
+ visits.add(new Visit(VisitKind.VISIT_THIS_PROPERTY_GET, name: name));
super.visitThisPropertyGet(node, name, arg);
}
@override
visitThisPropertyInvoke(
- Send node,
- NodeList arguments,
- Selector selector,
- arg) {
+ Send node, NodeList arguments, Selector selector, arg) {
visits.add(new Visit(VisitKind.VISIT_THIS_PROPERTY_INVOKE,
- name: selector.name, arguments: arguments));
+ name: selector.name, arguments: arguments));
super.visitThisPropertyInvoke(node, arguments, selector, arg);
}
@override
- visitThisPropertySet(
- SendSet node,
- Name name,
- Node rhs,
- arg) {
- visits.add(new Visit(VisitKind.VISIT_THIS_PROPERTY_SET,
- name: name, rhs: rhs));
+ visitThisPropertySet(SendSet node, Name name, Node rhs, arg) {
+ visits.add(
+ new Visit(VisitKind.VISIT_THIS_PROPERTY_SET, name: name, rhs: rhs));
super.visitThisPropertySet(node, name, rhs, arg);
}
@override
- visitTopLevelFieldGet(
- Send node,
- FieldElement field,
- arg) {
+ visitTopLevelFieldGet(Send node, FieldElement field, arg) {
visits.add(new Visit(VisitKind.VISIT_TOP_LEVEL_FIELD_GET, element: field));
}
@override
- visitTopLevelFieldInvoke(
- Send node,
- FieldElement field,
- NodeList arguments,
- CallStructure callStructure,
- arg) {
+ visitTopLevelFieldInvoke(Send node, FieldElement field, NodeList arguments,
+ CallStructure callStructure, arg) {
visits.add(new Visit(VisitKind.VISIT_TOP_LEVEL_FIELD_INVOKE,
element: field, arguments: arguments));
apply(arguments, arg);
}
@override
- visitTopLevelFieldSet(
- SendSet node,
- FieldElement field,
- Node rhs,
- arg) {
+ visitTopLevelFieldSet(SendSet node, FieldElement field, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_TOP_LEVEL_FIELD_SET,
element: field, rhs: rhs));
super.visitTopLevelFieldSet(node, field, rhs, arg);
}
@override
- visitFinalTopLevelFieldSet(
- SendSet node,
- FieldElement field,
- Node rhs,
- arg) {
+ visitFinalTopLevelFieldSet(SendSet node, FieldElement field, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_FINAL_TOP_LEVEL_FIELD_SET,
element: field, rhs: rhs));
super.visitFinalTopLevelFieldSet(node, field, rhs, arg);
}
@override
- visitTopLevelFunctionGet(
- Send node,
- MethodElement function,
- arg) {
- visits.add(new Visit(VisitKind.VISIT_TOP_LEVEL_FUNCTION_GET,
- element: function));
+ visitTopLevelFunctionGet(Send node, MethodElement function, arg) {
+ visits.add(
+ new Visit(VisitKind.VISIT_TOP_LEVEL_FUNCTION_GET, element: function));
}
@override
visitTopLevelFunctionSet(
- SendSet node,
- MethodElement function,
- Node rhs,
- arg) {
+ SendSet node, MethodElement function, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_TOP_LEVEL_FUNCTION_SET,
element: function, rhs: rhs));
super.visitTopLevelFunctionSet(node, function, rhs, arg);
}
@override
- visitTopLevelFunctionInvoke(
- Send node,
- MethodElement function,
- NodeList arguments,
- CallStructure callStructure,
- arg) {
+ visitTopLevelFunctionInvoke(Send node, MethodElement function,
+ NodeList arguments, CallStructure callStructure, arg) {
visits.add(new Visit(VisitKind.VISIT_TOP_LEVEL_FUNCTION_INVOKE,
element: function, arguments: arguments));
apply(arguments, arg);
}
@override
- visitTopLevelFunctionIncompatibleInvoke(
- Send node,
- MethodElement function,
- NodeList arguments,
- CallStructure callStructure,
- arg) {
+ visitTopLevelFunctionIncompatibleInvoke(Send node, MethodElement function,
+ NodeList arguments, CallStructure callStructure, arg) {
visits.add(new Visit(VisitKind.VISIT_TOP_LEVEL_FUNCTION_INCOMPATIBLE_INVOKE,
element: function, arguments: arguments));
apply(arguments, arg);
}
@override
- visitTopLevelGetterGet(
- Send node,
- FunctionElement getter,
- arg) {
- visits.add(new Visit(VisitKind.VISIT_TOP_LEVEL_GETTER_GET,
- element: getter));
+ visitTopLevelGetterGet(Send node, FunctionElement getter, arg) {
+ visits
+ .add(new Visit(VisitKind.VISIT_TOP_LEVEL_GETTER_GET, element: getter));
super.visitTopLevelGetterGet(node, getter, arg);
}
@override
- visitTopLevelSetterGet(
- Send node,
- FunctionElement setter,
- arg) {
- visits.add(new Visit(VisitKind.VISIT_TOP_LEVEL_SETTER_GET,
- element: setter));
+ visitTopLevelSetterGet(Send node, FunctionElement setter, arg) {
+ visits
+ .add(new Visit(VisitKind.VISIT_TOP_LEVEL_SETTER_GET, element: setter));
super.visitTopLevelSetterGet(node, setter, arg);
}
@override
- visitTopLevelGetterInvoke(
- Send node,
- FunctionElement getter,
- NodeList arguments,
- CallStructure callStructure,
- arg) {
+ visitTopLevelGetterInvoke(Send node, FunctionElement getter,
+ NodeList arguments, CallStructure callStructure, arg) {
visits.add(new Visit(VisitKind.VISIT_TOP_LEVEL_GETTER_INVOKE,
element: getter, arguments: arguments));
- super.visitTopLevelGetterInvoke(
- node, getter, arguments, callStructure, arg);
+ super
+ .visitTopLevelGetterInvoke(node, getter, arguments, callStructure, arg);
}
@override
- visitTopLevelSetterInvoke(
- Send node,
- FunctionElement setter,
- NodeList arguments,
- CallStructure callStructure,
- arg) {
+ visitTopLevelSetterInvoke(Send node, FunctionElement setter,
+ NodeList arguments, CallStructure callStructure, arg) {
visits.add(new Visit(VisitKind.VISIT_TOP_LEVEL_SETTER_INVOKE,
element: setter, arguments: arguments));
- super.visitTopLevelSetterInvoke(
- node, setter, arguments, callStructure, arg);
+ super
+ .visitTopLevelSetterInvoke(node, setter, arguments, callStructure, arg);
}
@override
- visitTopLevelGetterSet(
- SendSet node,
- FunctionElement getter,
- Node rhs,
- arg) {
+ visitTopLevelGetterSet(SendSet node, FunctionElement getter, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_TOP_LEVEL_GETTER_SET,
element: getter, rhs: rhs));
super.visitTopLevelGetterSet(node, getter, rhs, arg);
}
@override
- visitTopLevelSetterSet(
- SendSet node,
- FunctionElement setter,
- Node rhs,
- arg) {
+ visitTopLevelSetterSet(SendSet node, FunctionElement setter, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_TOP_LEVEL_SETTER_SET,
element: setter, rhs: rhs));
super.visitTopLevelSetterSet(node, setter, rhs, arg);
}
@override
- visitTypeVariableTypeLiteralGet(
- Send node,
- TypeVariableElement element,
- arg) {
+ visitTypeVariableTypeLiteralGet(Send node, TypeVariableElement element, arg) {
visits.add(new Visit(VisitKind.VISIT_TYPE_VARIABLE_TYPE_LITERAL_GET,
element: element));
}
@override
- visitTypeVariableTypeLiteralInvoke(
- Send node,
- TypeVariableElement element,
- NodeList arguments,
- CallStructure callStructure,
- arg) {
+ visitTypeVariableTypeLiteralInvoke(Send node, TypeVariableElement element,
+ NodeList arguments, CallStructure callStructure, arg) {
visits.add(new Visit(VisitKind.VISIT_TYPE_VARIABLE_TYPE_LITERAL_INVOKE,
element: element, arguments: arguments));
apply(arguments, arg);
@@ -994,31 +661,21 @@
@override
visitTypeVariableTypeLiteralSet(
- SendSet node,
- TypeVariableElement element,
- Node rhs,
- arg) {
+ SendSet node, TypeVariableElement element, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_TYPE_VARIABLE_TYPE_LITERAL_SET,
element: element, rhs: rhs));
super.visitTypeVariableTypeLiteralSet(node, element, rhs, arg);
}
@override
- visitTypedefTypeLiteralGet(
- Send node,
- ConstantExpression constant,
- arg) {
+ visitTypedefTypeLiteralGet(Send node, ConstantExpression constant, arg) {
visits.add(new Visit(VisitKind.VISIT_TYPEDEF_TYPE_LITERAL_GET,
constant: constant.toDartText()));
}
@override
- visitTypedefTypeLiteralInvoke(
- Send node,
- ConstantExpression constant,
- NodeList arguments,
- CallStructure callStructure,
- arg) {
+ visitTypedefTypeLiteralInvoke(Send node, ConstantExpression constant,
+ NodeList arguments, CallStructure callStructure, arg) {
visits.add(new Visit(VisitKind.VISIT_TYPEDEF_TYPE_LITERAL_INVOKE,
constant: constant.toDartText(), arguments: arguments));
apply(arguments, arg);
@@ -1026,21 +683,14 @@
@override
visitTypedefTypeLiteralSet(
- SendSet node,
- ConstantExpression constant,
- Node rhs,
- arg) {
+ SendSet node, ConstantExpression constant, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_TYPEDEF_TYPE_LITERAL_SET,
constant: constant.toDartText(), rhs: rhs));
super.visitTypedefTypeLiteralSet(node, constant, rhs, arg);
}
@override
- visitUnary(
- Send node,
- UnaryOperator operator,
- Node expression,
- arg) {
+ visitUnary(Send node, UnaryOperator operator, Node expression, arg) {
visits.add(new Visit(VisitKind.VISIT_UNARY,
expression: expression, operator: operator));
super.visitUnary(node, operator, expression, arg);
@@ -1048,58 +698,38 @@
@override
errorUndefinedUnaryExpression(
- Send node,
- Operator operator,
- Node expression,
- arg) {
+ Send node, Operator operator, Node expression, arg) {
visits.add(new Visit(VisitKind.ERROR_UNDEFINED_UNARY_EXPRESSION,
expression: expression, operator: operator));
super.errorUndefinedUnaryExpression(node, operator, expression, arg);
}
@override
- visitNot(
- Send node,
- Node expression,
- arg) {
+ visitNot(Send node, Node expression, arg) {
visits.add(new Visit(VisitKind.VISIT_NOT, expression: expression));
apply(expression, arg);
}
@override
- visitSuperFieldGet(
- Send node,
- FieldElement field,
- arg) {
+ visitSuperFieldGet(Send node, FieldElement field, arg) {
visits.add(new Visit(VisitKind.VISIT_SUPER_FIELD_GET, element: field));
}
@override
- visitUnresolvedSuperGet(
- Send node,
- Element element,
- arg) {
+ visitUnresolvedSuperGet(Send node, Element element, arg) {
visits.add(new Visit(VisitKind.VISIT_UNRESOLVED_SUPER_GET));
return super.visitUnresolvedSuperGet(node, element, arg);
}
@override
- visitUnresolvedSuperSet(
- Send node,
- Element element,
- Node rhs,
- arg) {
+ visitUnresolvedSuperSet(Send node, Element element, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_UNRESOLVED_SUPER_SET, rhs: rhs));
return super.visitUnresolvedSuperSet(node, element, rhs, arg);
}
@override
- visitSuperFieldInvoke(
- Send node,
- FieldElement field,
- NodeList arguments,
- CallStructure callStructure,
- arg) {
+ visitSuperFieldInvoke(Send node, FieldElement field, NodeList arguments,
+ CallStructure callStructure, arg) {
visits.add(new Visit(VisitKind.VISIT_SUPER_FIELD_INVOKE,
element: field, arguments: arguments));
apply(arguments, arg);
@@ -1107,194 +737,126 @@
@override
visitUnresolvedSuperInvoke(
- Send node,
- Element element,
- NodeList arguments,
- Selector selector,
- arg) {
+ Send node, Element element, NodeList arguments, Selector selector, arg) {
visits.add(new Visit(VisitKind.VISIT_UNRESOLVED_SUPER_INVOKE,
arguments: arguments));
apply(arguments, arg);
}
@override
- visitSuperFieldSet(
- SendSet node,
- FieldElement field,
- Node rhs,
- arg) {
- visits.add(new Visit(VisitKind.VISIT_SUPER_FIELD_SET,
- element: field, rhs: rhs));
+ visitSuperFieldSet(SendSet node, FieldElement field, Node rhs, arg) {
+ visits.add(
+ new Visit(VisitKind.VISIT_SUPER_FIELD_SET, element: field, rhs: rhs));
super.visitSuperFieldSet(node, field, rhs, arg);
}
@override
- visitFinalSuperFieldSet(
- SendSet node,
- FieldElement field,
- Node rhs,
- arg) {
+ visitFinalSuperFieldSet(SendSet node, FieldElement field, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_FINAL_SUPER_FIELD_SET,
element: field, rhs: rhs));
super.visitFinalSuperFieldSet(node, field, rhs, arg);
}
@override
- visitSuperMethodGet(
- Send node,
- MethodElement method,
- arg) {
+ visitSuperMethodGet(Send node, MethodElement method, arg) {
visits.add(new Visit(VisitKind.VISIT_SUPER_METHOD_GET, element: method));
}
@override
- visitSuperMethodSet(
- SendSet node,
- MethodElement method,
- Node rhs,
- arg) {
- visits.add(new Visit(VisitKind.VISIT_SUPER_METHOD_SET,
- element: method, rhs: rhs));
+ visitSuperMethodSet(SendSet node, MethodElement method, Node rhs, arg) {
+ visits.add(
+ new Visit(VisitKind.VISIT_SUPER_METHOD_SET, element: method, rhs: rhs));
super.visitSuperMethodSet(node, method, rhs, arg);
}
@override
- visitSuperMethodInvoke(
- Send node,
- MethodElement method,
- NodeList arguments,
- CallStructure callStructure,
- arg) {
+ visitSuperMethodInvoke(Send node, MethodElement method, NodeList arguments,
+ CallStructure callStructure, arg) {
visits.add(new Visit(VisitKind.VISIT_SUPER_METHOD_INVOKE,
element: method, arguments: arguments));
apply(arguments, arg);
}
@override
- visitSuperMethodIncompatibleInvoke(
- Send node,
- MethodElement method,
- NodeList arguments,
- CallStructure callStructure,
- arg) {
+ visitSuperMethodIncompatibleInvoke(Send node, MethodElement method,
+ NodeList arguments, CallStructure callStructure, arg) {
visits.add(new Visit(VisitKind.VISIT_SUPER_METHOD_INCOMPATIBLE_INVOKE,
element: method, arguments: arguments));
apply(arguments, arg);
}
@override
- visitSuperGetterGet(
- Send node,
- FunctionElement getter,
- arg) {
+ visitSuperGetterGet(Send node, FunctionElement getter, arg) {
visits.add(new Visit(VisitKind.VISIT_SUPER_GETTER_GET, element: getter));
super.visitSuperGetterGet(node, getter, arg);
}
@override
- visitSuperSetterGet(
- Send node,
- FunctionElement setter,
- arg) {
+ visitSuperSetterGet(Send node, FunctionElement setter, arg) {
visits.add(new Visit(VisitKind.VISIT_SUPER_SETTER_GET, element: setter));
super.visitSuperSetterGet(node, setter, arg);
}
@override
- visitSuperGetterInvoke(
- Send node,
- FunctionElement getter,
- NodeList arguments,
- CallStructure callStructure,
- arg) {
+ visitSuperGetterInvoke(Send node, FunctionElement getter, NodeList arguments,
+ CallStructure callStructure, arg) {
visits.add(new Visit(VisitKind.VISIT_SUPER_GETTER_INVOKE,
element: getter, arguments: arguments));
super.visitSuperGetterInvoke(node, getter, arguments, callStructure, arg);
}
@override
- visitSuperSetterInvoke(
- Send node,
- FunctionElement setter,
- NodeList arguments,
- CallStructure callStructure,
- arg) {
+ visitSuperSetterInvoke(Send node, FunctionElement setter, NodeList arguments,
+ CallStructure callStructure, arg) {
visits.add(new Visit(VisitKind.VISIT_SUPER_SETTER_INVOKE,
element: setter, arguments: arguments));
super.visitSuperSetterInvoke(node, setter, arguments, callStructure, arg);
}
@override
- visitSuperGetterSet(
- SendSet node,
- FunctionElement getter,
- Node rhs,
- arg) {
- visits.add(new Visit(VisitKind.VISIT_SUPER_GETTER_SET,
- element: getter, rhs: rhs));
+ visitSuperGetterSet(SendSet node, FunctionElement getter, Node rhs, arg) {
+ visits.add(
+ new Visit(VisitKind.VISIT_SUPER_GETTER_SET, element: getter, rhs: rhs));
super.visitSuperGetterSet(node, getter, rhs, arg);
}
@override
- visitSuperSetterSet(
- SendSet node,
- FunctionElement setter,
- Node rhs,
- arg) {
- visits.add(new Visit(VisitKind.VISIT_SUPER_SETTER_SET,
- element: setter, rhs: rhs));
+ visitSuperSetterSet(SendSet node, FunctionElement setter, Node rhs, arg) {
+ visits.add(
+ new Visit(VisitKind.VISIT_SUPER_SETTER_SET, element: setter, rhs: rhs));
super.visitSuperSetterSet(node, setter, rhs, arg);
}
@override
visitSuperUnary(
- Send node,
- UnaryOperator operator,
- FunctionElement function,
- arg) {
+ Send node, UnaryOperator operator, FunctionElement function, arg) {
visits.add(new Visit(VisitKind.VISIT_SUPER_UNARY,
element: function, operator: operator));
}
@override
visitUnresolvedSuperUnary(
- Send node,
- UnaryOperator operator,
- Element element,
- arg) {
- visits.add(new Visit(VisitKind.VISIT_UNRESOLVED_SUPER_UNARY,
- operator: operator));
+ Send node, UnaryOperator operator, Element element, arg) {
+ visits.add(
+ new Visit(VisitKind.VISIT_UNRESOLVED_SUPER_UNARY, operator: operator));
}
@override
- visitEquals(
- Send node,
- Node left,
- Node right,
- arg) {
+ visitEquals(Send node, Node left, Node right, arg) {
visits.add(new Visit(VisitKind.VISIT_EQUALS, left: left, right: right));
apply(left, arg);
apply(right, arg);
}
@override
- visitSuperEquals(
- Send node,
- FunctionElement function,
- Node argument,
- arg) {
+ visitSuperEquals(Send node, FunctionElement function, Node argument, arg) {
visits.add(new Visit(VisitKind.VISIT_SUPER_EQUALS,
element: function, right: argument));
apply(argument, arg);
}
@override
- visitIndexSet(
- Send node,
- Node receiver,
- Node index,
- Node rhs,
- arg) {
+ visitIndexSet(Send node, Node receiver, Node index, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_INDEX_SET,
receiver: receiver, index: index, rhs: rhs));
apply(receiver, arg);
@@ -1304,11 +866,7 @@
@override
visitSuperIndexSet(
- Send node,
- FunctionElement function,
- Node index,
- Node rhs,
- arg) {
+ Send node, FunctionElement function, Node index, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_SUPER_INDEX_SET,
element: function, index: index, rhs: rhs));
apply(index, arg);
@@ -1316,27 +874,17 @@
}
@override
- visitDynamicPropertyCompound(
- Send node,
- Node receiver,
- Name name,
- AssignmentOperator operator,
- Node rhs,
- arg) {
+ visitDynamicPropertyCompound(Send node, Node receiver, Name name,
+ AssignmentOperator operator, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_DYNAMIC_PROPERTY_COMPOUND,
- receiver: receiver, operator: operator, rhs: rhs,
- name: name));
- super.visitDynamicPropertyCompound(
- node, receiver, name, operator, rhs, arg);
+ receiver: receiver, operator: operator, rhs: rhs, name: name));
+ super
+ .visitDynamicPropertyCompound(node, receiver, name, operator, rhs, arg);
}
@override
- visitFinalLocalVariableCompound(
- Send node,
- LocalVariableElement variable,
- AssignmentOperator operator,
- Node rhs,
- arg) {
+ visitFinalLocalVariableCompound(Send node, LocalVariableElement variable,
+ AssignmentOperator operator, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_FINAL_LOCAL_VARIABLE_COMPOUND,
element: variable, operator: operator, rhs: rhs));
apply(rhs, arg);
@@ -1344,31 +892,21 @@
@override
visitFinalLocalVariablePrefix(
- Send node,
- LocalVariableElement variable,
- IncDecOperator operator,
- arg) {
+ Send node, LocalVariableElement variable, IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.VISIT_FINAL_LOCAL_VARIABLE_PREFIX,
element: variable, operator: operator));
}
@override
visitFinalLocalVariablePostfix(
- Send node,
- LocalVariableElement variable,
- IncDecOperator operator,
- arg) {
+ Send node, LocalVariableElement variable, IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.VISIT_FINAL_LOCAL_VARIABLE_POSTFIX,
element: variable, operator: operator));
}
@override
- visitFinalParameterCompound(
- Send node,
- ParameterElement parameter,
- AssignmentOperator operator,
- Node rhs,
- arg) {
+ visitFinalParameterCompound(Send node, ParameterElement parameter,
+ AssignmentOperator operator, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_FINAL_PARAMETER_COMPOUND,
element: parameter, operator: operator, rhs: rhs));
apply(rhs, arg);
@@ -1376,31 +914,21 @@
@override
visitFinalParameterPrefix(
- Send node,
- ParameterElement parameter,
- IncDecOperator operator,
- arg) {
+ Send node, ParameterElement parameter, IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.VISIT_FINAL_PARAMETER_PREFIX,
element: parameter, operator: operator));
}
@override
visitFinalParameterPostfix(
- Send node,
- ParameterElement parameter,
- IncDecOperator operator,
- arg) {
+ Send node, ParameterElement parameter, IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.VISIT_FINAL_PARAMETER_POSTFIX,
element: parameter, operator: operator));
}
@override
- visitFinalStaticFieldCompound(
- Send node,
- FieldElement field,
- AssignmentOperator operator,
- Node rhs,
- arg) {
+ visitFinalStaticFieldCompound(Send node, FieldElement field,
+ AssignmentOperator operator, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_STATIC_FINAL_FIELD_COMPOUND,
element: field, operator: operator, rhs: rhs));
apply(rhs, arg);
@@ -1408,43 +936,29 @@
@override
visitFinalStaticFieldPostfix(
- Send node,
- FieldElement field,
- IncDecOperator operator,
- arg) {
+ Send node, FieldElement field, IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.VISIT_STATIC_FINAL_FIELD_POSTFIX,
element: field, operator: operator));
}
@override
visitFinalStaticFieldPrefix(
- Send node,
- FieldElement field,
- IncDecOperator operator,
- arg) {
+ Send node, FieldElement field, IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.VISIT_STATIC_FINAL_FIELD_PREFIX,
element: field, operator: operator));
}
@override
- visitFinalSuperFieldCompound(
- Send node,
- FieldElement field,
- AssignmentOperator operator,
- Node rhs,
- arg) {
+ visitFinalSuperFieldCompound(Send node, FieldElement field,
+ AssignmentOperator operator, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_SUPER_FINAL_FIELD_COMPOUND,
element: field, operator: operator, rhs: rhs));
apply(rhs, arg);
}
@override
- visitFinalTopLevelFieldCompound(
- Send node,
- FieldElement field,
- AssignmentOperator operator,
- Node rhs,
- arg) {
+ visitFinalTopLevelFieldCompound(Send node, FieldElement field,
+ AssignmentOperator operator, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_TOP_LEVEL_FINAL_FIELD_COMPOUND,
element: field, operator: operator, rhs: rhs));
apply(rhs, arg);
@@ -1452,212 +966,133 @@
@override
visitFinalTopLevelFieldPostfix(
- Send node,
- FieldElement field,
- IncDecOperator operator,
- arg) {
+ Send node, FieldElement field, IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.VISIT_TOP_LEVEL_FINAL_FIELD_POSTFIX,
element: field, operator: operator));
}
@override
visitFinalTopLevelFieldPrefix(
- Send node,
- FieldElement field,
- IncDecOperator operator,
- arg) {
+ Send node, FieldElement field, IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.VISIT_TOP_LEVEL_FINAL_FIELD_PREFIX,
element: field, operator: operator));
}
@override
- visitLocalFunctionCompound(
- Send node,
- LocalFunctionElement function,
- AssignmentOperator operator,
- Node rhs,
- arg) {
+ visitLocalFunctionCompound(Send node, LocalFunctionElement function,
+ AssignmentOperator operator, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_LOCAL_FUNCTION_COMPOUND,
element: function, operator: operator, rhs: rhs));
apply(rhs, arg);
}
@override
- visitLocalVariableCompound(
- Send node,
- LocalVariableElement variable,
- AssignmentOperator operator,
- Node rhs,
- arg) {
+ visitLocalVariableCompound(Send node, LocalVariableElement variable,
+ AssignmentOperator operator, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_LOCAL_VARIABLE_COMPOUND,
element: variable, operator: operator, rhs: rhs));
apply(rhs, arg);
}
@override
- visitParameterCompound(
- Send node,
- ParameterElement parameter,
- AssignmentOperator operator,
- Node rhs,
- arg) {
+ visitParameterCompound(Send node, ParameterElement parameter,
+ AssignmentOperator operator, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_PARAMETER_COMPOUND,
element: parameter, operator: operator, rhs: rhs));
apply(rhs, arg);
}
@override
- visitStaticFieldCompound(
- Send node,
- FieldElement field,
- AssignmentOperator operator,
- Node rhs,
- arg) {
+ visitStaticFieldCompound(Send node, FieldElement field,
+ AssignmentOperator operator, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_STATIC_FIELD_COMPOUND,
element: field, operator: operator, rhs: rhs));
apply(rhs, arg);
}
@override
- visitStaticGetterSetterCompound(
- Send node,
- FunctionElement getter,
- FunctionElement setter,
- AssignmentOperator operator,
- Node rhs,
- arg) {
+ visitStaticGetterSetterCompound(Send node, FunctionElement getter,
+ FunctionElement setter, AssignmentOperator operator, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_STATIC_GETTER_SETTER_COMPOUND,
- operator: operator, rhs: rhs,
- getter: getter, setter: setter));
+ operator: operator, rhs: rhs, getter: getter, setter: setter));
apply(rhs, arg);
}
@override
- visitSuperFieldCompound(
- Send node,
- FieldElement field,
- AssignmentOperator operator,
- Node rhs,
- arg) {
+ visitSuperFieldCompound(Send node, FieldElement field,
+ AssignmentOperator operator, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_SUPER_FIELD_COMPOUND,
element: field, operator: operator, rhs: rhs));
apply(rhs, arg);
}
@override
- visitSuperGetterSetterCompound(
- Send node,
- FunctionElement getter,
- FunctionElement setter,
- AssignmentOperator operator,
- Node rhs,
- arg) {
+ visitSuperGetterSetterCompound(Send node, FunctionElement getter,
+ FunctionElement setter, AssignmentOperator operator, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_SUPER_GETTER_SETTER_COMPOUND,
- operator: operator, rhs: rhs,
- getter: getter, setter: setter));
+ operator: operator, rhs: rhs, getter: getter, setter: setter));
apply(rhs, arg);
}
@override
visitThisPropertyCompound(
- Send node,
- Name name,
- AssignmentOperator operator,
- Node rhs,
- arg) {
+ Send node, Name name, AssignmentOperator operator, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_THIS_PROPERTY_COMPOUND,
name: name, operator: operator, rhs: rhs));
super.visitThisPropertyCompound(node, name, operator, rhs, arg);
}
@override
- visitTopLevelFieldCompound(
- Send node,
- FieldElement field,
- AssignmentOperator operator,
- Node rhs,
- arg) {
+ visitTopLevelFieldCompound(Send node, FieldElement field,
+ AssignmentOperator operator, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_TOP_LEVEL_FIELD_COMPOUND,
element: field, operator: operator, rhs: rhs));
apply(rhs, arg);
}
@override
- visitTopLevelGetterSetterCompound(
- Send node,
- FunctionElement getter,
- FunctionElement setter,
- AssignmentOperator operator,
- Node rhs,
- arg) {
+ visitTopLevelGetterSetterCompound(Send node, FunctionElement getter,
+ FunctionElement setter, AssignmentOperator operator, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_TOP_LEVEL_GETTER_SETTER_COMPOUND,
- operator: operator, rhs: rhs,
- getter: getter, setter: setter));
+ operator: operator, rhs: rhs, getter: getter, setter: setter));
apply(rhs, arg);
}
@override
- visitStaticMethodSetterCompound(
- Send node,
- FunctionElement method,
- FunctionElement setter,
- AssignmentOperator operator,
- Node rhs,
- arg) {
+ visitStaticMethodSetterCompound(Send node, FunctionElement method,
+ FunctionElement setter, AssignmentOperator operator, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_STATIC_METHOD_SETTER_COMPOUND,
- operator: operator, rhs: rhs,
- getter: method, setter: setter));
+ operator: operator, rhs: rhs, getter: method, setter: setter));
apply(rhs, arg);
}
@override
- visitSuperFieldSetterCompound(
- Send node,
- FieldElement field,
- FunctionElement setter,
- AssignmentOperator operator,
- Node rhs,
- arg) {
+ visitSuperFieldSetterCompound(Send node, FieldElement field,
+ FunctionElement setter, AssignmentOperator operator, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_SUPER_FIELD_SETTER_COMPOUND,
- operator: operator, rhs: rhs,
- getter: field, setter: setter));
+ operator: operator, rhs: rhs, getter: field, setter: setter));
apply(rhs, arg);
}
@override
- visitSuperGetterFieldCompound(
- Send node,
- FunctionElement getter,
- FieldElement field,
- AssignmentOperator operator,
- Node rhs,
- arg) {
+ visitSuperGetterFieldCompound(Send node, FunctionElement getter,
+ FieldElement field, AssignmentOperator operator, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_SUPER_GETTER_FIELD_COMPOUND,
- operator: operator, rhs: rhs,
- getter: getter, setter: field));
+ operator: operator, rhs: rhs, getter: getter, setter: field));
apply(rhs, arg);
}
@override
- visitSuperMethodSetterCompound(
- Send node,
- FunctionElement method,
- FunctionElement setter,
- AssignmentOperator operator,
- Node rhs,
- arg) {
+ visitSuperMethodSetterCompound(Send node, FunctionElement method,
+ FunctionElement setter, AssignmentOperator operator, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_SUPER_METHOD_SETTER_COMPOUND,
getter: method, setter: setter, operator: operator, rhs: rhs));
apply(rhs, arg);
}
@override
- visitSuperMethodCompound(
- Send node,
- FunctionElement method,
- AssignmentOperator operator,
- Node rhs,
- arg) {
+ visitSuperMethodCompound(Send node, FunctionElement method,
+ AssignmentOperator operator, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_SUPER_METHOD_COMPOUND,
element: method, operator: operator, rhs: rhs));
apply(rhs, arg);
@@ -1665,31 +1100,21 @@
@override
visitSuperMethodPrefix(
- Send node,
- FunctionElement method,
- IncDecOperator operator,
- arg) {
+ Send node, FunctionElement method, IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.VISIT_SUPER_METHOD_PREFIX,
element: method, operator: operator));
}
@override
visitSuperMethodPostfix(
- Send node,
- FunctionElement method,
- IncDecOperator operator,
- arg) {
+ Send node, FunctionElement method, IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.VISIT_SUPER_METHOD_POSTFIX,
element: method, operator: operator));
}
@override
visitUnresolvedSuperCompound(
- Send node,
- Element element,
- AssignmentOperator operator,
- Node rhs,
- arg) {
+ Send node, Element element, AssignmentOperator operator, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_UNRESOLVED_SUPER_COMPOUND,
operator: operator, rhs: rhs));
apply(rhs, arg);
@@ -1697,45 +1122,29 @@
@override
visitUnresolvedSuperPrefix(
- Send node,
- Element element,
- IncDecOperator operator,
- arg) {
- visits.add(new Visit(VisitKind.VISIT_UNRESOLVED_SUPER_PREFIX,
- operator: operator));
+ Send node, Element element, IncDecOperator operator, arg) {
+ visits.add(
+ new Visit(VisitKind.VISIT_UNRESOLVED_SUPER_PREFIX, operator: operator));
}
@override
visitUnresolvedSuperPostfix(
- Send node,
- Element element,
- IncDecOperator operator,
- arg) {
+ Send node, Element element, IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.VISIT_UNRESOLVED_SUPER_POSTFIX,
operator: operator));
}
@override
- visitTopLevelMethodSetterCompound(
- Send node,
- FunctionElement method,
- FunctionElement setter,
- AssignmentOperator operator,
- Node rhs,
- arg) {
+ visitTopLevelMethodSetterCompound(Send node, FunctionElement method,
+ FunctionElement setter, AssignmentOperator operator, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_TOP_LEVEL_METHOD_SETTER_COMPOUND,
getter: method, setter: setter, operator: operator, rhs: rhs));
apply(rhs, arg);
}
@override
- visitCompoundIndexSet(
- Send node,
- Node receiver,
- Node index,
- AssignmentOperator operator,
- Node rhs,
- arg) {
+ visitCompoundIndexSet(Send node, Node receiver, Node index,
+ AssignmentOperator operator, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_COMPOUND_INDEX_SET,
receiver: receiver, index: index, rhs: rhs, operator: operator));
apply(receiver, arg);
@@ -1753,55 +1162,42 @@
Node rhs,
arg) {
visits.add(new Visit(VisitKind.VISIT_SUPER_COMPOUND_INDEX_SET,
- getter: getter, setter: setter,
- index: index, rhs: rhs, operator: operator));
+ getter: getter,
+ setter: setter,
+ index: index,
+ rhs: rhs,
+ operator: operator));
apply(index, arg);
apply(rhs, arg);
}
@override
- visitClassTypeLiteralCompound(
- Send node,
- ConstantExpression constant,
- AssignmentOperator operator,
- Node rhs,
- arg) {
+ visitClassTypeLiteralCompound(Send node, ConstantExpression constant,
+ AssignmentOperator operator, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_CLASS_TYPE_LITERAL_COMPOUND,
constant: constant.toDartText(), operator: operator, rhs: rhs));
apply(rhs, arg);
}
@override
- visitDynamicTypeLiteralCompound(
- Send node,
- ConstantExpression constant,
- AssignmentOperator operator,
- Node rhs,
- arg) {
+ visitDynamicTypeLiteralCompound(Send node, ConstantExpression constant,
+ AssignmentOperator operator, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_DYNAMIC_TYPE_LITERAL_COMPOUND,
constant: constant.toDartText(), operator: operator, rhs: rhs));
apply(rhs, arg);
}
@override
- visitTypeVariableTypeLiteralCompound(
- Send node,
- TypeVariableElement element,
- AssignmentOperator operator,
- Node rhs,
- arg) {
+ visitTypeVariableTypeLiteralCompound(Send node, TypeVariableElement element,
+ AssignmentOperator operator, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_TYPE_VARIABLE_TYPE_LITERAL_COMPOUND,
element: element, operator: operator, rhs: rhs));
apply(rhs, arg);
}
@override
- visitTypedefTypeLiteralCompound(
- Send node,
- ConstantExpression constant,
- AssignmentOperator operator,
- Node rhs,
- arg) {
+ visitTypedefTypeLiteralCompound(Send node, ConstantExpression constant,
+ AssignmentOperator operator, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_TYPEDEF_TYPE_LITERAL_COMPOUND,
constant: constant.toDartText(), operator: operator, rhs: rhs));
apply(rhs, arg);
@@ -1809,180 +1205,119 @@
@override
visitLocalFunctionPrefix(
- Send node,
- LocalFunctionElement function,
- IncDecOperator operator,
- arg) {
+ Send node, LocalFunctionElement function, IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.VISIT_LOCAL_FUNCTION_PREFIX,
element: function, operator: operator));
}
@override
visitClassTypeLiteralPrefix(
- Send node,
- ConstantExpression constant,
- IncDecOperator operator,
- arg) {
+ Send node, ConstantExpression constant, IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.VISIT_CLASS_TYPE_LITERAL_PREFIX,
constant: constant.toDartText(), operator: operator));
}
@override
visitDynamicTypeLiteralPrefix(
- Send node,
- ConstantExpression constant,
- IncDecOperator operator,
- arg) {
+ Send node, ConstantExpression constant, IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.VISIT_DYNAMIC_TYPE_LITERAL_PREFIX,
constant: constant.toDartText(), operator: operator));
}
@override
visitLocalVariablePrefix(
- Send node,
- LocalVariableElement variable,
- IncDecOperator operator,
- arg) {
+ Send node, LocalVariableElement variable, IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.VISIT_LOCAL_VARIABLE_PREFIX,
element: variable, operator: operator));
}
@override
visitParameterPrefix(
- Send node,
- ParameterElement parameter,
- IncDecOperator operator,
- arg) {
+ Send node, ParameterElement parameter, IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.VISIT_PARAMETER_PREFIX,
element: parameter, operator: operator));
}
@override
visitStaticFieldPrefix(
- Send node,
- FieldElement field,
- IncDecOperator operator,
- arg) {
+ Send node, FieldElement field, IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.VISIT_STATIC_FIELD_PREFIX,
element: field, operator: operator));
}
@override
- visitStaticGetterSetterPrefix(
- Send node,
- FunctionElement getter,
- FunctionElement setter,
- IncDecOperator operator,
- arg) {
+ visitStaticGetterSetterPrefix(Send node, FunctionElement getter,
+ FunctionElement setter, IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.VISIT_STATIC_GETTER_SETTER_PREFIX,
getter: getter, setter: setter, operator: operator));
}
@override
- visitStaticMethodSetterPrefix(
- Send node,
- FunctionElement getter,
- FunctionElement setter,
- IncDecOperator operator,
- arg) {
+ visitStaticMethodSetterPrefix(Send node, FunctionElement getter,
+ FunctionElement setter, IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.VISIT_STATIC_METHOD_SETTER_PREFIX,
getter: getter, setter: setter, operator: operator));
}
@override
- visitSuperFieldFieldCompound(
- Send node,
- FieldElement readField,
- FieldElement writtenField,
- AssignmentOperator operator,
- Node rhs,
- arg) {
+ visitSuperFieldFieldCompound(Send node, FieldElement readField,
+ FieldElement writtenField, AssignmentOperator operator, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_SUPER_FIELD_FIELD_COMPOUND,
getter: readField, setter: writtenField, operator: operator, rhs: rhs));
apply(rhs, arg);
}
@override
- visitSuperFieldFieldPrefix(
- Send node,
- FieldElement readField,
- FieldElement writtenField,
- IncDecOperator operator,
- arg) {
+ visitSuperFieldFieldPrefix(Send node, FieldElement readField,
+ FieldElement writtenField, IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.VISIT_SUPER_FIELD_FIELD_PREFIX,
getter: readField, setter: writtenField, operator: operator));
}
@override
visitSuperFieldPrefix(
- Send node,
- FieldElement field,
- IncDecOperator operator,
- arg) {
+ Send node, FieldElement field, IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.VISIT_SUPER_FIELD_PREFIX,
element: field, operator: operator));
}
@override
visitFinalSuperFieldPrefix(
- Send node,
- FieldElement field,
- IncDecOperator operator,
- arg) {
+ Send node, FieldElement field, IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.VISIT_SUPER_FINAL_FIELD_PREFIX,
element: field, operator: operator));
}
@override
- visitSuperFieldSetterPrefix(
- Send node,
- FieldElement field,
- FunctionElement setter,
- IncDecOperator operator,
- arg) {
+ visitSuperFieldSetterPrefix(Send node, FieldElement field,
+ FunctionElement setter, IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.VISIT_SUPER_FIELD_SETTER_PREFIX,
getter: field, setter: setter, operator: operator));
}
@override
- visitSuperGetterFieldPrefix(
- Send node,
- FunctionElement getter,
- FieldElement field,
- IncDecOperator operator,
- arg) {
+ visitSuperGetterFieldPrefix(Send node, FunctionElement getter,
+ FieldElement field, IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.VISIT_SUPER_GETTER_FIELD_PREFIX,
getter: getter, setter: field, operator: operator));
}
@override
- visitSuperGetterSetterPrefix(
- Send node,
- FunctionElement getter,
- FunctionElement setter,
- IncDecOperator operator,
- arg) {
+ visitSuperGetterSetterPrefix(Send node, FunctionElement getter,
+ FunctionElement setter, IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.VISIT_SUPER_GETTER_SETTER_PREFIX,
getter: getter, setter: setter, operator: operator));
}
@override
- visitSuperMethodSetterPrefix(
- Send node,
- FunctionElement method,
- FunctionElement setter,
- IncDecOperator operator,
- arg) {
+ visitSuperMethodSetterPrefix(Send node, FunctionElement method,
+ FunctionElement setter, IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.VISIT_SUPER_METHOD_SETTER_PREFIX,
getter: method, setter: setter, operator: operator));
}
@override
- visitThisPropertyPrefix(
- Send node,
- Name name,
- IncDecOperator operator,
- arg) {
+ visitThisPropertyPrefix(Send node, Name name, IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.VISIT_THIS_PROPERTY_PREFIX,
name: name, operator: operator));
super.visitThisPropertyPrefix(node, name, operator, arg);
@@ -1990,219 +1325,146 @@
@override
visitTopLevelFieldPrefix(
- Send node,
- FieldElement field,
- IncDecOperator operator,
- arg) {
+ Send node, FieldElement field, IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.VISIT_TOP_LEVEL_FIELD_PREFIX,
element: field, operator: operator));
}
@override
- visitTopLevelGetterSetterPrefix(
- Send node,
- FunctionElement getter,
- FunctionElement setter,
- IncDecOperator operator,
- arg) {
+ visitTopLevelGetterSetterPrefix(Send node, FunctionElement getter,
+ FunctionElement setter, IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.VISIT_TOP_LEVEL_GETTER_SETTER_PREFIX,
getter: getter, setter: setter, operator: operator));
}
@override
- visitTopLevelMethodSetterPrefix(
- Send node,
- FunctionElement method,
- FunctionElement setter,
- IncDecOperator operator,
- arg) {
+ visitTopLevelMethodSetterPrefix(Send node, FunctionElement method,
+ FunctionElement setter, IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.VISIT_TOP_LEVEL_METHOD_SETTER_PREFIX,
getter: method, setter: setter, operator: operator));
}
@override
visitTypeVariableTypeLiteralPrefix(
- Send node,
- TypeVariableElement element,
- IncDecOperator operator,
- arg) {
+ Send node, TypeVariableElement element, IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.VISIT_TYPE_VARIABLE_TYPE_LITERAL_PREFIX,
element: element, operator: operator));
}
@override
visitTypedefTypeLiteralPrefix(
- Send node,
- ConstantExpression constant,
- IncDecOperator operator,
- arg) {
+ Send node, ConstantExpression constant, IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.VISIT_TYPEDEF_TYPE_LITERAL_PREFIX,
constant: constant.toDartText(), operator: operator));
}
@override
visitLocalFunctionPostfix(
- Send node,
- LocalFunctionElement function,
- IncDecOperator operator,
- arg) {
+ Send node, LocalFunctionElement function, IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.VISIT_LOCAL_FUNCTION_POSTFIX,
element: function, operator: operator));
}
@override
visitClassTypeLiteralPostfix(
- Send node,
- ConstantExpression constant,
- IncDecOperator operator,
- arg) {
+ Send node, ConstantExpression constant, IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.VISIT_CLASS_TYPE_LITERAL_POSTFIX,
constant: constant.toDartText(), operator: operator));
}
@override
visitDynamicTypeLiteralPostfix(
- Send node,
- ConstantExpression constant,
- IncDecOperator operator,
- arg) {
+ Send node, ConstantExpression constant, IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.VISIT_DYNAMIC_TYPE_LITERAL_POSTFIX,
constant: constant.toDartText(), operator: operator));
}
@override
visitLocalVariablePostfix(
- Send node,
- LocalVariableElement variable,
- IncDecOperator operator,
- arg) {
+ Send node, LocalVariableElement variable, IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.VISIT_LOCAL_VARIABLE_POSTFIX,
element: variable, operator: operator));
}
@override
visitParameterPostfix(
- Send node,
- ParameterElement parameter,
- IncDecOperator operator,
- arg) {
+ Send node, ParameterElement parameter, IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.VISIT_PARAMETER_POSTFIX,
element: parameter, operator: operator));
}
@override
visitStaticFieldPostfix(
- Send node,
- FieldElement field,
- IncDecOperator operator,
- arg) {
+ Send node, FieldElement field, IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.VISIT_STATIC_FIELD_POSTFIX,
element: field, operator: operator));
}
@override
- visitStaticGetterSetterPostfix(
- Send node,
- FunctionElement getter,
- FunctionElement setter,
- IncDecOperator operator,
- arg) {
+ visitStaticGetterSetterPostfix(Send node, FunctionElement getter,
+ FunctionElement setter, IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.VISIT_STATIC_GETTER_SETTER_POSTFIX,
getter: getter, setter: setter, operator: operator));
}
@override
- visitStaticMethodSetterPostfix(
- Send node,
- FunctionElement getter,
- FunctionElement setter,
- IncDecOperator operator,
- arg) {
+ visitStaticMethodSetterPostfix(Send node, FunctionElement getter,
+ FunctionElement setter, IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.VISIT_STATIC_METHOD_SETTER_POSTFIX,
getter: getter, setter: setter, operator: operator));
}
@override
- visitSuperFieldFieldPostfix(
- Send node,
- FieldElement readField,
- FieldElement writtenField,
- IncDecOperator operator,
- arg) {
+ visitSuperFieldFieldPostfix(Send node, FieldElement readField,
+ FieldElement writtenField, IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.VISIT_SUPER_FIELD_FIELD_POSTFIX,
getter: readField, setter: writtenField, operator: operator));
}
@override
visitSuperFieldPostfix(
- Send node,
- FieldElement field,
- IncDecOperator operator,
- arg) {
+ Send node, FieldElement field, IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.VISIT_SUPER_FIELD_POSTFIX,
element: field, operator: operator));
}
@override
visitFinalSuperFieldPostfix(
- Send node,
- FieldElement field,
- IncDecOperator operator,
- arg) {
+ Send node, FieldElement field, IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.VISIT_SUPER_FINAL_FIELD_POSTFIX,
element: field, operator: operator));
}
@override
- visitSuperFieldSetterPostfix(
- Send node,
- FieldElement field,
- FunctionElement setter,
- IncDecOperator operator,
- arg) {
+ visitSuperFieldSetterPostfix(Send node, FieldElement field,
+ FunctionElement setter, IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.VISIT_SUPER_FIELD_SETTER_POSTFIX,
getter: field, setter: setter, operator: operator));
}
@override
- visitSuperGetterFieldPostfix(
- Send node,
- FunctionElement getter,
- FieldElement field,
- IncDecOperator operator,
- arg) {
+ visitSuperGetterFieldPostfix(Send node, FunctionElement getter,
+ FieldElement field, IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.VISIT_SUPER_GETTER_FIELD_POSTFIX,
getter: getter, setter: field, operator: operator));
}
@override
- visitSuperGetterSetterPostfix(
- Send node,
- FunctionElement getter,
- FunctionElement setter,
- IncDecOperator operator,
- arg) {
+ visitSuperGetterSetterPostfix(Send node, FunctionElement getter,
+ FunctionElement setter, IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.VISIT_SUPER_GETTER_SETTER_POSTFIX,
getter: getter, setter: setter, operator: operator));
}
@override
- visitSuperMethodSetterPostfix(
- Send node,
- FunctionElement method,
- FunctionElement setter,
- IncDecOperator operator,
- arg) {
+ visitSuperMethodSetterPostfix(Send node, FunctionElement method,
+ FunctionElement setter, IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.VISIT_SUPER_METHOD_SETTER_POSTFIX,
getter: method, setter: setter, operator: operator));
}
@override
- visitThisPropertyPostfix(
- Send node,
- Name name,
- IncDecOperator operator,
- arg) {
+ visitThisPropertyPostfix(Send node, Name name, IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.VISIT_THIS_PROPERTY_POSTFIX,
name: name, operator: operator));
super.visitThisPropertyPostfix(node, name, operator, arg);
@@ -2210,129 +1472,85 @@
@override
visitTopLevelFieldPostfix(
- Send node,
- FieldElement field,
- IncDecOperator operator,
- arg) {
+ Send node, FieldElement field, IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.VISIT_TOP_LEVEL_FIELD_POSTFIX,
element: field, operator: operator));
}
@override
- visitTopLevelGetterSetterPostfix(
- Send node,
- FunctionElement getter,
- FunctionElement setter,
- IncDecOperator operator,
- arg) {
+ visitTopLevelGetterSetterPostfix(Send node, FunctionElement getter,
+ FunctionElement setter, IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.VISIT_TOP_LEVEL_GETTER_SETTER_POSTFIX,
getter: getter, setter: setter, operator: operator));
}
@override
- visitTopLevelMethodSetterPostfix(
- Send node,
- FunctionElement method,
- FunctionElement setter,
- IncDecOperator operator,
- arg) {
+ visitTopLevelMethodSetterPostfix(Send node, FunctionElement method,
+ FunctionElement setter, IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.VISIT_TOP_LEVEL_METHOD_SETTER_POSTFIX,
getter: method, setter: setter, operator: operator));
}
@override
visitTypeVariableTypeLiteralPostfix(
- Send node,
- TypeVariableElement element,
- IncDecOperator operator,
- arg) {
+ Send node, TypeVariableElement element, IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.VISIT_TYPE_VARIABLE_TYPE_LITERAL_POSTFIX,
element: element, operator: operator));
}
@override
visitTypedefTypeLiteralPostfix(
- Send node,
- ConstantExpression constant,
- IncDecOperator operator,
- arg) {
+ Send node, ConstantExpression constant, IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.VISIT_TYPEDEF_TYPE_LITERAL_POSTFIX,
constant: constant.toDartText(), operator: operator));
}
@override
- visitUnresolvedCompound(
- Send node,
- ErroneousElement element,
- AssignmentOperator operator,
- Node rhs,
- arg) {
+ visitUnresolvedCompound(Send node, ErroneousElement element,
+ AssignmentOperator operator, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_UNRESOLVED_COMPOUND,
operator: operator, rhs: rhs));
apply(rhs, arg);
}
@override
- visitUnresolvedGet(
- Send node,
- Element element,
- arg) {
+ visitUnresolvedGet(Send node, Element element, arg) {
visits.add(new Visit(VisitKind.VISIT_UNRESOLVED_GET, name: element.name));
}
@override
- visitUnresolvedSet(
- Send node,
- Element element,
- Node rhs,
- arg) {
+ visitUnresolvedSet(Send node, Element element, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_UNRESOLVED_SET,
- name: element.name, rhs: rhs));
+ name: element.name, rhs: rhs));
super.visitUnresolvedSet(node, element, rhs, arg);
}
@override
visitUnresolvedInvoke(
- Send node,
- Element element,
- NodeList arguments,
- Selector selector,
- arg) {
+ Send node, Element element, NodeList arguments, Selector selector, arg) {
visits.add(new Visit(VisitKind.VISIT_UNRESOLVED_INVOKE,
- name: element.name, arguments: arguments));
+ name: element.name, arguments: arguments));
super.visitUnresolvedInvoke(node, element, arguments, selector, arg);
}
@override
visitUnresolvedPostfix(
- Send node,
- ErroneousElement element,
- IncDecOperator operator,
- arg) {
- visits.add(new Visit(
- VisitKind.VISIT_UNRESOLVED_POSTFIX, operator: operator));
+ Send node, ErroneousElement element, IncDecOperator operator, arg) {
+ visits
+ .add(new Visit(VisitKind.VISIT_UNRESOLVED_POSTFIX, operator: operator));
}
@override
visitUnresolvedPrefix(
- Send node,
- ErroneousElement element,
- IncDecOperator operator,
- arg) {
- visits.add(new Visit(
- VisitKind.VISIT_UNRESOLVED_PREFIX, operator: operator));
+ Send node, ErroneousElement element, IncDecOperator operator, arg) {
+ visits
+ .add(new Visit(VisitKind.VISIT_UNRESOLVED_PREFIX, operator: operator));
}
@override
- visitUnresolvedSuperCompoundIndexSet(
- Send node,
- Element element,
- Node index,
- AssignmentOperator operator,
- Node rhs,
- arg) {
- visits.add(new Visit(
- VisitKind.VISIT_UNRESOLVED_SUPER_COMPOUND_INDEX_SET,
+ visitUnresolvedSuperCompoundIndexSet(Send node, Element element, Node index,
+ AssignmentOperator operator, Node rhs, arg) {
+ visits.add(new Visit(VisitKind.VISIT_UNRESOLVED_SUPER_COMPOUND_INDEX_SET,
index: index, operator: operator, rhs: rhs));
apply(index, arg);
apply(rhs, arg);
@@ -2349,123 +1567,87 @@
arg) {
visits.add(new Visit(
VisitKind.VISIT_UNRESOLVED_SUPER_GETTER_COMPOUND_INDEX_SET,
- setter: setter, index: index, operator: operator, rhs: rhs));
+ setter: setter,
+ index: index,
+ operator: operator,
+ rhs: rhs));
apply(index, arg);
apply(rhs, arg);
}
@override
- visitUnresolvedSuperSetterCompoundIndexSet(
- Send node,
- MethodElement getter,
- Element element,
- Node index,
- AssignmentOperator operator,
- Node rhs,
- arg) {
+ visitUnresolvedSuperSetterCompoundIndexSet(Send node, MethodElement getter,
+ Element element, Node index, AssignmentOperator operator, Node rhs, arg) {
visits.add(new Visit(
VisitKind.VISIT_UNRESOLVED_SUPER_SETTER_COMPOUND_INDEX_SET,
- getter: getter, index: index, operator: operator, rhs: rhs));
+ getter: getter,
+ index: index,
+ operator: operator,
+ rhs: rhs));
apply(index, arg);
apply(rhs, arg);
}
@override
visitUnresolvedSuperIndexSet(
- Send node,
- ErroneousElement element,
- Node index,
- Node rhs,
- arg) {
+ Send node, ErroneousElement element, Node index, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_UNRESOLVED_SUPER_INDEX_SET,
- index: index, rhs: rhs));
+ index: index, rhs: rhs));
apply(index, arg);
apply(rhs, arg);
}
@override
visitUnresolvedSuperIndexPostfix(
- Send node,
- Element element,
- Node index,
- IncDecOperator operator,
- arg) {
+ Send node, Element element, Node index, IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.VISIT_UNRESOLVED_SUPER_INDEX_POSTFIX,
- index: index, operator: operator));
+ index: index, operator: operator));
apply(index, arg);
}
@override
- visitUnresolvedSuperGetterIndexPostfix(
- Send node,
- Element element,
- MethodElement setter,
- Node index,
- IncDecOperator operator,
- arg) {
+ visitUnresolvedSuperGetterIndexPostfix(Send node, Element element,
+ MethodElement setter, Node index, IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.VISIT_UNRESOLVED_SUPER_GETTER_INDEX_POSTFIX,
- setter: setter, index: index, operator: operator));
+ setter: setter, index: index, operator: operator));
apply(index, arg);
}
@override
- visitUnresolvedSuperSetterIndexPostfix(
- Send node,
- MethodElement getter,
- Element element,
- Node index,
- IncDecOperator operator,
- arg) {
+ visitUnresolvedSuperSetterIndexPostfix(Send node, MethodElement getter,
+ Element element, Node index, IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.VISIT_UNRESOLVED_SUPER_SETTER_INDEX_POSTFIX,
- getter: getter, index: index, operator: operator));
+ getter: getter, index: index, operator: operator));
apply(index, arg);
}
@override
visitUnresolvedSuperIndexPrefix(
- Send node,
- Element element,
- Node index,
- IncDecOperator operator,
- arg) {
+ Send node, Element element, Node index, IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.VISIT_UNRESOLVED_SUPER_INDEX_PREFIX,
- index: index, operator: operator));
+ index: index, operator: operator));
apply(index, arg);
}
@override
- visitUnresolvedSuperGetterIndexPrefix(
- Send node,
- Element element,
- MethodElement setter,
- Node index,
- IncDecOperator operator,
- arg) {
+ visitUnresolvedSuperGetterIndexPrefix(Send node, Element element,
+ MethodElement setter, Node index, IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.VISIT_UNRESOLVED_SUPER_GETTER_INDEX_PREFIX,
- setter: setter, index: index, operator: operator));
+ setter: setter, index: index, operator: operator));
apply(index, arg);
}
@override
- visitUnresolvedSuperSetterIndexPrefix(
- Send node,
- MethodElement getter,
- Element element,
- Node index,
- IncDecOperator operator,
- arg) {
+ visitUnresolvedSuperSetterIndexPrefix(Send node, MethodElement getter,
+ Element element, Node index, IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.VISIT_UNRESOLVED_SUPER_SETTER_INDEX_PREFIX,
- getter: getter, index: index, operator: operator));
+ getter: getter, index: index, operator: operator));
apply(index, arg);
}
@override
visitIndexPostfix(
- Send node,
- Node receiver,
- Node index,
- IncDecOperator operator,
- arg) {
+ Send node, Node receiver, Node index, IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.VISIT_INDEX_POSTFIX,
receiver: receiver, index: index, operator: operator));
apply(receiver, arg);
@@ -2474,11 +1656,7 @@
@override
visitIndexPrefix(
- Send node,
- Node receiver,
- Node index,
- IncDecOperator operator,
- arg) {
+ Send node, Node receiver, Node index, IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.VISIT_INDEX_PREFIX,
receiver: receiver, index: index, operator: operator));
apply(receiver, arg);
@@ -2494,8 +1672,10 @@
IncDecOperator operator,
arg) {
visits.add(new Visit(VisitKind.VISIT_SUPER_INDEX_POSTFIX,
- getter: indexFunction, setter: indexSetFunction,
- index: index, operator: operator));
+ getter: indexFunction,
+ setter: indexSetFunction,
+ index: index,
+ operator: operator));
apply(index, arg);
}
@@ -2508,56 +1688,42 @@
IncDecOperator operator,
arg) {
visits.add(new Visit(VisitKind.VISIT_SUPER_INDEX_PREFIX,
- getter: indexFunction, setter: indexSetFunction,
- index: index, operator: operator));
+ getter: indexFunction,
+ setter: indexSetFunction,
+ index: index,
+ operator: operator));
apply(index, arg);
}
@override
- visitUnresolvedClassConstructorInvoke(
- NewExpression node,
- Element constructor,
- DartType type,
- NodeList arguments,
- Selector selector,
- arg) {
+ visitUnresolvedClassConstructorInvoke(NewExpression node, Element constructor,
+ DartType type, NodeList arguments, Selector selector, arg) {
// TODO(johnniwinther): Test [type] when it is not `dynamic`.
- visits.add(new Visit(
- VisitKind.VISIT_UNRESOLVED_CLASS_CONSTRUCTOR_INVOKE,
+ visits.add(new Visit(VisitKind.VISIT_UNRESOLVED_CLASS_CONSTRUCTOR_INVOKE,
arguments: arguments));
apply(arguments, arg);
}
@override
- visitUnresolvedConstructorInvoke(
- NewExpression node,
- Element constructor,
- DartType type,
- NodeList arguments,
- Selector selector,
- arg) {
+ visitUnresolvedConstructorInvoke(NewExpression node, Element constructor,
+ DartType type, NodeList arguments, Selector selector, arg) {
// TODO(johnniwinther): Test [type] when it is not `dynamic`.
- visits.add(new Visit(
- VisitKind.VISIT_UNRESOLVED_CONSTRUCTOR_INVOKE,
+ visits.add(new Visit(VisitKind.VISIT_UNRESOLVED_CONSTRUCTOR_INVOKE,
arguments: arguments));
apply(arguments, arg);
}
@override
visitConstConstructorInvoke(
- NewExpression node,
- ConstructedConstantExpression constant,
- arg) {
+ NewExpression node, ConstructedConstantExpression constant, arg) {
visits.add(new Visit(VisitKind.VISIT_CONST_CONSTRUCTOR_INVOKE,
- constant: constant.toDartText()));
+ constant: constant.toDartText()));
super.visitConstConstructorInvoke(node, constant, arg);
}
@override
visitBoolFromEnvironmentConstructorInvoke(
- NewExpression node,
- BoolFromEnvironmentConstantExpression constant,
- arg) {
+ NewExpression node, BoolFromEnvironmentConstantExpression constant, arg) {
visits.add(new Visit(
VisitKind.VISIT_BOOL_FROM_ENVIRONMENT_CONSTRUCTOR_INVOKE,
constant: constant.toDartText()));
@@ -2566,9 +1732,7 @@
@override
visitIntFromEnvironmentConstructorInvoke(
- NewExpression node,
- IntFromEnvironmentConstantExpression constant,
- arg) {
+ NewExpression node, IntFromEnvironmentConstantExpression constant, arg) {
visits.add(new Visit(
VisitKind.VISIT_INT_FROM_ENVIRONMENT_CONSTRUCTOR_INVOKE,
constant: constant.toDartText()));
@@ -2576,10 +1740,8 @@
}
@override
- visitStringFromEnvironmentConstructorInvoke(
- NewExpression node,
- StringFromEnvironmentConstantExpression constant,
- arg) {
+ visitStringFromEnvironmentConstructorInvoke(NewExpression node,
+ StringFromEnvironmentConstantExpression constant, arg) {
visits.add(new Visit(
VisitKind.VISIT_STRING_FROM_ENVIRONMENT_CONSTRUCTOR_INVOKE,
constant: constant.toDartText()));
@@ -2587,31 +1749,30 @@
}
@override
- errorNonConstantConstructorInvoke(
- NewExpression node,
- Element element,
- DartType type,
- NodeList arguments,
- CallStructure callStructure,
- arg) {
+ errorNonConstantConstructorInvoke(NewExpression node, Element element,
+ DartType type, NodeList arguments, CallStructure callStructure, arg) {
visits.add(new Visit(VisitKind.ERROR_NON_CONSTANT_CONSTRUCTOR_INVOKE,
- element: element, type: type,
- arguments: arguments, selector: callStructure));
+ element: element,
+ type: type,
+ arguments: arguments,
+ selector: callStructure));
super.errorNonConstantConstructorInvoke(
node, element, type, arguments, callStructure, arg);
}
@override
visitConstructorIncompatibleInvoke(
- NewExpression node,
- ConstructorElement constructor,
- InterfaceType type,
- NodeList arguments,
- CallStructure callStructure,
- arg) {
+ NewExpression node,
+ ConstructorElement constructor,
+ InterfaceType type,
+ NodeList arguments,
+ CallStructure callStructure,
+ arg) {
visits.add(new Visit(VisitKind.VISIT_CONSTRUCTOR_INCOMPATIBLE_INVOKE,
- element: constructor, type: type,
- arguments: arguments, selector: callStructure));
+ element: constructor,
+ type: type,
+ arguments: arguments,
+ selector: callStructure));
super.visitConstructorIncompatibleInvoke(
node, constructor, type, arguments, callStructure, arg);
}
@@ -2624,8 +1785,7 @@
NodeList arguments,
CallStructure callStructure,
arg) {
- visits.add(new Visit(
- VisitKind.VISIT_FACTORY_CONSTRUCTOR_INVOKE,
+ visits.add(new Visit(VisitKind.VISIT_FACTORY_CONSTRUCTOR_INVOKE,
element: constructor,
type: type,
arguments: arguments,
@@ -2641,8 +1801,7 @@
NodeList arguments,
CallStructure callStructure,
arg) {
- visits.add(new Visit(
- VisitKind.VISIT_GENERATIVE_CONSTRUCTOR_INVOKE,
+ visits.add(new Visit(VisitKind.VISIT_GENERATIVE_CONSTRUCTOR_INVOKE,
element: constructor,
type: type,
arguments: arguments,
@@ -2660,8 +1819,7 @@
NodeList arguments,
CallStructure callStructure,
arg) {
- visits.add(new Visit(
- VisitKind.VISIT_REDIRECTING_FACTORY_CONSTRUCTOR_INVOKE,
+ visits.add(new Visit(VisitKind.VISIT_REDIRECTING_FACTORY_CONSTRUCTOR_INVOKE,
element: constructor,
type: type,
target: effectiveTarget,
@@ -2696,8 +1854,7 @@
NodeList arguments,
CallStructure callStructure,
arg) {
- visits.add(new Visit(
- VisitKind.VISIT_ABSTRACT_CLASS_CONSTRUCTOR_INVOKE,
+ visits.add(new Visit(VisitKind.VISIT_ABSTRACT_CLASS_CONSTRUCTOR_INVOKE,
element: constructor,
type: type,
arguments: arguments,
@@ -2723,283 +1880,183 @@
}
@override
- visitUnresolvedStaticGetterCompound(
- Send node,
- Element element,
- MethodElement setter,
- AssignmentOperator operator,
- Node rhs,
- arg) {
+ visitUnresolvedStaticGetterCompound(Send node, Element element,
+ MethodElement setter, AssignmentOperator operator, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_UNRESOLVED_STATIC_GETTER_COMPOUND,
setter: setter, operator: operator, rhs: rhs));
apply(rhs, arg);
}
@override
- visitUnresolvedTopLevelGetterCompound(
- Send node,
- Element element,
- MethodElement setter,
- AssignmentOperator operator,
- Node rhs,
- arg) {
+ visitUnresolvedTopLevelGetterCompound(Send node, Element element,
+ MethodElement setter, AssignmentOperator operator, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_UNRESOLVED_TOP_LEVEL_GETTER_COMPOUND,
setter: setter, operator: operator, rhs: rhs));
apply(rhs, arg);
}
@override
- visitUnresolvedStaticSetterCompound(
- Send node,
- MethodElement getter,
- Element element,
- AssignmentOperator operator,
- Node rhs,
- arg) {
+ visitUnresolvedStaticSetterCompound(Send node, MethodElement getter,
+ Element element, AssignmentOperator operator, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_UNRESOLVED_STATIC_SETTER_COMPOUND,
getter: getter, operator: operator, rhs: rhs));
apply(rhs, arg);
}
@override
- visitUnresolvedTopLevelSetterCompound(
- Send node,
- MethodElement getter,
- Element element,
- AssignmentOperator operator,
- Node rhs,
- arg) {
+ visitUnresolvedTopLevelSetterCompound(Send node, MethodElement getter,
+ Element element, AssignmentOperator operator, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_UNRESOLVED_TOP_LEVEL_SETTER_COMPOUND,
getter: getter, operator: operator, rhs: rhs));
apply(rhs, arg);
}
@override
- visitStaticMethodCompound(
- Send node,
- MethodElement method,
- AssignmentOperator operator,
- Node rhs,
- arg) {
+ visitStaticMethodCompound(Send node, MethodElement method,
+ AssignmentOperator operator, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_STATIC_METHOD_COMPOUND,
element: method, operator: operator, rhs: rhs));
apply(rhs, arg);
}
@override
- visitTopLevelMethodCompound(
- Send node,
- MethodElement method,
- AssignmentOperator operator,
- Node rhs,
- arg) {
+ visitTopLevelMethodCompound(Send node, MethodElement method,
+ AssignmentOperator operator, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_TOP_LEVEL_METHOD_COMPOUND,
element: method, operator: operator, rhs: rhs));
apply(rhs, arg);
}
@override
- visitUnresolvedStaticGetterPrefix(
- Send node,
- Element element,
- MethodElement setter,
- IncDecOperator operator,
- arg) {
+ visitUnresolvedStaticGetterPrefix(Send node, Element element,
+ MethodElement setter, IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.VISIT_UNRESOLVED_STATIC_GETTER_PREFIX,
setter: setter, operator: operator));
}
@override
- visitUnresolvedTopLevelGetterPrefix(
- Send node,
- Element element,
- MethodElement setter,
- IncDecOperator operator,
- arg) {
+ visitUnresolvedTopLevelGetterPrefix(Send node, Element element,
+ MethodElement setter, IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.VISIT_UNRESOLVED_TOP_LEVEL_GETTER_PREFIX,
setter: setter, operator: operator));
}
@override
- visitUnresolvedStaticSetterPrefix(
- Send node,
- MethodElement getter,
- Element element,
- IncDecOperator operator,
- arg) {
+ visitUnresolvedStaticSetterPrefix(Send node, MethodElement getter,
+ Element element, IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.VISIT_UNRESOLVED_STATIC_SETTER_PREFIX,
getter: getter, operator: operator));
}
@override
- visitUnresolvedTopLevelSetterPrefix(
- Send node,
- MethodElement getter,
- Element element,
- IncDecOperator operator,
- arg) {
+ visitUnresolvedTopLevelSetterPrefix(Send node, MethodElement getter,
+ Element element, IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.VISIT_UNRESOLVED_TOP_LEVEL_SETTER_PREFIX,
getter: getter, operator: operator));
}
@override
visitStaticMethodPrefix(
- Send node,
- MethodElement method,
- IncDecOperator operator,
- arg) {
+ Send node, MethodElement method, IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.VISIT_STATIC_METHOD_PREFIX,
element: method, operator: operator));
}
@override
visitTopLevelMethodPrefix(
- Send node,
- MethodElement method,
- IncDecOperator operator,
- arg) {
+ Send node, MethodElement method, IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.VISIT_TOP_LEVEL_METHOD_PREFIX,
element: method, operator: operator));
}
@override
- visitUnresolvedStaticGetterPostfix(
- Send node,
- Element element,
- MethodElement setter,
- IncDecOperator operator,
- arg) {
+ visitUnresolvedStaticGetterPostfix(Send node, Element element,
+ MethodElement setter, IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.VISIT_UNRESOLVED_STATIC_GETTER_POSTFIX,
setter: setter, operator: operator));
}
@override
- visitUnresolvedTopLevelGetterPostfix(
- Send node,
- Element element,
- MethodElement setter,
- IncDecOperator operator,
- arg) {
+ visitUnresolvedTopLevelGetterPostfix(Send node, Element element,
+ MethodElement setter, IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.VISIT_UNRESOLVED_TOP_LEVEL_GETTER_POSTFIX,
setter: setter, operator: operator));
}
@override
- visitUnresolvedStaticSetterPostfix(
- Send node,
- MethodElement getter,
- Element element,
- IncDecOperator operator,
- arg) {
+ visitUnresolvedStaticSetterPostfix(Send node, MethodElement getter,
+ Element element, IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.VISIT_UNRESOLVED_STATIC_SETTER_POSTFIX,
getter: getter, operator: operator));
}
@override
- visitUnresolvedTopLevelSetterPostfix(
- Send node,
- MethodElement getter,
- Element element,
- IncDecOperator operator,
- arg) {
+ visitUnresolvedTopLevelSetterPostfix(Send node, MethodElement getter,
+ Element element, IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.VISIT_UNRESOLVED_TOP_LEVEL_SETTER_POSTFIX,
getter: getter, operator: operator));
}
@override
visitStaticMethodPostfix(
- Send node,
- MethodElement method,
- IncDecOperator operator,
- arg) {
+ Send node, MethodElement method, IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.VISIT_STATIC_METHOD_POSTFIX,
element: method, operator: operator));
}
@override
visitTopLevelMethodPostfix(
- Send node,
- MethodElement method,
- IncDecOperator operator,
- arg) {
+ Send node, MethodElement method, IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.VISIT_TOP_LEVEL_METHOD_POSTFIX,
element: method, operator: operator));
}
@override
- visitUnresolvedSuperGetterCompound(
- Send node, Element element,
- MethodElement setter,
- AssignmentOperator operator,
- Node rhs,
- arg) {
+ visitUnresolvedSuperGetterCompound(Send node, Element element,
+ MethodElement setter, AssignmentOperator operator, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_UNRESOLVED_SUPER_GETTER_COMPOUND,
setter: setter, operator: operator, rhs: rhs));
apply(rhs, arg);
}
@override
- visitUnresolvedSuperGetterPostfix(
- Send node,
- Element element,
- MethodElement setter,
- IncDecOperator operator,
- arg) {
+ visitUnresolvedSuperGetterPostfix(Send node, Element element,
+ MethodElement setter, IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.VISIT_UNRESOLVED_SUPER_GETTER_POSTFIX,
setter: setter, operator: operator));
}
@override
- visitUnresolvedSuperGetterPrefix(
- Send node,
- Element element,
- MethodElement setter,
- IncDecOperator operator,
- arg) {
+ visitUnresolvedSuperGetterPrefix(Send node, Element element,
+ MethodElement setter, IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.VISIT_UNRESOLVED_SUPER_GETTER_PREFIX,
setter: setter, operator: operator));
}
@override
- visitUnresolvedSuperSetterCompound(
- Send node, MethodElement getter,
- Element element,
- AssignmentOperator operator,
- Node rhs,
- arg) {
+ visitUnresolvedSuperSetterCompound(Send node, MethodElement getter,
+ Element element, AssignmentOperator operator, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_UNRESOLVED_SUPER_SETTER_COMPOUND,
getter: getter, operator: operator, rhs: rhs));
apply(rhs, arg);
}
@override
- visitUnresolvedSuperSetterPostfix(
- Send node,
- MethodElement getter,
- Element element,
- IncDecOperator operator,
- arg) {
+ visitUnresolvedSuperSetterPostfix(Send node, MethodElement getter,
+ Element element, IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.VISIT_UNRESOLVED_SUPER_SETTER_POSTFIX,
getter: getter, operator: operator));
}
@override
- visitUnresolvedSuperSetterPrefix(
- Send node,
- MethodElement getter,
- Element element,
- IncDecOperator operator,
- arg) {
+ visitUnresolvedSuperSetterPrefix(Send node, MethodElement getter,
+ Element element, IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.VISIT_UNRESOLVED_SUPER_SETTER_PREFIX,
getter: getter, operator: operator));
}
@override
- visitIfNotNullDynamicPropertyGet(
- Send node,
- Node receiver,
- Name name,
- arg) {
+ visitIfNotNullDynamicPropertyGet(Send node, Node receiver, Name name, arg) {
visits.add(new Visit(VisitKind.VISIT_IF_NOT_NULL_DYNAMIC_PROPERTY_GET,
receiver: receiver, name: name));
super.visitIfNotNullDynamicPropertyGet(node, receiver, name, arg);
@@ -3007,11 +2064,7 @@
@override
visitIfNotNullDynamicPropertySet(
- Send node,
- Node receiver,
- Name name,
- Node rhs,
- arg) {
+ Send node, Node receiver, Name name, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_IF_NOT_NULL_DYNAMIC_PROPERTY_SET,
receiver: receiver, name: name, rhs: rhs));
super.visitIfNotNullDynamicPropertySet(node, receiver, name, rhs, arg);
@@ -3019,11 +2072,7 @@
@override
visitIfNotNullDynamicPropertyInvoke(
- Send node,
- Node receiver,
- NodeList arguments,
- Selector selector,
- arg) {
+ Send node, Node receiver, NodeList arguments, Selector selector, arg) {
visits.add(new Visit(VisitKind.VISIT_IF_NOT_NULL_DYNAMIC_PROPERTY_INVOKE,
receiver: receiver, selector: selector, arguments: arguments));
super.visitIfNotNullDynamicPropertyInvoke(
@@ -3032,11 +2081,7 @@
@override
visitIfNotNullDynamicPropertyPrefix(
- Send node,
- Node receiver,
- Name name,
- IncDecOperator operator,
- arg) {
+ Send node, Node receiver, Name name, IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.VISIT_IF_NOT_NULL_DYNAMIC_PROPERTY_PREFIX,
receiver: receiver, name: name, operator: operator));
super.visitIfNotNullDynamicPropertyPrefix(
@@ -3045,11 +2090,7 @@
@override
visitIfNotNullDynamicPropertyPostfix(
- Send node,
- Node receiver,
- Name name,
- IncDecOperator operator,
- arg) {
+ Send node, Node receiver, Name name, IncDecOperator operator, arg) {
visits.add(new Visit(VisitKind.VISIT_IF_NOT_NULL_DYNAMIC_PROPERTY_POSTFIX,
receiver: receiver, name: name, operator: operator));
super.visitIfNotNullDynamicPropertyPostfix(
@@ -3057,13 +2098,8 @@
}
@override
- visitIfNotNullDynamicPropertyCompound(
- Send node,
- Node receiver,
- Name name,
- AssignmentOperator operator,
- Node rhs,
- arg) {
+ visitIfNotNullDynamicPropertyCompound(Send node, Node receiver, Name name,
+ AssignmentOperator operator, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_IF_NOT_NULL_DYNAMIC_PROPERTY_COMPOUND,
receiver: receiver, name: name, operator: operator, rhs: rhs));
super.visitIfNotNullDynamicPropertyCompound(
@@ -3071,51 +2107,34 @@
}
@override
- visitIfNull(
- Send node,
- Node left,
- Node right,
- arg) {
+ visitIfNull(Send node, Node left, Node right, arg) {
visits.add(new Visit(VisitKind.VISIT_IF_NULL, left: left, right: right));
super.visitIfNull(node, left, right, arg);
}
@override
- visitConstantGet(
- Send node,
- ConstantExpression constant,
- arg) {
+ visitConstantGet(Send node, ConstantExpression constant, arg) {
visits.add(new Visit(VisitKind.VISIT_CONSTANT_GET,
constant: constant.toDartText()));
super.visitConstantGet(node, constant, arg);
}
@override
- visitConstantInvoke(
- Send node,
- ConstantExpression constant,
- NodeList arguments,
- CallStructure callStructure,
- arg) {
+ visitConstantInvoke(Send node, ConstantExpression constant,
+ NodeList arguments, CallStructure callStructure, arg) {
visits.add(new Visit(VisitKind.VISIT_CONSTANT_INVOKE,
constant: constant.toDartText()));
super.visitConstantInvoke(node, constant, arguments, callStructure, arg);
}
@override
- previsitDeferredAccess(
- Send node,
- PrefixElement prefix,
- arg) {
+ previsitDeferredAccess(Send node, PrefixElement prefix, arg) {
visits.add(new Visit(VisitKind.PREVISIT_DEFERRED_ACCESS, element: prefix));
}
@override
visitClassTypeLiteralSetIfNull(
- Send node,
- ConstantExpression constant,
- Node rhs,
- arg) {
+ Send node, ConstantExpression constant, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_CLASS_TYPE_LITERAL_SET_IF_NULL,
constant: constant.toDartText(), rhs: rhs));
super.visitClassTypeLiteralSetIfNull(node, constant, rhs, arg);
@@ -3123,11 +2142,7 @@
@override
visitDynamicPropertySetIfNull(
- Send node,
- Node receiver,
- Name name,
- Node rhs,
- arg) {
+ Send node, Node receiver, Name name, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_DYNAMIC_PROPERTY_SET_IF_NULL,
receiver: receiver, name: name, rhs: rhs));
super.visitDynamicPropertySetIfNull(node, receiver, name, rhs, arg);
@@ -3135,10 +2150,7 @@
@override
visitDynamicTypeLiteralSetIfNull(
- Send node,
- ConstantExpression constant,
- Node rhs,
- arg) {
+ Send node, ConstantExpression constant, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_DYNAMIC_TYPE_LITERAL_SET_IF_NULL,
constant: constant.toDartText(), rhs: rhs));
super.visitDynamicTypeLiteralSetIfNull(node, constant, rhs, arg);
@@ -3146,10 +2158,7 @@
@override
visitFinalLocalVariableSetIfNull(
- Send node,
- LocalVariableElement variable,
- Node rhs,
- arg) {
+ Send node, LocalVariableElement variable, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_FINAL_LOCAL_VARIABLE_SET_IF_NULL,
element: variable, rhs: rhs));
super.visitFinalLocalVariableSetIfNull(node, variable, rhs, arg);
@@ -3157,32 +2166,21 @@
@override
visitFinalParameterSetIfNull(
- Send node,
- ParameterElement parameter,
- Node rhs,
- arg) {
+ Send node, ParameterElement parameter, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_FINAL_PARAMETER_SET_IF_NULL,
element: parameter, rhs: rhs));
super.visitFinalParameterSetIfNull(node, parameter, rhs, arg);
}
@override
- visitFinalStaticFieldSetIfNull(
- Send node,
- FieldElement field,
- Node rhs,
- arg) {
+ visitFinalStaticFieldSetIfNull(Send node, FieldElement field, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_STATIC_FINAL_FIELD_SET_IF_NULL,
element: field, rhs: rhs));
super.visitFinalStaticFieldSetIfNull(node, field, rhs, arg);
}
@override
- visitFinalSuperFieldSetIfNull(
- Send node,
- FieldElement field,
- Node rhs,
- arg) {
+ visitFinalSuperFieldSetIfNull(Send node, FieldElement field, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_SUPER_FINAL_FIELD_SET_IF_NULL,
element: field, rhs: rhs));
super.visitFinalSuperFieldSetIfNull(node, field, rhs, arg);
@@ -3190,10 +2188,7 @@
@override
visitFinalTopLevelFieldSetIfNull(
- Send node,
- FieldElement field,
- Node rhs,
- arg) {
+ Send node, FieldElement field, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_TOP_LEVEL_FINAL_FIELD_SET_IF_NULL,
element: field, rhs: rhs));
super.visitFinalTopLevelFieldSetIfNull(node, field, rhs, arg);
@@ -3201,24 +2196,19 @@
@override
visitIfNotNullDynamicPropertySetIfNull(
- Send node,
- Node receiver,
- Name name,
- Node rhs,
- arg) {
+ Send node, Node receiver, Name name, Node rhs, arg) {
visits.add(new Visit(
VisitKind.VISIT_IF_NOT_NULL_DYNAMIC_PROPERTY_SET_IF_NULL,
- receiver: receiver, name: name, rhs: rhs));
- super.visitIfNotNullDynamicPropertySetIfNull(
- node, receiver, name, rhs, arg);
+ receiver: receiver,
+ name: name,
+ rhs: rhs));
+ super
+ .visitIfNotNullDynamicPropertySetIfNull(node, receiver, name, rhs, arg);
}
@override
visitLocalFunctionSetIfNull(
- Send node,
- LocalFunctionElement function,
- Node rhs,
- arg) {
+ Send node, LocalFunctionElement function, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_LOCAL_FUNCTION_SET_IF_NULL,
element: function, rhs: rhs));
super.visitLocalFunctionSetIfNull(node, function, rhs, arg);
@@ -3226,10 +2216,7 @@
@override
visitLocalVariableSetIfNull(
- Send node,
- LocalVariableElement variable,
- Node rhs,
- arg) {
+ Send node, LocalVariableElement variable, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_LOCAL_VARIABLE_SET_IF_NULL,
element: variable, rhs: rhs));
super.visitLocalVariableSetIfNull(node, variable, rhs, arg);
@@ -3237,44 +2224,29 @@
@override
visitParameterSetIfNull(
- Send node,
- ParameterElement parameter,
- Node rhs,
- arg) {
+ Send node, ParameterElement parameter, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_PARAMETER_SET_IF_NULL,
element: parameter, rhs: rhs));
super.visitParameterSetIfNull(node, parameter, rhs, arg);
}
@override
- visitStaticFieldSetIfNull(
- Send node,
- FieldElement field,
- Node rhs,
- arg) {
+ visitStaticFieldSetIfNull(Send node, FieldElement field, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_STATIC_FIELD_SET_IF_NULL,
element: field, rhs: rhs));
super.visitStaticFieldSetIfNull(node, field, rhs, arg);
}
@override
- visitStaticGetterSetterSetIfNull(
- Send node,
- FunctionElement getter,
- FunctionElement setter,
- Node rhs,
- arg) {
+ visitStaticGetterSetterSetIfNull(Send node, FunctionElement getter,
+ FunctionElement setter, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_STATIC_GETTER_SETTER_SET_IF_NULL,
getter: getter, setter: setter, rhs: rhs));
super.visitStaticGetterSetterSetIfNull(node, getter, setter, rhs, arg);
}
@override
- visitStaticMethodSetIfNull(
- Send node,
- FunctionElement method,
- Node rhs,
- arg) {
+ visitStaticMethodSetIfNull(Send node, FunctionElement method, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_STATIC_METHOD_SET_IF_NULL,
element: method, rhs: rhs));
super.visitStaticMethodSetIfNull(node, method, rhs, arg);
@@ -3282,35 +2254,23 @@
@override
visitStaticMethodSetterSetIfNull(
- Send node,
- MethodElement method,
- MethodElement setter,
- Node rhs,
- arg) {
+ Send node, MethodElement method, MethodElement setter, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_STATIC_METHOD_SETTER_SET_IF_NULL,
getter: method, setter: setter, rhs: rhs));
super.visitStaticMethodSetterSetIfNull(node, method, setter, rhs, arg);
}
@override
- visitSuperFieldFieldSetIfNull(
- Send node,
- FieldElement readField,
- FieldElement writtenField,
- Node rhs,
- arg) {
+ visitSuperFieldFieldSetIfNull(Send node, FieldElement readField,
+ FieldElement writtenField, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_SUPER_FIELD_FIELD_SET_IF_NULL,
getter: readField, setter: writtenField, rhs: rhs));
- super.visitSuperFieldFieldSetIfNull(
- node, readField, writtenField, rhs, arg);
+ super
+ .visitSuperFieldFieldSetIfNull(node, readField, writtenField, rhs, arg);
}
@override
- visitSuperFieldSetIfNull(
- Send node,
- FieldElement field,
- Node rhs,
- arg) {
+ visitSuperFieldSetIfNull(Send node, FieldElement field, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_SUPER_FIELD_SET_IF_NULL,
element: field, rhs: rhs));
super.visitSuperFieldSetIfNull(node, field, rhs, arg);
@@ -3318,11 +2278,7 @@
@override
visitSuperFieldSetterSetIfNull(
- Send node,
- FieldElement field,
- FunctionElement setter,
- Node rhs,
- arg) {
+ Send node, FieldElement field, FunctionElement setter, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_SUPER_FIELD_SETTER_SET_IF_NULL,
getter: field, setter: setter, rhs: rhs));
super.visitSuperFieldSetterSetIfNull(node, field, setter, rhs, arg);
@@ -3330,80 +2286,52 @@
@override
visitSuperGetterFieldSetIfNull(
- Send node,
- FunctionElement getter,
- FieldElement field,
- Node rhs,
- arg) {
+ Send node, FunctionElement getter, FieldElement field, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_SUPER_GETTER_FIELD_SET_IF_NULL,
getter: getter, setter: field, rhs: rhs));
super.visitSuperGetterFieldSetIfNull(node, getter, field, rhs, arg);
}
@override
- visitSuperGetterSetterSetIfNull(
- Send node,
- FunctionElement getter,
- FunctionElement setter,
- Node rhs,
- arg) {
+ visitSuperGetterSetterSetIfNull(Send node, FunctionElement getter,
+ FunctionElement setter, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_SUPER_GETTER_SETTER_SET_IF_NULL,
getter: getter, setter: setter, rhs: rhs));
super.visitSuperGetterSetterSetIfNull(node, getter, setter, rhs, arg);
}
@override
- visitSuperMethodSetIfNull(
- Send node,
- FunctionElement method,
- Node rhs,
- arg) {
+ visitSuperMethodSetIfNull(Send node, FunctionElement method, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_SUPER_METHOD_SET_IF_NULL,
element: method, rhs: rhs));
super.visitSuperMethodSetIfNull(node, method, rhs, arg);
}
@override
- visitSuperMethodSetterSetIfNull(
- Send node,
- FunctionElement method,
- FunctionElement setter,
- Node rhs,
- arg) {
+ visitSuperMethodSetterSetIfNull(Send node, FunctionElement method,
+ FunctionElement setter, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_SUPER_METHOD_SETTER_SET_IF_NULL,
getter: method, setter: setter, rhs: rhs));
super.visitSuperMethodSetterSetIfNull(node, method, setter, rhs, arg);
}
@override
- visitThisPropertySetIfNull(
- Send node,
- Name name,
- Node rhs,
- arg) {
+ visitThisPropertySetIfNull(Send node, Name name, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_THIS_PROPERTY_SET_IF_NULL,
name: name, rhs: rhs));
super.visitThisPropertySetIfNull(node, name, rhs, arg);
}
@override
- visitTopLevelFieldSetIfNull(
- Send node,
- FieldElement field,
- Node rhs,
- arg) {
+ visitTopLevelFieldSetIfNull(Send node, FieldElement field, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_TOP_LEVEL_FIELD_SET_IF_NULL,
element: field, rhs: rhs));
super.visitTopLevelFieldSetIfNull(node, field, rhs, arg);
}
@override
- visitTopLevelGetterSetterSetIfNull(
- Send node,
- FunctionElement getter,
- FunctionElement setter,
- Node rhs,
- arg) {
+ visitTopLevelGetterSetterSetIfNull(Send node, FunctionElement getter,
+ FunctionElement setter, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_TOP_LEVEL_GETTER_SETTER_SET_IF_NULL,
getter: getter, setter: setter, rhs: rhs));
super.visitTopLevelGetterSetterSetIfNull(node, getter, setter, rhs, arg);
@@ -3411,22 +2339,15 @@
@override
visitTopLevelMethodSetIfNull(
- Send node,
- FunctionElement method,
- Node rhs,
- arg) {
+ Send node, FunctionElement method, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_TOP_LEVEL_METHOD_SET_IF_NULL,
element: method, rhs: rhs));
super.visitTopLevelMethodSetIfNull(node, method, rhs, arg);
}
@override
- visitTopLevelMethodSetterSetIfNull(
- Send node,
- FunctionElement method,
- FunctionElement setter,
- Node rhs,
- arg) {
+ visitTopLevelMethodSetterSetIfNull(Send node, FunctionElement method,
+ FunctionElement setter, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_TOP_LEVEL_METHOD_SETTER_SET_IF_NULL,
getter: method, setter: setter, rhs: rhs));
super.visitTopLevelMethodSetterSetIfNull(node, method, setter, rhs, arg);
@@ -3434,10 +2355,7 @@
@override
visitTypeVariableTypeLiteralSetIfNull(
- Send node,
- TypeVariableElement element,
- Node rhs,
- arg) {
+ Send node, TypeVariableElement element, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_TYPE_VARIABLE_TYPE_LITERAL_SET_IF_NULL,
element: element, rhs: rhs));
super.visitTypeVariableTypeLiteralSetIfNull(node, element, rhs, arg);
@@ -3445,21 +2363,14 @@
@override
visitTypedefTypeLiteralSetIfNull(
- Send node,
- ConstantExpression constant,
- Node rhs,
- arg) {
+ Send node, ConstantExpression constant, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_TYPEDEF_TYPE_LITERAL_SET_IF_NULL,
constant: constant.toDartText(), rhs: rhs));
super.visitTypedefTypeLiteralSetIfNull(node, constant, rhs, arg);
}
@override
- visitUnresolvedSetIfNull(
- Send node,
- Element element,
- Node rhs,
- arg) {
+ visitUnresolvedSetIfNull(Send node, Element element, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_UNRESOLVED_SET_IF_NULL,
name: element.name, rhs: rhs));
super.visitUnresolvedSetIfNull(node, element, rhs, arg);
@@ -3467,11 +2378,7 @@
@override
visitUnresolvedStaticGetterSetIfNull(
- Send node,
- Element element,
- MethodElement setter,
- Node rhs,
- arg) {
+ Send node, Element element, MethodElement setter, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_UNRESOLVED_STATIC_GETTER_SET_IF_NULL,
setter: setter, rhs: rhs));
super.visitUnresolvedStaticGetterSetIfNull(node, element, setter, rhs, arg);
@@ -3479,11 +2386,7 @@
@override
visitUnresolvedStaticSetterSetIfNull(
- Send node,
- MethodElement getter,
- Element element,
- Node rhs,
- arg) {
+ Send node, MethodElement getter, Element element, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_UNRESOLVED_STATIC_SETTER_SET_IF_NULL,
getter: getter, rhs: rhs));
super.visitUnresolvedStaticSetterSetIfNull(node, getter, element, rhs, arg);
@@ -3491,22 +2394,14 @@
@override
visitUnresolvedSuperGetterSetIfNull(
- Send node,
- Element element,
- MethodElement setter,
- Node rhs,
- arg) {
+ Send node, Element element, MethodElement setter, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_UNRESOLVED_SUPER_GETTER_SET_IF_NULL,
setter: setter, rhs: rhs));
super.visitUnresolvedSuperGetterSetIfNull(node, element, setter, rhs, arg);
}
@override
- visitUnresolvedSuperSetIfNull(
- Send node,
- Element element,
- Node rhs,
- arg) {
+ visitUnresolvedSuperSetIfNull(Send node, Element element, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_UNRESOLVED_SUPER_SET_IF_NULL,
name: element.name, rhs: rhs));
super.visitUnresolvedSuperSetIfNull(node, element, rhs, arg);
@@ -3514,11 +2409,7 @@
@override
visitUnresolvedSuperSetterSetIfNull(
- Send node,
- MethodElement getter,
- Element element,
- Node rhs,
- arg) {
+ Send node, MethodElement getter, Element element, Node rhs, arg) {
visits.add(new Visit(VisitKind.VISIT_UNRESOLVED_SUPER_SETTER_SET_IF_NULL,
getter: getter, rhs: rhs));
super.visitUnresolvedSuperSetterSetIfNull(node, getter, element, rhs, arg);
@@ -3526,112 +2417,78 @@
@override
visitUnresolvedTopLevelGetterSetIfNull(
- Send node,
- Element element,
- MethodElement setter,
- Node rhs,
- arg) {
+ Send node, Element element, MethodElement setter, Node rhs, arg) {
visits.add(new Visit(
VisitKind.VISIT_UNRESOLVED_TOP_LEVEL_GETTER_SET_IF_NULL,
- setter: setter, rhs: rhs));
+ setter: setter,
+ rhs: rhs));
super.visitUnresolvedTopLevelGetterSetIfNull(
node, element, setter, rhs, arg);
}
@override
visitUnresolvedTopLevelSetterSetIfNull(
- Send node,
- MethodElement getter,
- Element element,
- Node rhs,
- arg) {
+ Send node, MethodElement getter, Element element, Node rhs, arg) {
visits.add(new Visit(
VisitKind.VISIT_UNRESOLVED_TOP_LEVEL_SETTER_SET_IF_NULL,
- getter: getter, rhs: rhs));
+ getter: getter,
+ rhs: rhs));
super.visitUnresolvedTopLevelSetterSetIfNull(
node, getter, element, rhs, arg);
}
@override
- visitIndexSetIfNull(
- SendSet node,
- Node receiver,
- Node index,
- Node rhs,
- arg) {
- visits.add(new Visit(
- VisitKind.VISIT_INDEX_SET_IF_NULL,
+ visitIndexSetIfNull(SendSet node, Node receiver, Node index, Node rhs, arg) {
+ visits.add(new Visit(VisitKind.VISIT_INDEX_SET_IF_NULL,
receiver: receiver, index: index, rhs: rhs));
super.visitIndexSetIfNull(node, receiver, index, rhs, arg);
}
@override
- visitSuperIndexSetIfNull(
- SendSet node,
- MethodElement getter,
- MethodElement setter,
- Node index,
- Node rhs,
- arg) {
- visits.add(new Visit(
- VisitKind.VISIT_SUPER_INDEX_SET_IF_NULL,
+ visitSuperIndexSetIfNull(SendSet node, MethodElement getter,
+ MethodElement setter, Node index, Node rhs, arg) {
+ visits.add(new Visit(VisitKind.VISIT_SUPER_INDEX_SET_IF_NULL,
getter: getter, setter: setter, index: index, rhs: rhs));
super.visitSuperIndexSetIfNull(node, getter, setter, index, rhs, arg);
}
@override
- visitUnresolvedSuperGetterIndexSetIfNull(
- Send node,
- Element element,
- MethodElement setter,
- Node index,
- Node rhs,
- arg) {
+ visitUnresolvedSuperGetterIndexSetIfNull(Send node, Element element,
+ MethodElement setter, Node index, Node rhs, arg) {
visits.add(new Visit(
VisitKind.VISIT_UNRESOLVED_SUPER_GETTER_INDEX_SET_IF_NULL,
- setter: setter, index: index, rhs: rhs));
+ setter: setter,
+ index: index,
+ rhs: rhs));
super.visitUnresolvedSuperGetterIndexSetIfNull(
node, element, setter, index, rhs, arg);
}
@override
- visitUnresolvedSuperSetterIndexSetIfNull(
- Send node,
- MethodElement getter,
- Element element,
- Node index,
- Node rhs,
- arg) {
+ visitUnresolvedSuperSetterIndexSetIfNull(Send node, MethodElement getter,
+ Element element, Node index, Node rhs, arg) {
visits.add(new Visit(
VisitKind.VISIT_UNRESOLVED_SUPER_SETTER_INDEX_SET_IF_NULL,
- getter: getter, index: index, rhs: rhs));
+ getter: getter,
+ index: index,
+ rhs: rhs));
super.visitUnresolvedSuperSetterIndexSetIfNull(
node, getter, element, index, rhs, arg);
}
@override
visitUnresolvedSuperIndexSetIfNull(
- Send node,
- Element element,
- Node index,
- Node rhs,
- arg) {
- visits.add(new Visit(
- VisitKind.VISIT_UNRESOLVED_SUPER_INDEX_SET_IF_NULL,
+ Send node, Element element, Node index, Node rhs, arg) {
+ visits.add(new Visit(VisitKind.VISIT_UNRESOLVED_SUPER_INDEX_SET_IF_NULL,
index: index, rhs: rhs));
super.visitUnresolvedSuperIndexSetIfNull(node, element, index, rhs, arg);
}
@override
errorInvalidIndexSetIfNull(
- SendSet node,
- ErroneousElement error,
- Node index,
- Node rhs,
- arg) {
- visits.add(new Visit(
- VisitKind.ERROR_INVALID_SET_IF_NULL,
- index: index, rhs: rhs));
+ SendSet node, ErroneousElement error, Node index, Node rhs, arg) {
+ visits.add(
+ new Visit(VisitKind.ERROR_INVALID_SET_IF_NULL, index: index, rhs: rhs));
super.visitUnresolvedSuperIndexSetIfNull(node, error, index, rhs, arg);
}
}
diff --git a/tests/compiler/dart2js/serialization/analysis_test_helper.dart b/tests/compiler/dart2js/serialization/analysis_test_helper.dart
index 82be8ee..00d19e6 100644
--- a/tests/compiler/dart2js/serialization/analysis_test_helper.dart
+++ b/tests/compiler/dart2js/serialization/analysis_test_helper.dart
@@ -37,13 +37,12 @@
});
}
-Future analyze(
- Uri entryPoint,
+Future analyze(Uri entryPoint,
{Map<String, String> sourceFiles: const <String, String>{},
- List<Uri> resolutionInputs,
- int index,
- Test test,
- bool verbose: false}) async {
+ List<Uri> resolutionInputs,
+ int index,
+ Test test,
+ bool verbose: false}) async {
String testDescription = test != null ? test.name : '${entryPoint}';
String id = index != null ? '$index: ' : '';
String title = '${id}${testDescription}';
@@ -58,10 +57,8 @@
if (test != null) {
Expect.equals(test.expectedErrorCount, diagnosticCollector.errors.length,
"Unexpected error count.");
- Expect.equals(
- test.expectedWarningCount,
- diagnosticCollector.warnings.length,
- "Unexpected warning count.");
+ Expect.equals(test.expectedWarningCount,
+ diagnosticCollector.warnings.length, "Unexpected warning count.");
Expect.equals(test.expectedHintCount, diagnosticCollector.hints.length,
"Unexpected hint count.");
Expect.equals(test.expectedInfoCount, diagnosticCollector.infos.length,
@@ -69,4 +66,3 @@
}
});
}
-
diff --git a/tests/compiler/dart2js/serialization/compilation_test_helper.dart b/tests/compiler/dart2js/serialization/compilation_test_helper.dart
index e1d4371..dd1989d 100644
--- a/tests/compiler/dart2js/serialization/compilation_test_helper.dart
+++ b/tests/compiler/dart2js/serialization/compilation_test_helper.dart
@@ -29,8 +29,7 @@
SerializationResult result = await serialize(entryPoint,
memorySourceFiles: serializedData.toMemorySourceFiles(),
resolutionInputs: serializedData.toUris());
- await compile(
- entryPoint,
+ await compile(entryPoint,
resolutionInputs: result.serializedData.toUris(),
sourceFiles: result.serializedData.toMemorySourceFiles());
} else {
@@ -41,13 +40,12 @@
});
}
-Future compile(
- Uri entryPoint,
+Future compile(Uri entryPoint,
{Map<String, String> sourceFiles: const <String, String>{},
- List<Uri> resolutionInputs,
- int index,
- Test test,
- bool verbose: false}) async {
+ List<Uri> resolutionInputs,
+ int index,
+ Test test,
+ bool verbose: false}) async {
String testDescription = test != null ? test.name : '${entryPoint}';
String id = index != null ? '$index: ' : '';
String title = '${id}${testDescription}';
@@ -68,4 +66,3 @@
print(outputCollector.getOutput('', 'js'));
}
}
-
diff --git a/tests/compiler/dart2js/serialization/duplicate_library_test.dart b/tests/compiler/dart2js/serialization/duplicate_library_test.dart
index 3380c66..290a704 100644
--- a/tests/compiler/dart2js/serialization/duplicate_library_test.dart
+++ b/tests/compiler/dart2js/serialization/duplicate_library_test.dart
@@ -17,8 +17,8 @@
void main(List<String> args) {
asyncTest(() async {
- SerializedData data = await serializeDartCore(
- arguments: new Arguments.from(args));
+ SerializedData data =
+ await serializeDartCore(arguments: new Arguments.from(args));
Map<String, String> sourceFiles = data.toMemorySourceFiles();
List<Uri> resolutionInputs = data.toUris();
Uri extraUri = Uri.parse('memory:extraUri');
@@ -35,4 +35,4 @@
Expect.isTrue(collector.errors.isNotEmpty,
"Expected duplicate serialized library errors.");
});
-}
\ No newline at end of file
+}
diff --git a/tests/compiler/dart2js/serialization/equivalence_test.dart b/tests/compiler/dart2js/serialization/equivalence_test.dart
index ee110f6..602daa1 100644
--- a/tests/compiler/dart2js/serialization/equivalence_test.dart
+++ b/tests/compiler/dart2js/serialization/equivalence_test.dart
@@ -92,15 +92,11 @@
entryPoint: entryPoint,
options: [Flags.analyzeAll, Flags.genericMethodSyntax]);
Compiler compiler = result.compiler;
- testSerialization(
- compiler.libraryLoader.libraries,
- compiler.reporter,
- compiler.resolution,
- compiler.libraryLoader,
- outPath: outPath,
- prettyPrint: prettyPrint);
- Expect.isFalse(compiler.reporter.hasReportedError,
- "Unexpected errors occured.");
+ testSerialization(compiler.libraryLoader.libraries, compiler.reporter,
+ compiler.resolution, compiler.libraryLoader,
+ outPath: outPath, prettyPrint: prettyPrint);
+ Expect.isFalse(
+ compiler.reporter.hasReportedError, "Unexpected errors occured.");
});
}
@@ -110,7 +106,7 @@
Resolution resolution,
LibraryProvider libraryProvider,
{String outPath,
- bool prettyPrint}) {
+ bool prettyPrint}) {
Serializer serializer = new Serializer();
for (LibraryElement library1 in libraries1) {
serializer.serialize(library1);
@@ -129,11 +125,11 @@
Deserializer deserializer = new Deserializer.fromText(
new DeserializationContext(reporter, resolution, libraryProvider),
Uri.parse('out1.data'),
- text, const JsonSerializationDecoder());
+ text,
+ const JsonSerializationDecoder());
List<LibraryElement> libraries2 = <LibraryElement>[];
for (LibraryElement library1 in libraries1) {
- LibraryElement library2 =
- deserializer.lookupLibrary(library1.canonicalUri);
+ LibraryElement library2 = deserializer.lookupLibrary(library1.canonicalUri);
if (library2 == null) {
throw new ArgumentError('No library ${library1.canonicalUri} found.');
}
@@ -150,10 +146,10 @@
Deserializer deserializer3 = new Deserializer.fromText(
new DeserializationContext(reporter, resolution, libraryProvider),
Uri.parse('out2.data'),
- text2, const JsonSerializationDecoder());
+ text2,
+ const JsonSerializationDecoder());
for (LibraryElement library1 in libraries1) {
- LibraryElement library2 =
- deserializer.lookupLibrary(library1.canonicalUri);
+ LibraryElement library2 = deserializer.lookupLibrary(library1.canonicalUri);
if (library2 == null) {
throw new ArgumentError('No library ${library1.canonicalUri} found.');
}
@@ -170,8 +166,7 @@
/// Check the equivalence of [library1] and [library2] and their content.
///
/// Uses [object1], [object2] and [property] to provide context for failures.
-checkLibraryContent(
- Object object1, object2, String property,
+checkLibraryContent(Object object1, object2, String property,
LibraryElement library1, LibraryElement library2) {
checkElementProperties(object1, object2, property, library1, library2);
}
@@ -179,8 +174,7 @@
/// Check the equivalence of [element1] and [element2] and their properties.
///
/// Uses [object1], [object2] and [property] to provide context for failures.
-checkElementProperties(
- Object object1, object2, String property,
+checkElementProperties(Object object1, object2, String property,
Element element1, Element element2) {
currentCheck =
new Check(currentCheck, object1, object2, property, element1, element2);
@@ -189,8 +183,8 @@
}
/// Checks the equivalence of [constructor1] and [constructor2].
-void constantConstructorEquivalence(ConstantConstructor constructor1,
- ConstantConstructor constructor2) {
+void constantConstructorEquivalence(
+ ConstantConstructor constructor1, ConstantConstructor constructor2) {
const ConstantConstructorEquivalence().visit(constructor1, constructor2);
}
@@ -200,32 +194,27 @@
const ConstantConstructorEquivalence();
@override
- void visit(ConstantConstructor constructor1,
- ConstantConstructor constructor2) {
+ void visit(
+ ConstantConstructor constructor1, ConstantConstructor constructor2) {
if (identical(constructor1, constructor2)) return;
- check(constructor1, constructor2, 'kind',
- constructor1.kind, constructor2.kind);
+ check(constructor1, constructor2, 'kind', constructor1.kind,
+ constructor2.kind);
constructor1.accept(this, constructor2);
}
@override
- visitGenerative(
- GenerativeConstantConstructor constructor1,
+ visitGenerative(GenerativeConstantConstructor constructor1,
GenerativeConstantConstructor constructor2) {
- checkTypes(
- constructor1, constructor2, 'type',
- constructor1.type, constructor2.type);
+ checkTypes(constructor1, constructor2, 'type', constructor1.type,
+ constructor2.type);
check(constructor1, constructor2, 'defaultValues.length',
- constructor1.defaultValues.length,
- constructor2.defaultValues.length);
+ constructor1.defaultValues.length, constructor2.defaultValues.length);
constructor1.defaultValues.forEach((k, v) {
- checkConstants(
- constructor1, constructor2, 'defaultValue[$k]',
- v, constructor2.defaultValues[k]);
+ checkConstants(constructor1, constructor2, 'defaultValue[$k]', v,
+ constructor2.defaultValues[k]);
});
check(constructor1, constructor2, 'fieldMap.length',
- constructor1.fieldMap.length,
- constructor2.fieldMap.length);
+ constructor1.fieldMap.length, constructor2.fieldMap.length);
constructor1.fieldMap.forEach((k1, v1) {
bool matched = false;
constructor2.fieldMap.forEach((k2, v2) {
@@ -243,17 +232,20 @@
}
});
checkConstants(
- constructor1, constructor2, 'superConstructorInvocation',
+ constructor1,
+ constructor2,
+ 'superConstructorInvocation',
constructor1.superConstructorInvocation,
constructor2.superConstructorInvocation);
}
@override
- visitRedirectingFactory(
- RedirectingFactoryConstantConstructor constructor1,
+ visitRedirectingFactory(RedirectingFactoryConstantConstructor constructor1,
RedirectingFactoryConstantConstructor constructor2) {
checkConstants(
- constructor1, constructor2, 'targetConstructorInvocation',
+ constructor1,
+ constructor2,
+ 'targetConstructorInvocation',
constructor1.targetConstructorInvocation,
constructor2.targetConstructorInvocation);
}
@@ -263,15 +255,15 @@
RedirectingGenerativeConstantConstructor constructor1,
RedirectingGenerativeConstantConstructor constructor2) {
check(constructor1, constructor2, 'defaultValues.length',
- constructor1.defaultValues.length,
- constructor2.defaultValues.length);
+ constructor1.defaultValues.length, constructor2.defaultValues.length);
constructor1.defaultValues.forEach((k, v) {
- checkConstants(
- constructor1, constructor2, 'defaultValue[$k]',
- v, constructor2.defaultValues[k]);
+ checkConstants(constructor1, constructor2, 'defaultValue[$k]', v,
+ constructor2.defaultValues[k]);
});
checkConstants(
- constructor1, constructor2, 'thisConstructorInvocation',
+ constructor1,
+ constructor2,
+ 'thisConstructorInvocation',
constructor1.thisConstructorInvocation,
constructor2.thisConstructorInvocation);
}
@@ -281,9 +273,9 @@
///
/// Uses [object1], [object2] and [property] to provide context for failures.
checkElementLists(Object object1, Object object2, String property,
- Iterable<Element> list1, Iterable<Element> list2) {
- checkListEquivalence(object1, object2, property,
- list1, list2, checkElementProperties);
+ Iterable<Element> list1, Iterable<Element> list2) {
+ checkListEquivalence(
+ object1, object2, property, list1, list2, checkElementProperties);
}
/// Check the equivalence of the two metadata annotations, [metadata1] and
@@ -292,8 +284,8 @@
/// Uses [object1], [object2] and [property] to provide context for failures.
checkMetadata(Object object1, Object object2, String property,
MetadataAnnotation metadata1, MetadataAnnotation metadata2) {
- check(object1, object2, property,
- metadata1, metadata2, areMetadataAnnotationsEquivalent);
+ check(object1, object2, property, metadata1, metadata2,
+ areMetadataAnnotationsEquivalent);
}
/// Visitor that checks for equivalence of [Element] properties.
@@ -310,24 +302,20 @@
if (element1 == element2) return;
check(element1, element2, 'kind', element1.kind, element2.kind);
element1.accept(this, element2);
- check(element1, element2, 'isSynthesized',
- element1.isSynthesized, element2.isSynthesized);
- check(element1, element2, 'isLocal',
- element1.isLocal, element2.isLocal);
- check(element1, element2, 'isFinal',
- element1.isFinal, element2.isFinal);
- check(element1, element2, 'isConst',
- element1.isConst, element2.isConst);
- check(element1, element2, 'isAbstract',
- element1.isAbstract, element2.isAbstract);
- check(element1, element2, 'isStatic',
- element1.isStatic, element2.isStatic);
- check(element1, element2, 'isTopLevel',
- element1.isTopLevel, element2.isTopLevel);
- check(element1, element2, 'isClassMember',
- element1.isClassMember, element2.isClassMember);
- check(element1, element2, 'isInstanceMember',
- element1.isInstanceMember, element2.isInstanceMember);
+ check(element1, element2, 'isSynthesized', element1.isSynthesized,
+ element2.isSynthesized);
+ check(element1, element2, 'isLocal', element1.isLocal, element2.isLocal);
+ check(element1, element2, 'isFinal', element1.isFinal, element2.isFinal);
+ check(element1, element2, 'isConst', element1.isConst, element2.isConst);
+ check(element1, element2, 'isAbstract', element1.isAbstract,
+ element2.isAbstract);
+ check(element1, element2, 'isStatic', element1.isStatic, element2.isStatic);
+ check(element1, element2, 'isTopLevel', element1.isTopLevel,
+ element2.isTopLevel);
+ check(element1, element2, 'isClassMember', element1.isClassMember,
+ element2.isClassMember);
+ check(element1, element2, 'isInstanceMember', element1.isInstanceMember,
+ element2.isInstanceMember);
List<MetadataAnnotation> metadata1 = <MetadataAnnotation>[];
metadata1.addAll(element1.metadata);
if (element1.isPatched) {
@@ -338,8 +326,8 @@
if (element2.isPatched) {
metadata2.addAll(element2.implementation.metadata);
}
- checkListEquivalence(element1, element2, 'metadata',
- metadata1, metadata2, checkMetadata);
+ checkListEquivalence(
+ element1, element2, 'metadata', metadata1, metadata2, checkMetadata);
}
@override
@@ -351,18 +339,22 @@
void visitLibraryElement(LibraryElement element1, LibraryElement element2) {
checkElementIdentities(null, null, null, element1, element2);
check(element1, element2, 'name', element1.name, element2.name);
- check(element1, element2, 'libraryName',
- element1.libraryName, element2.libraryName);
+ check(element1, element2, 'libraryName', element1.libraryName,
+ element2.libraryName);
visitMembers(element1, element2);
visit(element1.entryCompilationUnit, element2.entryCompilationUnit);
checkElementLists(
- element1, element2, 'compilationUnits',
+ element1,
+ element2,
+ 'compilationUnits',
LibrarySerializer.getCompilationUnits(element1),
LibrarySerializer.getCompilationUnits(element2));
checkElementLists(
- element1, element2, 'imports',
+ element1,
+ element2,
+ 'imports',
LibrarySerializer.getImports(element1),
LibrarySerializer.getImports(element2));
checkElementLists(
@@ -374,7 +366,9 @@
element1, element2, 'importScope', imported1, imported2);
checkElementListIdentities(
- element1, element2, 'exportScope',
+ element1,
+ element2,
+ 'exportScope',
LibrarySerializer.getExportedElements(element1),
LibrarySerializer.getExportedElements(element2));
@@ -383,27 +377,22 @@
}
}
- void checkImportsFor(Element element1, Element element2,
- Element import1, Element import2) {
+ void checkImportsFor(
+ Element element1, Element element2, Element import1, Element import2) {
List<ImportElement> imports1 = element1.library.getImportsFor(import1);
List<ImportElement> imports2 = element2.library.getImportsFor(import2);
- checkElementListIdentities(
- element1, element2, 'importsFor($import1/$import2)',
- imports1, imports2);
+ checkElementListIdentities(element1, element2,
+ 'importsFor($import1/$import2)', imports1, imports2);
}
@override
- void visitCompilationUnitElement(CompilationUnitElement element1,
- CompilationUnitElement element2) {
- check(element1, element2,
- 'name',
- element1.name, element2.name);
+ void visitCompilationUnitElement(
+ CompilationUnitElement element1, CompilationUnitElement element2) {
+ check(element1, element2, 'name', element1.name, element2.name);
checkElementIdentities(
- element1, element2, 'library',
- element1.library, element2.library);
- check(element1, element2,
- 'script.resourceUri',
- element1.script.resourceUri, element2.script.resourceUri);
+ element1, element2, 'library', element1.library, element2.library);
+ check(element1, element2, 'script.resourceUri', element1.script.resourceUri,
+ element2.script.resourceUri);
List<Element> members1 = <Element>[];
List<Element> members2 = <Element>[];
element1.forEachLocalMember((Element member) {
@@ -416,8 +405,8 @@
element1, element2, 'localMembers', members1, members2);
}
- void visitMembers(ScopeContainerElement element1,
- ScopeContainerElement element2) {
+ void visitMembers(
+ ScopeContainerElement element1, ScopeContainerElement element2) {
Set<String> names = new Set<String>();
Iterable<Element> members1 = element1.isLibrary
? LibrarySerializer.getMembers(element1)
@@ -458,8 +447,8 @@
throw message;
}
}
- currentCheck = new Check(currentCheck, element1, element2,
- 'member:$name', member1, member2);
+ currentCheck = new Check(
+ currentCheck, element1, element2, 'member:$name', member1, member2);
visit(member1, member2);
currentCheck = currentCheck.parent;
}
@@ -468,99 +457,81 @@
@override
void visitClassElement(ClassElement element1, ClassElement element2) {
checkElementIdentities(null, null, null, element1, element2);
- check(element1, element2, 'name',
- element1.name, element2.name);
+ check(element1, element2, 'name', element1.name, element2.name);
if (!element1.isUnnamedMixinApplication) {
- check(element1, element2, 'sourcePosition',
- element1.sourcePosition, element2.sourcePosition);
+ check(element1, element2, 'sourcePosition', element1.sourcePosition,
+ element2.sourcePosition);
} else {
check(element1, element2, 'sourcePosition.uri',
element1.sourcePosition.uri, element2.sourcePosition.uri);
MixinApplicationElement mixin1 = element1;
MixinApplicationElement mixin2 = element2;
- checkElementIdentities(mixin1, mixin2, 'subclass',
- mixin1.subclass, mixin2.subclass);
- checkTypes(mixin1, mixin2, 'mixinType',
- mixin1.mixinType, mixin2.mixinType);
+ checkElementIdentities(
+ mixin1, mixin2, 'subclass', mixin1.subclass, mixin2.subclass);
+ checkTypes(
+ mixin1, mixin2, 'mixinType', mixin1.mixinType, mixin2.mixinType);
}
checkElementIdentities(
- element1, element2, 'library',
- element1.library, element2.library);
- checkElementIdentities(
- element1, element2, 'compilationUnit',
+ element1, element2, 'library', element1.library, element2.library);
+ checkElementIdentities(element1, element2, 'compilationUnit',
element1.compilationUnit, element2.compilationUnit);
- checkTypeLists(
- element1, element2, 'typeVariables',
- element1.typeVariables, element2.typeVariables);
+ checkTypeLists(element1, element2, 'typeVariables', element1.typeVariables,
+ element2.typeVariables);
checkTypes(
- element1, element2, 'thisType',
- element1.thisType, element2.thisType);
+ element1, element2, 'thisType', element1.thisType, element2.thisType);
checkTypes(
- element1, element2, 'rawType',
- element1.rawType, element2.rawType);
- check(element1, element2, 'isObject',
- element1.isObject, element2.isObject);
- checkTypeLists(element1, element2, 'typeVariables',
- element1.typeVariables, element2.typeVariables);
- check(element1, element2, 'isAbstract',
- element1.isAbstract, element2.isAbstract);
+ element1, element2, 'rawType', element1.rawType, element2.rawType);
+ check(element1, element2, 'isObject', element1.isObject, element2.isObject);
+ checkTypeLists(element1, element2, 'typeVariables', element1.typeVariables,
+ element2.typeVariables);
+ check(element1, element2, 'isAbstract', element1.isAbstract,
+ element2.isAbstract);
check(element1, element2, 'isUnnamedMixinApplication',
element1.isUnnamedMixinApplication, element2.isUnnamedMixinApplication);
- check(element1, element2, 'isProxy',
- element1.isProxy, element2.isProxy);
- check(element1, element2, 'isInjected',
- element1.isInjected, element2.isInjected);
- check(element1, element2, 'isEnumClass',
- element1.isEnumClass, element2.isEnumClass);
+ check(element1, element2, 'isProxy', element1.isProxy, element2.isProxy);
+ check(element1, element2, 'isInjected', element1.isInjected,
+ element2.isInjected);
+ check(element1, element2, 'isEnumClass', element1.isEnumClass,
+ element2.isEnumClass);
if (element1.isEnumClass) {
EnumClassElement enum1 = element1;
EnumClassElement enum2 = element2;
- checkElementLists(enum1, enum2, 'enumValues',
- enum1.enumValues, enum2.enumValues);
+ checkElementLists(
+ enum1, enum2, 'enumValues', enum1.enumValues, enum2.enumValues);
}
if (!element1.isObject) {
- checkTypes(element1, element2, 'supertype',
- element1.supertype, element2.supertype);
+ checkTypes(element1, element2, 'supertype', element1.supertype,
+ element2.supertype);
}
- check(element1, element2, 'hierarchyDepth',
- element1.hierarchyDepth, element2.hierarchyDepth);
- checkTypeLists(
- element1, element2, 'allSupertypes',
- element1.allSupertypes.toList(),
- element2.allSupertypes.toList());
+ check(element1, element2, 'hierarchyDepth', element1.hierarchyDepth,
+ element2.hierarchyDepth);
+ checkTypeLists(element1, element2, 'allSupertypes',
+ element1.allSupertypes.toList(), element2.allSupertypes.toList());
OrderedTypeSet typeSet1 = element1.allSupertypesAndSelf;
OrderedTypeSet typeSet2 = element2.allSupertypesAndSelf;
- checkListEquivalence(
- element1, element2, 'allSupertypes',
- typeSet1.levelOffsets,
- typeSet2.levelOffsets,
- check);
- check(element1, element2, 'allSupertypesAndSelf.levels',
- typeSet1.levels, typeSet2.levels);
- checkTypeLists(
- element1, element2, 'supertypes',
- typeSet1.supertypes.toList(),
- typeSet2.supertypes.toList());
- checkTypeLists(
- element1, element2, 'types',
- typeSet1.types.toList(),
+ checkListEquivalence(element1, element2, 'allSupertypes',
+ typeSet1.levelOffsets, typeSet2.levelOffsets, check);
+ check(element1, element2, 'allSupertypesAndSelf.levels', typeSet1.levels,
+ typeSet2.levels);
+ checkTypeLists(element1, element2, 'supertypes',
+ typeSet1.supertypes.toList(), typeSet2.supertypes.toList());
+ checkTypeLists(element1, element2, 'types', typeSet1.types.toList(),
typeSet2.types.toList());
- checkTypeLists(
- element1, element2, 'interfaces',
- element1.interfaces.toList(),
- element2.interfaces.toList());
+ checkTypeLists(element1, element2, 'interfaces',
+ element1.interfaces.toList(), element2.interfaces.toList());
List<ConstructorElement> getConstructors(ClassElement cls) {
return cls.implementation.constructors.map((c) => c.declaration).toList();
}
- checkElementLists(
- element1, element2, 'constructors',
- getConstructors(element1),
- getConstructors(element2));
+ checkElementLists(element1, element2, 'constructors',
+ getConstructors(element1), getConstructors(element2));
- checkElementIdentities(element1, element2, 'defaultConstructor',
+ checkElementIdentities(
+ element1,
+ element2,
+ 'defaultConstructor',
element1.lookupDefaultConstructor(),
element2.lookupDefaultConstructor());
@@ -569,8 +540,8 @@
ClassElement superclass1 = element1.superclass;
ClassElement superclass2 = element2.superclass;
while (superclass1 != null && superclass1.isMixinApplication) {
- checkElementProperties(element1, element2, 'supermixin',
- superclass1, superclass2);
+ checkElementProperties(
+ element1, element2, 'supermixin', superclass1, superclass2);
superclass1 = superclass1.superclass;
superclass2 = superclass2.superclass;
}
@@ -579,141 +550,133 @@
@override
void visitFieldElement(FieldElement element1, FieldElement element2) {
checkElementIdentities(null, null, null, element1, element2);
- check(element1, element2, 'name',
- element1.name, element2.name);
- check(element1, element2, 'sourcePosition',
- element1.sourcePosition, element2.sourcePosition);
- checkTypes(
- element1, element2, 'type',
- element1.type, element2.type);
+ check(element1, element2, 'name', element1.name, element2.name);
+ check(element1, element2, 'sourcePosition', element1.sourcePosition,
+ element2.sourcePosition);
+ checkTypes(element1, element2, 'type', element1.type, element2.type);
checkConstants(
- element1, element2, 'constant',
- element1.constant, element2.constant);
- check(element1, element2, 'isTopLevel',
- element1.isTopLevel, element2.isTopLevel);
- check(element1, element2, 'isStatic',
- element1.isStatic, element2.isStatic);
- check(element1, element2, 'isInstanceMember',
- element1.isInstanceMember, element2.isInstanceMember);
- check(element1, element2, 'isInjected',
- element1.isInjected, element2.isInjected);
+ element1, element2, 'constant', element1.constant, element2.constant);
+ check(element1, element2, 'isTopLevel', element1.isTopLevel,
+ element2.isTopLevel);
+ check(element1, element2, 'isStatic', element1.isStatic, element2.isStatic);
+ check(element1, element2, 'isInstanceMember', element1.isInstanceMember,
+ element2.isInstanceMember);
+ check(element1, element2, 'isInjected', element1.isInjected,
+ element2.isInjected);
checkElementIdentities(
- element1, element2, 'library',
- element1.library, element2.library);
- checkElementIdentities(
- element1, element2, 'compilationUnit',
+ element1, element2, 'library', element1.library, element2.library);
+ checkElementIdentities(element1, element2, 'compilationUnit',
element1.compilationUnit, element2.compilationUnit);
- checkElementIdentities(
- element1, element2, 'enclosingClass',
+ checkElementIdentities(element1, element2, 'enclosingClass',
element1.enclosingClass, element2.enclosingClass);
}
@override
- void visitFunctionElement(FunctionElement element1,
- FunctionElement element2) {
+ void visitFunctionElement(
+ FunctionElement element1, FunctionElement element2) {
checkElementIdentities(null, null, null, element1, element2);
- check(element1, element2, 'name',
- element1.name, element2.name);
- check(element1, element2, 'sourcePosition',
- element1.sourcePosition, element2.sourcePosition);
- checkTypes(
- element1, element2, 'type',
- element1.type, element2.type);
- checkListEquivalence(
- element1, element2, 'parameters',
- element1.parameters, element2.parameters,
- checkElementProperties);
- check(element1, element2, 'isOperator',
- element1.isOperator, element2.isOperator);
- check(
- element1, element2, 'asyncMarker',
- element1.asyncMarker,
+ check(element1, element2, 'name', element1.name, element2.name);
+ check(element1, element2, 'sourcePosition', element1.sourcePosition,
+ element2.sourcePosition);
+ checkTypes(element1, element2, 'type', element1.type, element2.type);
+ checkListEquivalence(element1, element2, 'parameters', element1.parameters,
+ element2.parameters, checkElementProperties);
+ check(element1, element2, 'isOperator', element1.isOperator,
+ element2.isOperator);
+ check(element1, element2, 'asyncMarker', element1.asyncMarker,
element2.asyncMarker);
- check(element1, element2, 'isInjected',
- element1.isInjected, element2.isInjected);
+ check(element1, element2, 'isInjected', element1.isInjected,
+ element2.isInjected);
checkElementIdentities(
- element1, element2, 'library',
- element1.library, element2.library);
- checkElementIdentities(
- element1, element2, 'compilationUnit',
+ element1, element2, 'library', element1.library, element2.library);
+ checkElementIdentities(element1, element2, 'compilationUnit',
element1.compilationUnit, element2.compilationUnit);
- checkElementIdentities(
- element1, element2, 'enclosingClass',
+ checkElementIdentities(element1, element2, 'enclosingClass',
element1.enclosingClass, element2.enclosingClass);
check(
- element1, element2, 'functionSignature.type',
+ element1,
+ element2,
+ 'functionSignature.type',
element1.functionSignature.type,
element2.functionSignature.type,
areTypesEquivalent);
checkElementLists(
- element1, element2, 'functionSignature.requiredParameters',
+ element1,
+ element2,
+ 'functionSignature.requiredParameters',
element1.functionSignature.requiredParameters,
element2.functionSignature.requiredParameters);
checkElementLists(
- element1, element2, 'functionSignature.optionalParameters',
+ element1,
+ element2,
+ 'functionSignature.optionalParameters',
element1.functionSignature.optionalParameters,
element2.functionSignature.optionalParameters);
check(
- element1, element2, 'functionSignature.requiredParameterCount',
+ element1,
+ element2,
+ 'functionSignature.requiredParameterCount',
element1.functionSignature.requiredParameterCount,
element2.functionSignature.requiredParameterCount);
check(
- element1, element2, 'functionSignature.optionalParameterCount',
+ element1,
+ element2,
+ 'functionSignature.optionalParameterCount',
element1.functionSignature.optionalParameterCount,
element2.functionSignature.optionalParameterCount);
check(
- element1, element2, 'functionSignature.optionalParametersAreNamed',
+ element1,
+ element2,
+ 'functionSignature.optionalParametersAreNamed',
element1.functionSignature.optionalParametersAreNamed,
element2.functionSignature.optionalParametersAreNamed);
check(
- element1, element2, 'functionSignature.hasOptionalParameters',
+ element1,
+ element2,
+ 'functionSignature.hasOptionalParameters',
element1.functionSignature.hasOptionalParameters,
element2.functionSignature.hasOptionalParameters);
check(
- element1, element2, 'functionSignature.parameterCount',
+ element1,
+ element2,
+ 'functionSignature.parameterCount',
element1.functionSignature.parameterCount,
element2.functionSignature.parameterCount);
checkElementLists(
- element1, element2, 'functionSignature.orderedOptionalParameters',
+ element1,
+ element2,
+ 'functionSignature.orderedOptionalParameters',
element1.functionSignature.orderedOptionalParameters,
element2.functionSignature.orderedOptionalParameters);
- checkTypeLists(element1, element2, 'typeVariables',
- element1.typeVariables, element2.typeVariables);
+ checkTypeLists(element1, element2, 'typeVariables', element1.typeVariables,
+ element2.typeVariables);
}
@override
- void visitConstructorElement(ConstructorElement element1,
- ConstructorElement element2) {
+ void visitConstructorElement(
+ ConstructorElement element1, ConstructorElement element2) {
checkElementIdentities(null, null, null, element1, element2);
- checkElementIdentities(
- element1, element2, 'enclosingClass',
+ checkElementIdentities(element1, element2, 'enclosingClass',
element1.enclosingClass, element2.enclosingClass);
- check(
- element1, element2, 'name',
- element1.name, element2.name);
+ check(element1, element2, 'name', element1.name, element2.name);
if (!element1.isSynthesized) {
- check(element1, element2, 'sourcePosition',
- element1.sourcePosition, element2.sourcePosition);
+ check(element1, element2, 'sourcePosition', element1.sourcePosition,
+ element2.sourcePosition);
} else {
check(element1, element2, 'sourcePosition.uri',
element1.sourcePosition.uri, element2.sourcePosition.uri);
}
- checkListEquivalence(
- element1, element2, 'parameters',
- element1.parameters, element2.parameters,
- checkElementProperties);
- checkTypes(
- element1, element2, 'type',
- element1.type, element2.type);
- check(element1, element2, 'isExternal',
- element1.isExternal, element2.isExternal);
+ checkListEquivalence(element1, element2, 'parameters', element1.parameters,
+ element2.parameters, checkElementProperties);
+ checkTypes(element1, element2, 'type', element1.type, element2.type);
+ check(element1, element2, 'isExternal', element1.isExternal,
+ element2.isExternal);
if (element1.isConst && !element1.isExternal) {
constantConstructorEquivalence(
- element1.constantConstructor,
- element2.constantConstructor);
+ element1.constantConstructor, element2.constantConstructor);
}
check(element1, element2, 'isRedirectingGenerative',
element1.isRedirectingGenerative, element2.isRedirectingGenerative);
@@ -722,160 +685,151 @@
checkElementIdentities(element1, element2, 'effectiveTarget',
element1.effectiveTarget, element2.effectiveTarget);
if (element1.isRedirectingFactory) {
- checkElementIdentities(element1, element2, 'immediateRedirectionTarget',
+ checkElementIdentities(
+ element1,
+ element2,
+ 'immediateRedirectionTarget',
element1.immediateRedirectionTarget,
element2.immediateRedirectionTarget);
- checkElementIdentities(element1, element2, 'redirectionDeferredPrefix',
+ checkElementIdentities(
+ element1,
+ element2,
+ 'redirectionDeferredPrefix',
element1.redirectionDeferredPrefix,
element2.redirectionDeferredPrefix);
- check(element1, element2, 'isEffectiveTargetMalformed',
+ check(
+ element1,
+ element2,
+ 'isEffectiveTargetMalformed',
element1.isEffectiveTargetMalformed,
element2.isEffectiveTargetMalformed);
}
checkElementIdentities(element1, element2, 'definingConstructor',
element1.definingConstructor, element2.definingConstructor);
check(
- element1, element2, 'effectiveTargetType',
+ element1,
+ element2,
+ 'effectiveTargetType',
element1.computeEffectiveTargetType(element1.enclosingClass.thisType),
element2.computeEffectiveTargetType(element2.enclosingClass.thisType),
areTypesEquivalent);
check(
- element1, element2, 'effectiveTargetType.raw',
+ element1,
+ element2,
+ 'effectiveTargetType.raw',
element1.computeEffectiveTargetType(element1.enclosingClass.rawType),
element2.computeEffectiveTargetType(element2.enclosingClass.rawType),
areTypesEquivalent);
- checkElementIdentities(element1, element2, 'immediateRedirectionTarget',
+ checkElementIdentities(
+ element1,
+ element2,
+ 'immediateRedirectionTarget',
element1.immediateRedirectionTarget,
element2.immediateRedirectionTarget);
checkElementIdentities(element1, element2, 'redirectionDeferredPrefix',
element1.redirectionDeferredPrefix, element2.redirectionDeferredPrefix);
- check(element1, element2, 'isInjected',
- element1.isInjected, element2.isInjected);
+ check(element1, element2, 'isInjected', element1.isInjected,
+ element2.isInjected);
}
@override
- void visitAbstractFieldElement(AbstractFieldElement element1,
- AbstractFieldElement element2) {
+ void visitAbstractFieldElement(
+ AbstractFieldElement element1, AbstractFieldElement element2) {
visit(element1.getter, element2.getter);
visit(element1.setter, element2.setter);
}
@override
- void visitTypeVariableElement(TypeVariableElement element1,
- TypeVariableElement element2) {
+ void visitTypeVariableElement(
+ TypeVariableElement element1, TypeVariableElement element2) {
checkElementIdentities(null, null, null, element1, element2);
check(element1, element2, 'name', element1.name, element2.name);
- check(element1, element2, 'sourcePosition',
- element1.sourcePosition, element2.sourcePosition);
+ check(element1, element2, 'sourcePosition', element1.sourcePosition,
+ element2.sourcePosition);
check(element1, element2, 'index', element1.index, element2.index);
- checkTypes(
- element1, element2, 'type',
- element1.type, element2.type);
- checkTypes(
- element1, element2, 'bound',
- element1.bound, element2.bound);
+ checkTypes(element1, element2, 'type', element1.type, element2.type);
+ checkTypes(element1, element2, 'bound', element1.bound, element2.bound);
}
@override
- void visitTypedefElement(TypedefElement element1,
- TypedefElement element2) {
+ void visitTypedefElement(TypedefElement element1, TypedefElement element2) {
checkElementIdentities(null, null, null, element1, element2);
check(element1, element2, 'name', element1.name, element2.name);
- check(element1, element2, 'sourcePosition',
- element1.sourcePosition, element2.sourcePosition);
- checkTypes(
- element1, element2, 'alias',
- element1.alias, element2.alias);
- checkTypeLists(
- element1, element2, 'typeVariables',
- element1.typeVariables, element2.typeVariables);
+ check(element1, element2, 'sourcePosition', element1.sourcePosition,
+ element2.sourcePosition);
+ checkTypes(element1, element2, 'alias', element1.alias, element2.alias);
+ checkTypeLists(element1, element2, 'typeVariables', element1.typeVariables,
+ element2.typeVariables);
checkElementIdentities(
- element1, element2, 'library',
- element1.library, element2.library);
- checkElementIdentities(
- element1, element2, 'compilationUnit',
+ element1, element2, 'library', element1.library, element2.library);
+ checkElementIdentities(element1, element2, 'compilationUnit',
element1.compilationUnit, element2.compilationUnit);
// TODO(johnniwinther): Check the equivalence of typedef parameters.
}
@override
- void visitParameterElement(ParameterElement element1,
- ParameterElement element2) {
+ void visitParameterElement(
+ ParameterElement element1, ParameterElement element2) {
checkElementIdentities(null, null, null, element1, element2);
- checkElementIdentities(
- element1, element2, 'functionDeclaration',
+ checkElementIdentities(element1, element2, 'functionDeclaration',
element1.functionDeclaration, element2.functionDeclaration);
check(element1, element2, 'name', element1.name, element2.name);
- check(element1, element2, 'sourcePosition',
- element1.sourcePosition, element2.sourcePosition);
- checkTypes(
- element1, element2, 'type',
- element1.type, element2.type);
- check(
- element1, element2, 'isOptional',
- element1.isOptional, element2.isOptional);
- check(
- element1, element2, 'isNamed',
- element1.isNamed, element2.isNamed);
+ check(element1, element2, 'sourcePosition', element1.sourcePosition,
+ element2.sourcePosition);
+ checkTypes(element1, element2, 'type', element1.type, element2.type);
+ check(element1, element2, 'isOptional', element1.isOptional,
+ element2.isOptional);
+ check(element1, element2, 'isNamed', element1.isNamed, element2.isNamed);
check(element1, element2, 'name', element1.name, element2.name);
if (element1.isOptional) {
checkConstants(
- element1, element2, 'constant',
- element1.constant, element2.constant);
+ element1, element2, 'constant', element1.constant, element2.constant);
}
- checkElementIdentities(
- element1, element2, 'compilationUnit',
+ checkElementIdentities(element1, element2, 'compilationUnit',
element1.compilationUnit, element2.compilationUnit);
}
@override
- void visitFieldParameterElement(InitializingFormalElement element1,
- InitializingFormalElement element2) {
+ void visitFieldParameterElement(
+ InitializingFormalElement element1, InitializingFormalElement element2) {
visitParameterElement(element1, element2);
- checkElementIdentities(
- element1, element2, 'fieldElement',
+ checkElementIdentities(element1, element2, 'fieldElement',
element1.fieldElement, element2.fieldElement);
}
@override
void visitImportElement(ImportElement element1, ImportElement element2) {
check(element1, element2, 'uri', element1.uri, element2.uri);
- check(
- element1, element2, 'isDeferred',
- element1.isDeferred, element2.isDeferred);
+ check(element1, element2, 'isDeferred', element1.isDeferred,
+ element2.isDeferred);
checkElementProperties(
- element1, element2, 'prefix',
- element1.prefix, element2.prefix);
- checkElementIdentities(
- element1, element2, 'importedLibrary',
+ element1, element2, 'prefix', element1.prefix, element2.prefix);
+ checkElementIdentities(element1, element2, 'importedLibrary',
element1.importedLibrary, element2.importedLibrary);
}
@override
void visitExportElement(ExportElement element1, ExportElement element2) {
check(element1, element2, 'uri', element1.uri, element2.uri);
- checkElementIdentities(
- element1, element2, 'importedLibrary',
+ checkElementIdentities(element1, element2, 'importedLibrary',
element1.exportedLibrary, element2.exportedLibrary);
}
@override
void visitPrefixElement(PrefixElement element1, PrefixElement element2) {
- check(
- element1, element2, 'isDeferred',
- element1.isDeferred, element2.isDeferred);
- checkElementIdentities(
- element1, element2, 'deferredImport',
+ check(element1, element2, 'isDeferred', element1.isDeferred,
+ element2.isDeferred);
+ checkElementIdentities(element1, element2, 'deferredImport',
element1.deferredImport, element2.deferredImport);
if (element1.isDeferred) {
- checkElementProperties(element1, element2,
- 'loadLibrary', element1.loadLibrary, element2.loadLibrary);
+ checkElementProperties(element1, element2, 'loadLibrary',
+ element1.loadLibrary, element2.loadLibrary);
}
element1.forEachLocalMember((Element member1) {
String name = member1.name;
Element member2 = element2.lookupLocalMember(name);
- checkElementIdentities(element1, element2, 'lookupLocalMember:$name',
- member1, member2);
+ checkElementIdentities(
+ element1, element2, 'lookupLocalMember:$name', member1, member2);
checkImportsFor(element1, element2, member1, member2);
});
}
@@ -883,7 +837,7 @@
@override
void visitErroneousElement(
ErroneousElement element1, ErroneousElement element2) {
- check(element1, element2, 'messageKind',
- element1.messageKind, element2.messageKind);
+ check(element1, element2, 'messageKind', element1.messageKind,
+ element2.messageKind);
}
}
diff --git a/tests/compiler/dart2js/serialization/helper.dart b/tests/compiler/dart2js/serialization/helper.dart
index 9c3204a..cd6ecb2 100644
--- a/tests/compiler/dart2js/serialization/helper.dart
+++ b/tests/compiler/dart2js/serialization/helper.dart
@@ -26,14 +26,14 @@
final String serializedDataFileName;
final bool verbose;
- const Arguments({
- this.filename,
- this.start,
- this.end,
- this.loadSerializedData: false,
- this.saveSerializedData: false,
- this.serializedDataFileName: DEFAULT_DATA_FILE_NAME,
- this.verbose: false});
+ const Arguments(
+ {this.filename,
+ this.start,
+ this.end,
+ this.loadSerializedData: false,
+ this.saveSerializedData: false,
+ this.serializedDataFileName: DEFAULT_DATA_FILE_NAME,
+ this.verbose: false});
factory Arguments.from(List<String> arguments) {
String filename;
@@ -71,9 +71,7 @@
saveSerializedData: saveSerializedData);
}
- Future forEachTest(
- SerializedData serializedData,
- List<Test> tests,
+ Future forEachTest(SerializedData serializedData, List<Test> tests,
TestFunction testFunction) async {
Uri entryPoint = Uri.parse('memory:main.dart');
int first = start ?? 0;
@@ -106,13 +104,12 @@
}
}
-typedef Future TestFunction(
- Uri entryPoint,
+typedef Future TestFunction(Uri entryPoint,
{Map<String, String> sourceFiles,
- List<Uri> resolutionInputs,
- int index,
- Test test,
- bool verbose});
+ List<Uri> resolutionInputs,
+ int index,
+ Test test,
+ bool verbose});
Future<SerializedData> serializeDartCore(
{Arguments arguments: const Arguments()}) {
@@ -148,9 +145,9 @@
Future<SerializationResult> serialize(Uri entryPoint,
{Map<String, String> memorySourceFiles: const <String, String>{},
- List<Uri> resolutionInputs: const <Uri>[],
- Uri dataUri,
- bool deserializeCompilationDataForTesting: false}) async {
+ List<Uri> resolutionInputs: const <Uri>[],
+ Uri dataUri,
+ bool deserializeCompilationDataForTesting: false}) async {
if (dataUri == null) {
dataUri = Uri.parse('memory:${DEFAULT_DATA_FILE_NAME}');
}
@@ -163,8 +160,8 @@
compiler.serialization.deserializeCompilationDataForTesting =
deserializeCompilationDataForTesting;
await compiler.run(entryPoint);
- SerializedData serializedData = new SerializedData(
- dataUri, outputCollector.getOutput('', 'data'));
+ SerializedData serializedData =
+ new SerializedData(dataUri, outputCollector.getOutput('', 'data'));
return new SerializationResult(compiler, serializedData);
}
@@ -226,10 +223,9 @@
Uri additionalDataUri = Uri.parse('memory:additional.data');
SerializedData additionalSerializedData;
if (test.sourceFiles.isEmpty) {
- SerializationResult result = await serialize(
- uriList.first,
+ SerializationResult result = await serialize(uriList.first,
memorySourceFiles: sourceFiles,
- resolutionInputs: serializedData.toUris(),
+ resolutionInputs: serializedData.toUris(),
dataUri: additionalDataUri);
additionalSerializedData = result.serializedData;
} else {
@@ -247,8 +243,7 @@
libraries.add(compiler.libraryLoader.lookupLibrary(uri));
}
additionalSerializedData = new SerializedData(
- additionalDataUri,
- outputCollector.getOutput('', 'data'));
+ additionalDataUri, outputCollector.getOutput('', 'data'));
}
return <SerializedData>[serializedData, additionalSerializedData];
}
@@ -304,7 +299,7 @@
stopwatch.stop();
int elapsedMilliseconds = stopwatch.elapsedMilliseconds;
print('$taskTitle: $title: ${elapsedMilliseconds}ms');
- measurementResults.add(
- new MeasurementResult(title, taskTitle, elapsedMilliseconds));
+ measurementResults
+ .add(new MeasurementResult(title, taskTitle, elapsedMilliseconds));
return result;
-}
\ No newline at end of file
+}
diff --git a/tests/compiler/dart2js/serialization/impact_test.dart b/tests/compiler/dart2js/serialization/impact_test.dart
index 3858f70..97a6e2d 100644
--- a/tests/compiler/dart2js/serialization/impact_test.dart
+++ b/tests/compiler/dart2js/serialization/impact_test.dart
@@ -24,21 +24,16 @@
} else {
Uri entryPoint = Uri.parse('memory:main.dart');
await check(serializedData, entryPoint,
- sourceFiles: {'main.dart': 'main() {}'},
- verbose: arguments.verbose);
+ sourceFiles: {'main.dart': 'main() {}'}, verbose: arguments.verbose);
}
});
}
-Future check(
- SerializedData serializedData,
- Uri entryPoint,
- {Map<String, String> sourceFiles: const <String, String>{},
- bool verbose: false}) async {
-
- Compiler compilerNormal = compilerFor(
- memorySourceFiles: sourceFiles,
- options: [Flags.analyzeAll]);
+Future check(SerializedData serializedData, Uri entryPoint,
+ {Map<String, String> sourceFiles: const <String, String>{},
+ bool verbose: false}) async {
+ Compiler compilerNormal =
+ compilerFor(memorySourceFiles: sourceFiles, options: [Flags.analyzeAll]);
compilerNormal.resolution.retainCachesForTesting = true;
await compilerNormal.run(entryPoint);
diff --git a/tests/compiler/dart2js/serialization/library_test.dart b/tests/compiler/dart2js/serialization/library_test.dart
index 840cd78..2334ac6 100644
--- a/tests/compiler/dart2js/serialization/library_test.dart
+++ b/tests/compiler/dart2js/serialization/library_test.dart
@@ -53,24 +53,18 @@
entryPoint = Uris.dart_core;
}
asyncTest(() async {
- Compiler compiler = await compilerFor(
- entryPoint: entryPoint, options: [Flags.analyzeAll]);
+ Compiler compiler =
+ await compilerFor(entryPoint: entryPoint, options: [Flags.analyzeAll]);
compiler.serialization.supportSerialization = true;
await compiler.run(entryPoint);
- List<SerializedData> data =
- createData(compiler,
- outPath: outPath,
- prettyPrint: prettyPrint,
- shardCount: shardCount);
+ List<SerializedData> data = createData(compiler,
+ outPath: outPath, prettyPrint: prettyPrint, shardCount: shardCount);
await testAnalysis(compiler, data, entryPoint);
});
}
-List<SerializedData> createData(
- Compiler compiler,
- {String outPath,
- bool prettyPrint,
- int shardCount: 3}) {
+List<SerializedData> createData(Compiler compiler,
+ {String outPath, bool prettyPrint, int shardCount: 3}) {
Iterable<LibraryElement> libraries1 = compiler.libraryLoader.libraries;
if (shardCount < 1 || shardCount > libraries1.length) {
shardCount = libraries1.length;
@@ -92,8 +86,7 @@
List<SerializedData> data = <SerializedData>[];
for (int shard = 0; shard < shardCount; shard++) {
List<LibraryElement> libraries = librarySplits[shard];
- Serializer serializer =
- compiler.serialization.createSerializer(libraries);
+ Serializer serializer = compiler.serialization.createSerializer(libraries);
String text = serializer.toText(const JsonSerializationEncoder());
String outText = text;
if (prettyPrint) {
@@ -117,9 +110,7 @@
}
Future testAnalysis(
- Compiler compiler1,
- List<SerializedData> data,
- Uri entryPoint) async {
+ Compiler compiler1, List<SerializedData> data, Uri entryPoint) async {
Map<String, String> memorySourceFiles = <String, String>{};
List<Uri> resolutionInputs = <Uri>[];
for (int index = 0; index < data.length; index++) {
@@ -144,4 +135,4 @@
checkAllImpacts(compiler1, compiler2);
}
Expect.isFalse(compiler2.reporter.hasReportedError, "Unexpected errors");
-}
\ No newline at end of file
+}
diff --git a/tests/compiler/dart2js/serialization/members_test.dart b/tests/compiler/dart2js/serialization/members_test.dart
index ef23e87..22e0899 100644
--- a/tests/compiler/dart2js/serialization/members_test.dart
+++ b/tests/compiler/dart2js/serialization/members_test.dart
@@ -17,30 +17,25 @@
import 'helper.dart';
import 'test_helper.dart';
-
main(List<String> args) {
Arguments arguments = new Arguments.from(args);
asyncTest(() async {
SerializedData serializedData =
- await serializeDartCore(arguments: arguments);
+ await serializeDartCore(arguments: arguments);
if (arguments.filename != null) {
Uri entryPoint = Uri.base.resolve(nativeToUriPath(arguments.filename));
- await checkClassMembers(
- serializedData, entryPoint, verbose: arguments.verbose);
+ await checkClassMembers(serializedData, entryPoint,
+ verbose: arguments.verbose);
} else {
- await checkClassMembers(
- serializedData, Uris.dart_core, verbose: arguments.verbose);
+ await checkClassMembers(serializedData, Uris.dart_core,
+ verbose: arguments.verbose);
}
});
}
-Future checkClassMembers(
- SerializedData serializedData,
- Uri entryPoint,
+Future checkClassMembers(SerializedData serializedData, Uri entryPoint,
{bool verbose: false}) async {
-
- Compiler compilerNormal = compilerFor(
- options: [Flags.analyzeAll]);
+ Compiler compilerNormal = compilerFor(options: [Flags.analyzeAll]);
await compilerNormal.run(entryPoint);
Compiler compilerDeserialized = compilerFor(
@@ -52,22 +47,15 @@
checkAllMembers(compilerNormal, compilerDeserialized, verbose: true);
}
-void checkAllMembers(
- Compiler compiler1,
- Compiler compiler2,
+void checkAllMembers(Compiler compiler1, Compiler compiler2,
{bool verbose: false}) {
- checkLoadedLibraryMembers(
- compiler1,
- compiler2,
- (Element member1) => member1 is ClassElement,
- checkMembers,
+ checkLoadedLibraryMembers(compiler1, compiler2,
+ (Element member1) => member1 is ClassElement, checkMembers,
verbose: verbose);
}
-
/// Check equivalence of members of [class1] and [class2].
-void checkMembers(
- Compiler compiler1, ClassMemberMixin class1,
+void checkMembers(Compiler compiler1, ClassMemberMixin class1,
Compiler compiler2, ClassMemberMixin class2,
{bool verbose: false}) {
if (verbose) {
@@ -76,21 +64,24 @@
MembersCreator.computeAllClassMembers(compiler1.resolution, class1);
MembersCreator.computeAllClassMembers(compiler2.resolution, class2);
- check(class1, class2, 'interfaceMemberAreClassMembers',
+ check(
+ class1,
+ class2,
+ 'interfaceMemberAreClassMembers',
class1.interfaceMembersAreClassMembers,
class2.interfaceMembersAreClassMembers);
class1.forEachClassMember((Member member1) {
Name name1 = member1.name;
Name name2 = convertName(name1, compiler2);
- checkMember(class1, class2, 'classMember:$name1',
- member1, class2.lookupClassMember(name2));
+ checkMember(class1, class2, 'classMember:$name1', member1,
+ class2.lookupClassMember(name2));
});
class1.forEachInterfaceMember((MemberSignature member1) {
Name name1 = member1.name;
Name name2 = convertName(name1, compiler2);
- checkMemberSignature(class1, class2, 'interfaceMember:$name1',
- member1, class2.lookupInterfaceMember(name2));
+ checkMemberSignature(class1, class2, 'interfaceMember:$name1', member1,
+ class2.lookupInterfaceMember(name2));
});
}
@@ -116,16 +107,16 @@
throw "No member ${member1.name} in $class2 for $property";
}
checkMemberSignature(class1, class2, property, member1, member2);
- checkElementIdentities(class1, class2, '$property.element',
- member1.element, member2.element);
- check(class1, class2, '$property.declarer',
- member1.declarer, member2.declarer, areTypesEquivalent);
- check(class1, class2, '$property.isStatic',
- member1.isStatic, member2.isStatic);
+ checkElementIdentities(
+ class1, class2, '$property.element', member1.element, member2.element);
+ check(class1, class2, '$property.declarer', member1.declarer,
+ member2.declarer, areTypesEquivalent);
+ check(
+ class1, class2, '$property.isStatic', member1.isStatic, member2.isStatic);
check(class1, class2, '$property.isDeclaredByField',
member1.isDeclaredByField, member2.isDeclaredByField);
- check(class1, class2, '$property.isAbstract',
- member1.isAbstract, member2.isAbstract);
+ check(class1, class2, '$property.isAbstract', member1.isAbstract,
+ member2.isAbstract);
if (member1.isAbstract && member1.implementation != null) {
checkMember(class1, class2, '$property.implementation',
member1.implementation, member2.implementation);
@@ -133,8 +124,7 @@
}
void checkMemberSignature(ClassElement class1, ClassElement class2,
- String property,
- MemberSignature member1, MemberSignature member2) {
+ String property, MemberSignature member1, MemberSignature member2) {
if (member2 == null) {
print('$class1 interface members:');
class1.forEachInterfaceMember((m) => print(' ${m.name} $m'));
@@ -142,16 +132,16 @@
class2.forEachInterfaceMember((m) => print(' ${m.name} $m'));
throw "No member ${member1.name} in $class2 for $property";
}
- check(class1, class2, '$property.name',
- member1.name, member2.name, areNamesEquivalent);
- check(class1, class2, '$property.type',
- member1.type, member2.type, areTypesEquivalent);
- check(class1, class2, '$property.functionType',
- member1.functionType, member2.functionType, areTypesEquivalent);
- check(class1, class2, '$property.isGetter',
- member1.isGetter, member2.isGetter);
- check(class1, class2, '$property.isSetter',
- member1.isSetter, member2.isSetter);
- check(class1, class2, '$property.isMethod',
- member1.isMethod, member2.isMethod);
+ check(class1, class2, '$property.name', member1.name, member2.name,
+ areNamesEquivalent);
+ check(class1, class2, '$property.type', member1.type, member2.type,
+ areTypesEquivalent);
+ check(class1, class2, '$property.functionType', member1.functionType,
+ member2.functionType, areTypesEquivalent);
+ check(
+ class1, class2, '$property.isGetter', member1.isGetter, member2.isGetter);
+ check(
+ class1, class2, '$property.isSetter', member1.isSetter, member2.isSetter);
+ check(
+ class1, class2, '$property.isMethod', member1.isMethod, member2.isMethod);
}
diff --git a/tests/compiler/dart2js/serialization/model_test_helper.dart b/tests/compiler/dart2js/serialization/model_test_helper.dart
index ef92303..6952d35 100644
--- a/tests/compiler/dart2js/serialization/model_test_helper.dart
+++ b/tests/compiler/dart2js/serialization/model_test_helper.dart
@@ -38,19 +38,18 @@
await serializeDartCore(arguments: arguments);
if (arguments.filename != null) {
Uri entryPoint = Uri.base.resolve(nativeToUriPath(arguments.filename));
- SerializationResult result = await measure(
- '${entryPoint}', 'serialize', () {
- return serialize(
- entryPoint,
+ SerializationResult result =
+ await measure('${entryPoint}', 'serialize', () {
+ return serialize(entryPoint,
memorySourceFiles: serializedData.toMemorySourceFiles(),
resolutionInputs: serializedData.toUris(),
dataUri: Uri.parse('memory:test.data'));
});
await checkModels(entryPoint,
- sourceFiles: serializedData.toMemorySourceFiles(
- result.serializedData.toMemorySourceFiles()),
- resolutionInputs: serializedData.toUris(
- result.serializedData.toUris()));
+ sourceFiles: serializedData
+ .toMemorySourceFiles(result.serializedData.toMemorySourceFiles()),
+ resolutionInputs:
+ serializedData.toUris(result.serializedData.toUris()));
} else {
Uri entryPoint = Uri.parse('memory:main.dart');
await arguments.forEachTest(serializedData, TESTS, checkModels);
@@ -59,33 +58,30 @@
});
}
-Future checkModels(
- Uri entryPoint,
+Future checkModels(Uri entryPoint,
{Map<String, String> sourceFiles: const <String, String>{},
- List<Uri> resolutionInputs,
- int index,
- Test test,
- bool verbose: false}) async {
+ List<Uri> resolutionInputs,
+ int index,
+ Test test,
+ bool verbose: false}) async {
String testDescription = test != null ? test.name : '${entryPoint}';
String id = index != null ? '$index: ' : '';
String title = '${id}${testDescription}';
- Compiler compilerNormal = await measure(
- title, 'compile normal', () async {
+ Compiler compilerNormal = await measure(title, 'compile normal', () async {
Compiler compilerNormal = compilerFor(
- memorySourceFiles: sourceFiles,
- options: [Flags.analyzeOnly]);
+ memorySourceFiles: sourceFiles, options: [Flags.analyzeOnly]);
compilerNormal.resolution.retainCachesForTesting = true;
await compilerNormal.run(entryPoint);
compilerNormal.phase = Compiler.PHASE_DONE_RESOLVING;
compilerNormal.world.populate();
compilerNormal.backend.onResolutionComplete();
- compilerNormal.deferredLoadTask.onResolutionComplete(
- compilerNormal.mainFunction);
+ compilerNormal.deferredLoadTask
+ .onResolutionComplete(compilerNormal.mainFunction);
return compilerNormal;
});
- Compiler compilerDeserialized = await measure(
- title, 'compile deserialized', () async {
+ Compiler compilerDeserialized =
+ await measure(title, 'compile deserialized', () async {
Compiler compilerDeserialized = compilerFor(
memorySourceFiles: sourceFiles,
resolutionInputs: resolutionInputs,
@@ -95,15 +91,13 @@
compilerDeserialized.phase = Compiler.PHASE_DONE_RESOLVING;
compilerDeserialized.world.populate();
compilerDeserialized.backend.onResolutionComplete();
- compilerDeserialized.deferredLoadTask.onResolutionComplete(
- compilerDeserialized.mainFunction);
+ compilerDeserialized.deferredLoadTask
+ .onResolutionComplete(compilerDeserialized.mainFunction);
return compilerDeserialized;
});
return measure(title, 'check models', () async {
- checkAllImpacts(
- compilerNormal, compilerDeserialized,
- verbose: verbose);
+ checkAllImpacts(compilerNormal, compilerDeserialized, verbose: verbose);
checkSets(
compilerNormal.resolverWorld.directlyInstantiatedClasses,
@@ -130,32 +124,34 @@
compilerNormal.enqueuer.resolution.processedElements,
compilerDeserialized.enqueuer.resolution.processedElements,
"Processed element mismatch",
- areElementsEquivalent,
- onSameElement: (a, b) {
- checkElements(
- compilerNormal, compilerDeserialized, a, b, verbose: verbose);
- },
- verbose: verbose);
+ areElementsEquivalent, onSameElement: (a, b) {
+ checkElements(compilerNormal, compilerDeserialized, a, b,
+ verbose: verbose);
+ }, verbose: verbose);
checkClassHierarchyNodes(
compilerNormal,
compilerDeserialized,
- compilerNormal.world.getClassHierarchyNode(
- compilerNormal.coreClasses.objectClass),
+ compilerNormal.world
+ .getClassHierarchyNode(compilerNormal.coreClasses.objectClass),
compilerDeserialized.world.getClassHierarchyNode(
compilerDeserialized.coreClasses.objectClass),
verbose: verbose);
- Expect.equals(compilerNormal.enabledInvokeOn,
+ Expect.equals(
+ compilerNormal.enabledInvokeOn,
compilerDeserialized.enabledInvokeOn,
"Compiler.enabledInvokeOn mismatch");
- Expect.equals(compilerNormal.enabledFunctionApply,
+ Expect.equals(
+ compilerNormal.enabledFunctionApply,
compilerDeserialized.enabledFunctionApply,
"Compiler.enabledFunctionApply mismatch");
- Expect.equals(compilerNormal.enabledRuntimeType,
+ Expect.equals(
+ compilerNormal.enabledRuntimeType,
compilerDeserialized.enabledRuntimeType,
"Compiler.enabledRuntimeType mismatch");
- Expect.equals(compilerNormal.hasIsolateSupport,
+ Expect.equals(
+ compilerNormal.hasIsolateSupport,
compilerDeserialized.hasIsolateSupport,
"Compiler.hasIsolateSupport mismatch");
Expect.equals(
@@ -175,57 +171,56 @@
failOnUnfound: false,
failOnExtra: false,
onSameElement: (ConstantValue value1, ConstantValue value2) {
- OutputUnit outputUnit1 = constants1[value1];
- OutputUnit outputUnit2 = constants2[value2];
- checkOutputUnits(outputUnit1, outputUnit2,
- 'for ${value1.toStructuredText()} '
- 'vs ${value2.toStructuredText()}');
- },
- onUnfoundElement: (ConstantValue value1) {
- OutputUnit outputUnit1 = constants1[value1];
- Expect.isTrue(outputUnit1.isMainOutput,
- "Missing deferred constant: ${value1.toStructuredText()}");
- },
- onExtraElement: (ConstantValue value2) {
- OutputUnit outputUnit2 = constants2[value2];
- Expect.isTrue(outputUnit2.isMainOutput,
- "Extra deferred constant: ${value2.toStructuredText()}");
- },
- elementToString: (a) {
- return '${a.toStructuredText()} -> ${constants1[a]}/${constants2[a]}';
- });
+ OutputUnit outputUnit1 = constants1[value1];
+ OutputUnit outputUnit2 = constants2[value2];
+ checkOutputUnits(
+ outputUnit1,
+ outputUnit2,
+ 'for ${value1.toStructuredText()} '
+ 'vs ${value2.toStructuredText()}');
+ }, onUnfoundElement: (ConstantValue value1) {
+ OutputUnit outputUnit1 = constants1[value1];
+ Expect.isTrue(outputUnit1.isMainOutput,
+ "Missing deferred constant: ${value1.toStructuredText()}");
+ }, onExtraElement: (ConstantValue value2) {
+ OutputUnit outputUnit2 = constants2[value2];
+ Expect.isTrue(outputUnit2.isMainOutput,
+ "Extra deferred constant: ${value2.toStructuredText()}");
+ }, elementToString: (a) {
+ return '${a.toStructuredText()} -> ${constants1[a]}/${constants2[a]}';
+ });
});
}
void checkElements(
- Compiler compiler1, Compiler compiler2,
- Element element1, Element element2,
+ Compiler compiler1, Compiler compiler2, Element element1, Element element2,
{bool verbose: false}) {
if (element1.isFunction ||
element1.isConstructor ||
(element1.isField && element1.isInstanceMember)) {
AstElement astElement1 = element1;
AstElement astElement2 = element2;
- ClosureClassMap closureData1 =
- compiler1.closureToClassMapper.computeClosureToClassMapping(
- astElement1.resolvedAst);
- ClosureClassMap closureData2 =
- compiler2.closureToClassMapper.computeClosureToClassMapping(
- astElement2.resolvedAst);
+ ClosureClassMap closureData1 = compiler1.closureToClassMapper
+ .computeClosureToClassMapping(astElement1.resolvedAst);
+ ClosureClassMap closureData2 = compiler2.closureToClassMapper
+ .computeClosureToClassMapping(astElement2.resolvedAst);
- checkElementIdentities(closureData1, closureData2,
+ checkElementIdentities(
+ closureData1,
+ closureData2,
'$element1.closureElement',
- closureData1.closureElement, closureData2.closureElement);
- checkElementIdentities(closureData1, closureData2,
+ closureData1.closureElement,
+ closureData2.closureElement);
+ checkElementIdentities(
+ closureData1,
+ closureData2,
'$element1.closureClassElement',
- closureData1.closureClassElement, closureData2.closureClassElement);
- checkElementIdentities(closureData1, closureData2,
- '$element1.callElement',
+ closureData1.closureClassElement,
+ closureData2.closureClassElement);
+ checkElementIdentities(closureData1, closureData2, '$element1.callElement',
closureData1.callElement, closureData2.callElement);
- check(closureData1, closureData2,
- '$element1.thisLocal',
- closureData1.thisLocal, closureData2.thisLocal,
- areLocalsEquivalent);
+ check(closureData1, closureData2, '$element1.thisLocal',
+ closureData1.thisLocal, closureData2.thisLocal, areLocalsEquivalent);
checkMaps(
closureData1.freeVariableMap,
closureData2.freeVariableMap,
@@ -250,24 +245,16 @@
if (element1 is MemberElement && element2 is MemberElement) {
MemberElement member1 = element1.implementation;
MemberElement member2 = element2.implementation;
- checkSets(
- member1.nestedClosures,
- member2.nestedClosures,
- "$member1.nestedClosures",
- areElementsEquivalent,
- verbose: verbose,
+ checkSets(member1.nestedClosures, member2.nestedClosures,
+ "$member1.nestedClosures", areElementsEquivalent, verbose: verbose,
onSameElement: (a, b) {
- LocalFunctionElement localFunction1 = a.expression;
- LocalFunctionElement localFunction2 = b.expression;
- checkElementIdentities(
- localFunction1, localFunction2,
- 'enclosingClass',
- localFunction1.enclosingClass, localFunction2.enclosingClass);
- testResolvedAstEquivalence(
- localFunction1.resolvedAst,
- localFunction2.resolvedAst,
- const CheckStrategy());
- });
+ LocalFunctionElement localFunction1 = a.expression;
+ LocalFunctionElement localFunction2 = b.expression;
+ checkElementIdentities(localFunction1, localFunction2, 'enclosingClass',
+ localFunction1.enclosingClass, localFunction2.enclosingClass);
+ testResolvedAstEquivalence(localFunction1.resolvedAst,
+ localFunction2.resolvedAst, const CheckStrategy());
+ });
}
}
JavaScriptBackend backend1 = compiler1.backend;
@@ -280,30 +267,24 @@
checkElementOutputUnits(compiler1, compiler2, element1, element2);
}
-void checkMixinUses(
- Compiler compiler1, Compiler compiler2,
- ClassElement class1, ClassElement class2,
+void checkMixinUses(Compiler compiler1, Compiler compiler2, ClassElement class1,
+ ClassElement class2,
{bool verbose: false}) {
-
checkSets(
compiler1.world.mixinUsesOf(class1),
compiler2.world.mixinUsesOf(class2),
"Mixin uses of $class1 vs $class2",
areElementsEquivalent,
verbose: verbose);
-
}
-void checkClassHierarchyNodes(
- Compiler compiler1,
- Compiler compiler2,
+void checkClassHierarchyNodes(Compiler compiler1, Compiler compiler2,
ClassHierarchyNode node1, ClassHierarchyNode node2,
{bool verbose: false}) {
if (verbose) {
print('Checking $node1 vs $node2');
}
- Expect.isTrue(
- areElementsEquivalent(node1.cls, node2.cls),
+ Expect.isTrue(areElementsEquivalent(node1.cls, node2.cls),
"Element identity mismatch for ${node1.cls} vs ${node2.cls}.");
Expect.equals(
node1.isDirectlyInstantiated,
@@ -321,8 +302,8 @@
bool found = false;
for (ClassHierarchyNode other in node2.directSubclasses) {
if (areElementsEquivalent(child.cls, other.cls)) {
- checkClassHierarchyNodes(compiler1, compiler2,
- child, other, verbose: verbose);
+ checkClassHierarchyNodes(compiler1, compiler2, child, other,
+ verbose: verbose);
found = true;
break;
}
@@ -331,14 +312,15 @@
if (child.isInstantiated) {
print('Missing subclass ${child.cls} of ${node1.cls} '
'in ${node2.directSubclasses}');
- print(compiler1.world.dump(
- verbose ? compiler1.coreClasses.objectClass : node1.cls));
- print(compiler2.world.dump(
- verbose ? compiler2.coreClasses.objectClass : node2.cls));
+ print(compiler1.world
+ .dump(verbose ? compiler1.coreClasses.objectClass : node1.cls));
+ print(compiler2.world
+ .dump(verbose ? compiler2.coreClasses.objectClass : node2.cls));
}
- Expect.isFalse(child.isInstantiated,
+ Expect.isFalse(
+ child.isInstantiated,
'Missing subclass ${child.cls} of ${node1.cls} in '
- '${node2.directSubclasses}');
+ '${node2.directSubclasses}');
}
}
checkMixinUses(compiler1, compiler2, node1.cls, node2.cls, verbose: verbose);
@@ -361,7 +343,7 @@
if (a == null || b == null) return false;
if (a is ClosureFieldElement && b is ClosureFieldElement) {
return areElementsEquivalent(a.closureClass, b.closureClass) &&
- areLocalsEquivalent(a.local, b.local);
+ areLocalsEquivalent(a.local, b.local);
} else if (a is BoxFieldElement && b is BoxFieldElement) {
return areElementsEquivalent(a.variableElement, b.variableElement) &&
areLocalsEquivalent(a.box, b.box);
@@ -375,13 +357,14 @@
if (!areLocalsEquivalent(a.boxElement, b.boxElement)) {
return false;
}
- checkMaps(a.capturedVariables, b.capturedVariables,
+ checkMaps(
+ a.capturedVariables,
+ b.capturedVariables,
'ClosureScope.capturedVariables',
areLocalsEquivalent,
areElementsEquivalent);
checkSets(a.boxedLoopVariables, b.boxedLoopVariables,
- 'ClosureScope.boxedLoopVariables',
- areElementsEquivalent);
+ 'ClosureScope.boxedLoopVariables', areElementsEquivalent);
return true;
}
@@ -393,8 +376,7 @@
return '(${node.runtimeType}) $text';
}
-void checkElementOutputUnits(
- Compiler compiler1, Compiler compiler2,
+void checkElementOutputUnits(Compiler compiler1, Compiler compiler2,
Element element1, Element element2) {
OutputUnit outputUnit1 =
compiler1.deferredLoadTask.getOutputUnitForElementForTesting(element1);
@@ -406,11 +388,13 @@
void checkOutputUnits(
OutputUnit outputUnit1, OutputUnit outputUnit2, String message) {
if (outputUnit1 == null && outputUnit2 == null) return;
- check(outputUnit1, outputUnit2,
- 'OutputUnit.isMainOutput $message',
+ check(outputUnit1, outputUnit2, 'OutputUnit.isMainOutput $message',
outputUnit1.isMainOutput, outputUnit2.isMainOutput);
- checkSetEquivalence(outputUnit1, outputUnit2,
+ checkSetEquivalence(
+ outputUnit1,
+ outputUnit2,
'OutputUnit.imports $message',
- outputUnit1.imports, outputUnit2.imports,
+ outputUnit1.imports,
+ outputUnit2.imports,
(a, b) => areElementsEquivalent(a.declaration, b.declaration));
}
diff --git a/tests/compiler/dart2js/serialization/native_data_test.dart b/tests/compiler/dart2js/serialization/native_data_test.dart
index d2a9173..04e3ab4 100644
--- a/tests/compiler/dart2js/serialization/native_data_test.dart
+++ b/tests/compiler/dart2js/serialization/native_data_test.dart
@@ -50,28 +50,16 @@
NativeData nativeData1 = backend1.nativeData;
NativeData nativeData2 = backend2.nativeData;
- checkMaps(
- nativeData1.jsInteropNames,
- nativeData2.jsInteropNames,
- "NativeData.jsInteropNames",
- areElementsEquivalent,
- equality,
+ checkMaps(nativeData1.jsInteropNames, nativeData2.jsInteropNames,
+ "NativeData.jsInteropNames", areElementsEquivalent, equality,
verbose: verbose);
- checkMaps(
- nativeData1.nativeMemberName,
- nativeData2.nativeMemberName,
- "NativeData.nativeMemberName",
- areElementsEquivalent,
- equality,
+ checkMaps(nativeData1.nativeMemberName, nativeData2.nativeMemberName,
+ "NativeData.nativeMemberName", areElementsEquivalent, equality,
verbose: verbose);
- checkMaps(
- nativeData1.nativeClassTagInfo,
- nativeData2.nativeClassTagInfo,
- "NativeData.nativeClassTagInfo",
- areElementsEquivalent,
- equality,
+ checkMaps(nativeData1.nativeClassTagInfo, nativeData2.nativeClassTagInfo,
+ "NativeData.nativeClassTagInfo", areElementsEquivalent, equality,
verbose: verbose);
checkMaps(
diff --git a/tests/compiler/dart2js/serialization/reserialization_test.dart b/tests/compiler/dart2js/serialization/reserialization_test.dart
index 2f56e2e..59fae6c 100644
--- a/tests/compiler/dart2js/serialization/reserialization_test.dart
+++ b/tests/compiler/dart2js/serialization/reserialization_test.dart
@@ -55,15 +55,15 @@
LibraryElement library2 = libraries2.firstWhere((LibraryElement library2) {
return library2.canonicalUri == library1.canonicalUri;
});
- Expect.isNotNull(library2,
- "No library found for ${library1.canonicalUri}.");
+ Expect.isNotNull(
+ library2, "No library found for ${library1.canonicalUri}.");
checkLibraryContent('library1', 'library2', 'library', library1, library2);
LibraryElement library3 = libraries3.firstWhere((LibraryElement library3) {
return library3.canonicalUri == library1.canonicalUri;
});
- Expect.isNotNull(library3,
- "No library found for ${library1.canonicalUri}.");
+ Expect.isNotNull(
+ library3, "No library found for ${library1.canonicalUri}.");
checkLibraryContent('library1', 'library3', 'library', library1, library3);
}
diff --git a/tests/compiler/dart2js/serialization/resolved_ast_test.dart b/tests/compiler/dart2js/serialization/resolved_ast_test.dart
index d39f906..f18a7b6 100644
--- a/tests/compiler/dart2js/serialization/resolved_ast_test.dart
+++ b/tests/compiler/dart2js/serialization/resolved_ast_test.dart
@@ -16,7 +16,6 @@
import 'test_data.dart';
import 'test_helper.dart';
-
main(List<String> args) {
Arguments arguments = new Arguments.from(args);
asyncTest(() async {
@@ -35,14 +34,10 @@
});
}
-Future check(
- SerializedData serializedData,
- Uri entryPoint,
- [Map<String, String> sourceFiles = const <String, String>{}]) async {
-
- Compiler compilerNormal = compilerFor(
- memorySourceFiles: sourceFiles,
- options: [Flags.analyzeAll]);
+Future check(SerializedData serializedData, Uri entryPoint,
+ [Map<String, String> sourceFiles = const <String, String>{}]) async {
+ Compiler compilerNormal =
+ compilerFor(memorySourceFiles: sourceFiles, options: [Flags.analyzeAll]);
compilerNormal.resolution.retainCachesForTesting = true;
await compilerNormal.run(entryPoint);
diff --git a/tests/compiler/dart2js/serialization/test_data.dart b/tests/compiler/dart2js/serialization/test_data.dart
index d4b8434..c3f7bef 100644
--- a/tests/compiler/dart2js/serialization/test_data.dart
+++ b/tests/compiler/dart2js/serialization/test_data.dart
@@ -7,15 +7,18 @@
const List<Test> TESTS = const <Test>[
// These tests are very long-running and put here first to compile them on
// their own tests.
- const Test('Disable tree shaking through reflection', const {
- 'main.dart': '''
+ const Test(
+ 'Disable tree shaking through reflection',
+ const {
+ 'main.dart': '''
import 'dart:mirrors';
main() {
reflect(null).invoke(#toString, []).reflectee;
}
''',
- }, expectedWarningCount: 1),
+ },
+ expectedWarningCount: 1),
const Test('Use of dart:indexed_db', const {
'main.dart': '''
@@ -30,19 +33,14 @@
}),
// These tests
- const Test('Empty program', const {
- 'main.dart': 'main() {}'
- }),
+ const Test('Empty program', const {'main.dart': 'main() {}'}),
- const Test('Hello World', const {
- 'main.dart': 'main() => print("Hello World");'
- }),
+ const Test(
+ 'Hello World', const {'main.dart': 'main() => print("Hello World");'}),
- const Test('Too many arguments to print', const {
- 'main.dart': 'main() => print("Hello World", 0);'
- },
- expectedWarningCount: 1,
- expectedInfoCount: 1),
+ const Test('Too many arguments to print',
+ const {'main.dart': 'main() => print("Hello World", 0);'},
+ expectedWarningCount: 1, expectedInfoCount: 1),
const Test('Hello World with string interpolation', const {
'main.dart': r'''
@@ -52,15 +50,17 @@
}'''
}),
- const Test('Too many arguments to print with string interpolation', const {
- 'main.dart': r'''
+ const Test(
+ 'Too many arguments to print with string interpolation',
+ const {
+ 'main.dart': r'''
main() {
String text = "Hello World";
print('$text', text);
}'''
- },
- expectedWarningCount: 1,
- expectedInfoCount: 1),
+ },
+ expectedWarningCount: 1,
+ expectedInfoCount: 1),
const Test('Print main arguments', const {
'main.dart': r'''
@@ -70,13 +70,13 @@
}),
const Test('For loop on main arguments', const {
- 'main.dart': r'''
+ 'main.dart': r'''
main(List<String> arguments) {
for (int i = 0; i < arguments.length; i++) {
print(arguments[i]);
}
}'''
- }),
+ }),
const Test('For-in loop on main arguments', const {
'main.dart': r'''
@@ -95,14 +95,16 @@
}'''
}),
- const Test('Simple class implements Function without call method', const {
- 'main.dart': r'''
+ const Test(
+ 'Simple class implements Function without call method',
+ const {
+ 'main.dart': r'''
class Class implements Function {}
main() {
print(new Class());
}'''
- },
- expectedWarningCount: 1),
+ },
+ expectedWarningCount: 1),
const Test('Simple class implements Function with call method', const {
'main.dart': r'''
@@ -124,43 +126,51 @@
}'''
}),
- const Test('Implement Comparable with two many type arguments', const {
- 'main.dart': r'''
+ const Test(
+ 'Implement Comparable with two many type arguments',
+ const {
+ 'main.dart': r'''
class Class implements Comparable<Class, Class> {
int compareTo(other) => 0;
}
main() {
print(new Class());
}'''
- },
- expectedWarningCount: 1),
+ },
+ expectedWarningCount: 1),
- const Test('Implement Comparable with incompatible parameter types', const {
- 'main.dart': r'''
+ const Test(
+ 'Implement Comparable with incompatible parameter types',
+ const {
+ 'main.dart': r'''
class Class implements Comparable<Class> {
int compareTo(String other) => 0;
}
main() {
print(new Class().compareTo(null));
}'''
- },
- expectedWarningCount: 1,
- expectedInfoCount: 1),
+ },
+ expectedWarningCount: 1,
+ expectedInfoCount: 1),
- const Test('Implement Comparable with incompatible parameter count', const {
- 'main.dart': r'''
+ const Test(
+ 'Implement Comparable with incompatible parameter count',
+ const {
+ 'main.dart': r'''
class Class implements Comparable {
bool compareTo(a, b) => true;
}
main() {
print(new Class().compareTo(null, null));
}'''
- },
- expectedWarningCount: 1,
- expectedInfoCount: 1),
+ },
+ expectedWarningCount: 1,
+ expectedInfoCount: 1),
- const Test('Implement Random and call nextInt directly', const {
- 'main.dart': r'''
+ const Test(
+ 'Implement Random and call nextInt directly',
+ const {
+ 'main.dart': r'''
import 'dart:math';
class MyRandom implements Random {
@@ -173,9 +183,9 @@
main() {
new MyRandom().nextInt(0);
}'''
- },
- expectedWarningCount: 1,
- expectedInfoCount: 0),
+ },
+ expectedWarningCount: 1,
+ expectedInfoCount: 0),
const Test('Implement Random and do not call nextInt', const {
'main.dart': r'''
@@ -193,8 +203,10 @@
}'''
}),
- const Test('Implement Random and call nextInt through native code', const {
- 'main.dart': r'''
+ const Test(
+ 'Implement Random and call nextInt through native code',
+ const {
+ 'main.dart': r'''
import 'dart:math';
class MyRandom implements Random {
@@ -210,9 +222,9 @@
// method.
[].shuffle(new MyRandom());
}'''
- },
- expectedWarningCount: 1,
- expectedInfoCount: 0),
+ },
+ expectedWarningCount: 1,
+ expectedInfoCount: 0),
const Test('Handle break and continue', const {
'main.dart': '''
@@ -278,9 +290,8 @@
''',
}),
- const Test('Call forwarding constructor on named mixin application',
- const {
- 'main.dart': '''
+ const Test('Call forwarding constructor on named mixin application', const {
+ 'main.dart': '''
import 'dart:collection';
main() => new UnmodifiableListView(null);
''',
@@ -304,13 +315,15 @@
''',
}),
- const Test('Call forwarding constructor on named mixin application, no args.',
+ const Test(
+ 'Call forwarding constructor on named mixin application, no args.',
const {
'main.dart': '''
import 'lib.dart';
main() => new C();
''',
- }, preserializedSourceFiles: const {
+ },
+ preserializedSourceFiles: const {
'lib.dart': '''
class M {}
class S {}
@@ -318,13 +331,15 @@
''',
}),
- const Test('Call forwarding constructor on named mixin application, one arg.',
+ const Test(
+ 'Call forwarding constructor on named mixin application, one arg.',
const {
'main.dart': '''
import 'lib.dart';
main() => new C(0);
''',
- }, preserializedSourceFiles: const {
+ },
+ preserializedSourceFiles: const {
'lib.dart': '''
class M {}
class S {
@@ -334,12 +349,14 @@
''',
}),
- const Test('Import mirrors, thus checking import paths', const {
- 'main.dart': '''
+ const Test(
+ 'Import mirrors, thus checking import paths',
+ const {
+ 'main.dart': '''
import 'dart:mirrors';
main() {}
''',
- },
+ },
expectedWarningCount: 1),
const Test('Serialized symbol literal', const {
@@ -514,7 +531,7 @@
''',
'b.dart': '''
''',
-}),
+ }),
const Test('Deferred prefix loadLibrary', const {
'main.dart': '''
@@ -535,42 +552,50 @@
''',
}),
- const Test('Deferred without prefix', const {
- 'main.dart': '''
+ const Test(
+ 'Deferred without prefix',
+ const {
+ 'main.dart': '''
import 'a.dart';
main() {
test();
}
''',
- }, preserializedSourceFiles: const {
- 'a.dart': '''
+ },
+ preserializedSourceFiles: const {
+ 'a.dart': '''
import 'b.dart' deferred;
test() {}
''',
- 'b.dart': '''
+ 'b.dart': '''
''',
- }, expectedErrorCount: 1),
+ },
+ expectedErrorCount: 1),
- const Test('Deferred with duplicate prefix', const {
- 'main.dart': '''
+ const Test(
+ 'Deferred with duplicate prefix',
+ const {
+ 'main.dart': '''
import 'a.dart';
main() {
test();
}
''',
- }, preserializedSourceFiles: const {
- 'a.dart': '''
+ },
+ preserializedSourceFiles: const {
+ 'a.dart': '''
import 'b.dart' deferred as pre;
import 'c.dart' deferred as pre;
test() {}
''',
- 'b.dart': '''
+ 'b.dart': '''
''',
- 'c.dart': '''
+ 'c.dart': '''
''',
- }, expectedErrorCount: 1),
+ },
+ expectedErrorCount: 1),
const Test('Closure in operator function', const {
'main.dart': '''
@@ -590,23 +615,27 @@
''',
}),
- const Test('Checked setter', const {
- 'main.dart': '''
+ const Test(
+ 'Checked setter',
+ const {
+ 'main.dart': '''
import 'a.dart';
main() {
test();
}
''',
- }, preserializedSourceFiles: const {
- 'a.dart': '''
+ },
+ preserializedSourceFiles: const {
+ 'a.dart': '''
class C {
set foo(int i) {}
}
test() => new C().foo = 0;
''',
- }, checkedMode: true),
+ },
+ checkedMode: true),
const Test('Deferred access', const {
'main.dart': '''
@@ -659,12 +688,12 @@
const Test('Deferred static access', const {},
preserializedSourceFiles: const {
- 'main.dart': '''
+ 'main.dart': '''
import 'b.dart' deferred as prefix;
main() => prefix.loadLibrary().then((_) => prefix.test2());
''',
- 'b.dart': '''
+ 'b.dart': '''
test2() => x;
var x = const ConstClass(const ConstClass(1));
class ConstClass {
@@ -672,7 +701,7 @@
const ConstClass(this.x);
}
''',
- }),
+ }),
const Test('Multi variable declaration', const {
'main.dart': '''
@@ -686,9 +715,8 @@
''',
}),
- const Test('Double values', const {},
- preserializedSourceFiles: const {
- 'main.dart': '''
+ const Test('Double values', const {}, preserializedSourceFiles: const {
+ 'main.dart': '''
const a = 1e+400;
main() => a;
''',
@@ -696,27 +724,28 @@
const Test('Erroneous constructor', const {},
preserializedSourceFiles: const {
- 'main.dart': '''
-main() => new Null();
-'''}),
-
- const Test('Metadata on imports', const {},
- preserializedSourceFiles: const {
'main.dart': '''
+main() => new Null();
+'''
+ }),
+
+ const Test('Metadata on imports', const {}, preserializedSourceFiles: const {
+ 'main.dart': '''
@deprecated
import 'main.dart';
main() {}
-'''}),
+'''
+ }),
- const Test('Metadata on exports', const {},
- preserializedSourceFiles: const {
- 'main.dart': '''
+ const Test('Metadata on exports', const {}, preserializedSourceFiles: const {
+ 'main.dart': '''
@deprecated
export 'main.dart';
main() {}
-'''}),
+'''
+ }),
const Test('Metadata on part tags', const {},
preserializedSourceFiles: const {
@@ -727,11 +756,13 @@
part 'a.dart';
main() {}
-'''},
+'''
+ },
unserializedSourceFiles: const {
'a.dart': '''
part of main;
-'''}),
+'''
+ }),
const Test('Metadata on part-of tags', const {},
preserializedSourceFiles: const {
@@ -741,27 +772,29 @@
part 'a.dart';
main() {}
-'''},
+'''
+ },
unserializedSourceFiles: const {
'a.dart': '''
@deprecated
part of main;
-'''}),
+'''
+ }),
- const Test('Ambiguous elements', const {},
- preserializedSourceFiles: const {
- 'main.dart': '''
+ const Test('Ambiguous elements', const {}, preserializedSourceFiles: const {
+ 'main.dart': '''
import 'a.dart';
import 'b.dart';
main() => new foo();
''',
- 'a.dart': '''
+ 'a.dart': '''
var foo;
''',
- 'b.dart': '''
+ 'b.dart': '''
var foo;
-''',}),
+''',
+ }),
const Test('html and mirrors', const {},
preserializedSourceFiles: const {
@@ -769,7 +802,8 @@
import 'dart:html';
import 'dart:mirrors';
main() {}
-'''},
+'''
+ },
expectedWarningCount: 1),
];
@@ -784,9 +818,7 @@
final int expectedInfoCount;
final bool checkedMode;
- const Test(
- this.name,
- this.sourceFiles,
+ const Test(this.name, this.sourceFiles,
{this.preserializedSourceFiles,
this.unserializedSourceFiles,
this.expectedErrorCount: 0,
diff --git a/tests/compiler/dart2js/serialization/test_helper.dart b/tests/compiler/dart2js/serialization/test_helper.dart
index f5d986d..db97fc4 100644
--- a/tests/compiler/dart2js/serialization/test_helper.dart
+++ b/tests/compiler/dart2js/serialization/test_helper.dart
@@ -26,7 +26,8 @@
final Object value1;
final Object value2;
- Check(this.parent, this.object1, this.object2, this.property, this.value1, this.value2);
+ Check(this.parent, this.object1, this.object2, this.property, this.value1,
+ this.value2);
String printOn(StringBuffer sb, String indent) {
if (parent != null) {
@@ -59,62 +60,55 @@
@override
bool test(var object1, var object2, String property, var value1, var value2,
- [bool equivalence(a, b) = equality]) {
+ [bool equivalence(a, b) = equality]) {
return check(object1, object2, property, value1, value2, equivalence);
}
@override
bool testLists(
- Object object1, Object object2, String property,
- List list1, List list2,
+ Object object1, Object object2, String property, List list1, List list2,
[bool elementEquivalence(a, b) = equality]) {
- return checkListEquivalence(
- object1, object2, property, list1, list2,
+ return checkListEquivalence(object1, object2, property, list1, list2,
(o1, o2, p, v1, v2) {
- if (!elementEquivalence(v1, v2)) {
- throw "$o1.$p = '${v1}' <> "
- "$o2.$p = '${v2}'";
- }
- return true;
- });
+ if (!elementEquivalence(v1, v2)) {
+ throw "$o1.$p = '${v1}' <> "
+ "$o2.$p = '${v2}'";
+ }
+ return true;
+ });
}
@override
bool testSets(
- var object1, var object2, String property,
- Iterable set1, Iterable set2,
+ var object1, var object2, String property, Iterable set1, Iterable set2,
[bool elementEquivalence(a, b) = equality]) {
return checkSetEquivalence(
- object1, object2,property, set1, set2, elementEquivalence);
+ object1, object2, property, set1, set2, elementEquivalence);
}
@override
- bool testMaps(
- var object1, var object2, String property, Map map1, Map map2,
+ bool testMaps(var object1, var object2, String property, Map map1, Map map2,
[bool keyEquivalence(a, b) = equality,
bool valueEquivalence(a, b) = equality]) {
- return checkMapEquivalence(object1, object2, property,
- map1, map2, keyEquivalence, valueEquivalence);
+ return checkMapEquivalence(object1, object2, property, map1, map2,
+ keyEquivalence, valueEquivalence);
}
@override
- bool testElements(
- Object object1, Object object2, String property,
+ bool testElements(Object object1, Object object2, String property,
Element element1, Element element2) {
return checkElementIdentities(
object1, object2, property, element1, element2);
}
@override
- bool testTypes(
- Object object1, Object object2, String property,
+ bool testTypes(Object object1, Object object2, String property,
DartType type1, DartType type2) {
return checkTypes(object1, object2, property, type1, type2);
}
@override
- bool testConstants(
- Object object1, Object object2, String property,
+ bool testConstants(Object object1, Object object2, String property,
ConstantExpression exp1, ConstantExpression exp2) {
return checkConstants(object1, object2, property, exp1, exp2);
}
@@ -126,17 +120,14 @@
}
@override
- bool testTypeLists(
- Object object1, Object object2, String property,
+ bool testTypeLists(Object object1, Object object2, String property,
List<DartType> list1, List<DartType> list2) {
return checkTypeLists(object1, object2, property, list1, list2);
}
@override
- bool testConstantLists(
- Object object1, Object object2, String property,
- List<ConstantExpression> list1,
- List<ConstantExpression> list2) {
+ bool testConstantLists(Object object1, Object object2, String property,
+ List<ConstantExpression> list1, List<ConstantExpression> list2) {
return checkConstantLists(object1, object2, property, list1, list2);
}
@@ -147,19 +138,19 @@
}
@override
- bool testNodes(Object object1, Object object2, String property,
- Node node1, Node node2) {
- return new NodeEquivalenceVisitor(this).testNodes(
- object1, object2, property, node1, node2);
+ bool testNodes(
+ Object object1, Object object2, String property, Node node1, Node node2) {
+ return new NodeEquivalenceVisitor(this)
+ .testNodes(object1, object2, property, node1, node2);
}
}
/// Check that the values [property] of [object1] and [object2], [value1] and
/// [value2] respectively, are equal and throw otherwise.
bool check(var object1, var object2, String property, var value1, var value2,
- [bool equivalence(a, b) = equality]) {
- currentCheck = new Check(
- currentCheck, object1, object2, property, value1, value2);
+ [bool equivalence(a, b) = equality]) {
+ currentCheck =
+ new Check(currentCheck, object1, object2, property, value1, value2);
if (!equivalence(value1, value2)) {
throw currentCheck;
}
@@ -172,26 +163,26 @@
///
/// Uses [object1], [object2] and [property] to provide context for failures.
bool checkListEquivalence(
- Object object1, Object object2, String property,
- Iterable list1, Iterable list2,
+ Object object1,
+ Object object2,
+ String property,
+ Iterable list1,
+ Iterable list2,
void checkEquivalence(o1, o2, property, a, b)) {
currentCheck =
new Check(currentCheck, object1, object2, property, list1, list2);
for (int i = 0; i < list1.length && i < list2.length; i++) {
checkEquivalence(
- object1, object2, property,
- list1.elementAt(i), list2.elementAt(i));
+ object1, object2, property, list1.elementAt(i), list2.elementAt(i));
}
for (int i = list1.length; i < list2.length; i++) {
- throw
- 'Missing equivalent for element '
+ throw 'Missing equivalent for element '
'#$i ${list2.elementAt(i)} in `${property}` on $object2.\n'
'`${property}` on $object1:\n ${list1.join('\n ')}\n'
'`${property}` on $object2:\n ${list2.join('\n ')}';
}
for (int i = list2.length; i < list1.length; i++) {
- throw
- 'Missing equivalent for element '
+ throw 'Missing equivalent for element '
'#$i ${list1.elementAt(i)} in `${property}` on $object1.\n'
'`${property}` on $object1:\n ${list1.join('\n ')}\n'
'`${property}` on $object2:\n ${list2.join('\n ')}';
@@ -207,12 +198,8 @@
/// but not in [set2] are added to [unfound], and the set of elements in [set2]
/// but not in [set1] are returned.
Set computeSetDifference(
- Iterable set1,
- Iterable set2,
- List<List> common,
- List unfound,
- {bool sameElement(a, b): equality,
- void checkElements(a, b)}) {
+ Iterable set1, Iterable set2, List<List> common, List unfound,
+ {bool sameElement(a, b): equality, void checkElements(a, b)}) {
// TODO(johnniwinther): Avoid the quadratic cost here. Some ideas:
// - convert each set to a list and sort it first, then compare by walking
// both lists in parallel
@@ -245,22 +232,15 @@
/// [elementEquivalence] to compute the pair-wise equivalence.
///
/// Uses [object1], [object2] and [property] to provide context for failures.
-bool checkSetEquivalence(
- var object1,
- var object2,
- String property,
- Iterable set1,
- Iterable set2,
- bool sameElement(a, b),
+bool checkSetEquivalence(var object1, var object2, String property,
+ Iterable set1, Iterable set2, bool sameElement(a, b),
{void onSameElement(a, b)}) {
List<List> common = <List>[];
List unfound = [];
- Set remaining =
- computeSetDifference(set1, set2, common, unfound,
- sameElement: sameElement, checkElements: onSameElement);
+ Set remaining = computeSetDifference(set1, set2, common, unfound,
+ sameElement: sameElement, checkElements: onSameElement);
if (unfound.isNotEmpty || remaining.isNotEmpty) {
- String message =
- "Set mismatch for `$property` on $object1 vs $object2: \n"
+ String message = "Set mismatch for `$property` on $object1 vs $object2: \n"
"Common:\n ${common.join('\n ')}\n"
"Unfound:\n ${unfound.join('\n ')}\n"
"Extra: \n ${remaining.join('\n ')}";
@@ -273,19 +253,12 @@
/// [elementEquivalence] to compute the pair-wise equivalence.
///
/// Uses [object1], [object2] and [property] to provide context for failures.
-bool checkMapEquivalence(
- var object1,
- var object2,
- String property,
- Map map1,
- Map map2,
- bool sameKey(a, b),
- bool sameValue(a, b)) {
+bool checkMapEquivalence(var object1, var object2, String property, Map map1,
+ Map map2, bool sameKey(a, b), bool sameValue(a, b)) {
List<List> common = <List>[];
List unfound = [];
- Set remaining =
- computeSetDifference(map1.keys, map2.keys, common, unfound,
- sameElement: sameKey);
+ Set remaining = computeSetDifference(map1.keys, map2.keys, common, unfound,
+ sameElement: sameKey);
if (unfound.isNotEmpty || remaining.isNotEmpty) {
String message =
"Map key mismatch for `$property` on $object1 vs $object2: \n"
@@ -295,8 +268,8 @@
throw message;
}
for (List pair in common) {
- check(object1, object2, 'Map value for `$property`',
- map1[pair[0]], map2[pair[1]], sameValue);
+ check(object1, object2, 'Map value for `$property`', map1[pair[0]],
+ map2[pair[1]], sameValue);
}
return true;
}
@@ -305,32 +278,28 @@
/// and [element2].
///
/// Uses [object1], [object2] and [property] to provide context for failures.
-bool checkElementIdentities(
- Object object1, Object object2, String property,
+bool checkElementIdentities(Object object1, Object object2, String property,
Element element1, Element element2) {
if (identical(element1, element2)) return true;
- return check(object1, object2,
- property, element1, element2, areElementsEquivalent);
+ return check(
+ object1, object2, property, element1, element2, areElementsEquivalent);
}
/// Checks the pair-wise equivalence of the identity (but not properties) of the
/// elements in [list] and [list2].
///
/// Uses [object1], [object2] and [property] to provide context for failures.
-bool checkElementListIdentities(
- Object object1, Object object2, String property,
+bool checkElementListIdentities(Object object1, Object object2, String property,
Iterable<Element> list1, Iterable<Element> list2) {
return checkListEquivalence(
- object1, object2, property,
- list1, list2, checkElementIdentities);
+ object1, object2, property, list1, list2, checkElementIdentities);
}
/// Checks the equivalence of [type1] and [type2].
///
/// Uses [object1], [object2] and [property] to provide context for failures.
-bool checkTypes(
- Object object1, Object object2, String property,
- DartType type1, DartType type2) {
+bool checkTypes(Object object1, Object object2, String property, DartType type1,
+ DartType type2) {
if (identical(type1, type2)) return true;
if (type1 == null || type2 == null) {
return check(object1, object2, property, type1, type2);
@@ -343,8 +312,7 @@
/// Checks the pair-wise equivalence of the types in [list1] and [list2].
///
/// Uses [object1], [object2] and [property] to provide context for failures.
-bool checkTypeLists(
- Object object1, Object object2, String property,
+bool checkTypeLists(Object object1, Object object2, String property,
List<DartType> list1, List<DartType> list2) {
return checkListEquivalence(
object1, object2, property, list1, list2, checkTypes);
@@ -353,8 +321,7 @@
/// Checks the equivalence of [exp1] and [exp2].
///
/// Uses [object1], [object2] and [property] to provide context for failures.
-bool checkConstants(
- Object object1, Object object2, String property,
+bool checkConstants(Object object1, Object object2, String property,
ConstantExpression exp1, ConstantExpression exp2) {
if (identical(exp1, exp2)) return true;
if (exp1 == null || exp2 == null) {
@@ -368,42 +335,40 @@
/// Checks the equivalence of [value1] and [value2].
///
/// Uses [object1], [object2] and [property] to provide context for failures.
-bool checkConstantValues(
- Object object1, Object object2, String property,
+bool checkConstantValues(Object object1, Object object2, String property,
ConstantValue value1, ConstantValue value2) {
if (identical(value1, value2)) return true;
if (value1 == null || value2 == null) {
return check(object1, object2, property, value1, value2);
} else {
- return check(object1, object2, property, value1, value2,
- (a, b) => const ConstantValueEquivalence(
- const CheckStrategy()).visit(a, b));
+ return check(
+ object1,
+ object2,
+ property,
+ value1,
+ value2,
+ (a, b) =>
+ const ConstantValueEquivalence(const CheckStrategy()).visit(a, b));
}
}
/// Checks the pair-wise equivalence of the constants in [list1] and [list2].
///
/// Uses [object1], [object2] and [property] to provide context for failures.
-bool checkConstantLists(
- Object object1, Object object2, String property,
- List<ConstantExpression> list1,
- List<ConstantExpression> list2) {
+bool checkConstantLists(Object object1, Object object2, String property,
+ List<ConstantExpression> list1, List<ConstantExpression> list2) {
return checkListEquivalence(
- object1, object2, property,
- list1, list2, checkConstants);
+ object1, object2, property, list1, list2, checkConstants);
}
/// Checks the pair-wise equivalence of the constants values in [list1] and
/// [list2].
///
/// Uses [object1], [object2] and [property] to provide context for failures.
-bool checkConstantValueLists(
- Object object1, Object object2, String property,
- List<ConstantValue> list1,
- List<ConstantValue> list2) {
+bool checkConstantValueLists(Object object1, Object object2, String property,
+ List<ConstantValue> list1, List<ConstantValue> list2) {
return checkListEquivalence(
- object1, object2, property,
- list1, list2, checkConstantValues);
+ object1, object2, property, list1, list2, checkConstantValues);
}
/// Check member property equivalence between all members common to [compiler1]
@@ -413,10 +378,9 @@
Compiler compiler2,
bool hasProperty(Element member1),
void checkMemberProperties(Compiler compiler1, Element member1,
- Compiler compiler2, Element member2,
- {bool verbose}),
+ Compiler compiler2, Element member2,
+ {bool verbose}),
{bool verbose: false}) {
-
void checkMembers(Element member1, Element member2) {
if (member1.isClass && member2.isClass) {
ClassElement class1 = member1;
@@ -425,9 +389,7 @@
if (hasProperty(member1)) {
if (areElementsEquivalent(member1, member2)) {
- checkMemberProperties(
- compiler1, member1,
- compiler2, member2,
+ checkMemberProperties(compiler1, member1, compiler2, member2,
verbose: verbose);
}
}
@@ -456,9 +418,7 @@
}
if (areElementsEquivalent(member1, member2)) {
- checkMemberProperties(
- compiler1, member1,
- compiler2, member2,
+ checkMemberProperties(compiler1, member1, compiler2, member2,
verbose: verbose);
}
}
@@ -470,30 +430,22 @@
library1.forEachLocalMember((Element member1) {
checkMembers(member1, library2.localLookup(member1.name));
});
-
}
}
}
/// Check equivalence of all resolution impacts.
-void checkAllImpacts(
- Compiler compiler1,
- Compiler compiler2,
+void checkAllImpacts(Compiler compiler1, Compiler compiler2,
{bool verbose: false}) {
- checkLoadedLibraryMembers(
- compiler1,
- compiler2,
- (Element member1) {
- return compiler1.resolution.hasResolutionImpact(member1);
- },
- checkImpacts,
- verbose: verbose);
+ checkLoadedLibraryMembers(compiler1, compiler2, (Element member1) {
+ return compiler1.resolution.hasResolutionImpact(member1);
+ }, checkImpacts, verbose: verbose);
}
/// Check equivalence of resolution impact for [member1] and [member2].
-void checkImpacts(Compiler compiler1, Element member1,
- Compiler compiler2, Element member2,
- {bool verbose: false}) {
+void checkImpacts(
+ Compiler compiler1, Element member1, Compiler compiler2, Element member2,
+ {bool verbose: false}) {
ResolutionImpact impact1 = compiler1.resolution.getResolutionImpact(member1);
ResolutionImpact impact2 = compiler2.resolution.getResolutionImpact(member2);
@@ -514,10 +466,7 @@
}
void checkSets(
- Iterable set1,
- Iterable set2,
- String messagePrefix,
- bool sameElement(a, b),
+ Iterable set1, Iterable set2, String messagePrefix, bool sameElement(a, b),
{bool failOnUnfound: true,
bool failOnExtra: true,
bool verbose: false,
@@ -527,10 +476,8 @@
String elementToString(key): defaultToString}) {
List<List> common = <List>[];
List unfound = [];
- Set remaining = computeSetDifference(
- set1, set2, common, unfound,
- sameElement: sameElement,
- checkElements: onSameElement);
+ Set remaining = computeSetDifference(set1, set2, common, unfound,
+ sameElement: sameElement, checkElements: onSameElement);
if (onUnfoundElement != null) {
unfound.forEach(onUnfoundElement);
}
@@ -569,11 +516,7 @@
String defaultToString(obj) => '$obj';
-void checkMaps(
- Map map1,
- Map map2,
- String messagePrefix,
- bool sameKey(a, b),
+void checkMaps(Map map1, Map map2, String messagePrefix, bool sameKey(a, b),
bool sameValue(a, b),
{bool failOnUnfound: true,
bool failOnMismatch: true,
@@ -583,16 +526,14 @@
List<List> common = <List>[];
List unfound = [];
List<List> mismatch = <List>[];
- Set remaining = computeSetDifference(
- map1.keys, map2.keys, common, unfound,
- sameElement: sameKey,
- checkElements: (k1, k2) {
- var v1 = map1[k1];
- var v2 = map2[k2];
- if (!sameValue(v1, v2)) {
- mismatch.add([k1, k2]);
- }
- });
+ Set remaining = computeSetDifference(map1.keys, map2.keys, common, unfound,
+ sameElement: sameKey, checkElements: (k1, k2) {
+ var v1 = map1[k1];
+ var v2 = map2[k2];
+ if (!sameValue(v1, v2)) {
+ mismatch.add([k1, k2]);
+ }
+ });
StringBuffer sb = new StringBuffer();
sb.write("$messagePrefix:");
if (verbose) {
@@ -651,25 +592,17 @@
}
}
-void checkAllResolvedAsts(
- Compiler compiler1,
- Compiler compiler2,
+void checkAllResolvedAsts(Compiler compiler1, Compiler compiler2,
{bool verbose: false}) {
- checkLoadedLibraryMembers(
- compiler1,
- compiler2,
- (Element member1) {
- return member1 is ExecutableElement &&
- compiler1.resolution.hasResolvedAst(member1);
- },
- checkResolvedAsts,
- verbose: verbose);
+ checkLoadedLibraryMembers(compiler1, compiler2, (Element member1) {
+ return member1 is ExecutableElement &&
+ compiler1.resolution.hasResolvedAst(member1);
+ }, checkResolvedAsts, verbose: verbose);
}
-
/// Check equivalence of [impact1] and [impact2].
-void checkResolvedAsts(Compiler compiler1, Element member1,
- Compiler compiler2, Element member2,
+void checkResolvedAsts(
+ Compiler compiler1, Element member1, Compiler compiler2, Element member2,
{bool verbose: false}) {
if (!compiler2.serialization.isDeserialized(member2)) {
return;
@@ -683,8 +616,7 @@
print('Checking resolved asts for $member1 vs $member2');
}
- testResolvedAstEquivalence(
- resolvedAst1, resolvedAst2, const CheckStrategy());
+ testResolvedAstEquivalence(resolvedAst1, resolvedAst2, const CheckStrategy());
}
/// Returns the test arguments for testing the [index]th skipped test. The
@@ -710,7 +642,7 @@
if (index == 1 && skip != 0) {
return ['${skip}', segmentNumber(index)];
- } else if (index == count) {
+ } else if (index == count) {
return [segmentNumber(index - 1)];
} else {
return [segmentNumber(index - 1), segmentNumber(index)];
diff --git a/tests/compiler/dart2js/setlet_test.dart b/tests/compiler/dart2js/setlet_test.dart
index 8c9a9e5..f27cbcb 100644
--- a/tests/compiler/dart2js/setlet_test.dart
+++ b/tests/compiler/dart2js/setlet_test.dart
@@ -75,13 +75,20 @@
// For a variety of inputs and operations, test that Setlet behaves just like
// Set.
var samples = [
- [], [1], [1, 2], [2, 1], [1, 3], [3, 1], [1, 2, 3], [3, 1, 2],
- [1, 2, 3, 4, 5, 6, 7],
- [1, 2, 3, 4, 5, 6, 7, 8, 9],
- [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],
- [1, 2, 3, 4, 5, 6, 7, 8, 9],
- [6, 7, 8, 9, 10, 11],
- [7, 8, 6, 5],
+ [],
+ [1],
+ [1, 2],
+ [2, 1],
+ [1, 3],
+ [3, 1],
+ [1, 2, 3],
+ [3, 1, 2],
+ [1, 2, 3, 4, 5, 6, 7],
+ [1, 2, 3, 4, 5, 6, 7, 8, 9],
+ [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],
+ [1, 2, 3, 4, 5, 6, 7, 8, 9],
+ [6, 7, 8, 9, 10, 11],
+ [7, 8, 6, 5],
];
for (var a in samples) {
@@ -106,7 +113,6 @@
}
}
-
testSetXElement(name, fn, a, b) {
var set1 = new LinkedHashSet.from(a);
var setlet1 = new Setlet.from(a);
@@ -137,12 +143,11 @@
if (setResult == null || setResult is bool || setResult is num) {
Expect.equals(setResult, setletResult, '$operationName');
} else if (setResult is Iterable) {
- Expect.isTrue(setletResult is Iterable,
- '$operationName: returns Iterable');
+ Expect.isTrue(setletResult is Iterable, '$operationName: returns Iterable');
Expect.equals(setResult.isEmpty, setletResult.isEmpty,
'$operationName: same isEmpty');
- Expect.equals(setResult.length, setletResult.length,
- '$operationName: same length');
+ Expect.equals(
+ setResult.length, setletResult.length, '$operationName: same length');
Expect.listEquals(setResult.toList(), setletResult.toList(),
'$operationName: same toList() result');
} else {
diff --git a/tests/compiler/dart2js/sha1_test.dart b/tests/compiler/dart2js/sha1_test.dart
index d622eec..c2002c9 100644
--- a/tests/compiler/dart2js/sha1_test.dart
+++ b/tests/compiler/dart2js/sha1_test.dart
@@ -6,6 +6,7 @@
// into the compiler.
library sha1_test;
+
import 'package:compiler/src/hash/sha1.dart';
import "package:unittest/unittest.dart";
@@ -13,7 +14,6 @@
part 'sha1_long_test_vectors.dart';
part 'sha1_short_test_vectors.dart';
-
void main() {
test('expected values', _testExpectedValues);
test('invalid use', _testInvalidUse);
diff --git a/tests/compiler/dart2js/show_package_warnings_test.dart b/tests/compiler/dart2js/show_package_warnings_test.dart
index cc05018..f4e06b9 100644
--- a/tests/compiler/dart2js/show_package_warnings_test.dart
+++ b/tests/compiler/dart2js/show_package_warnings_test.dart
@@ -32,9 +32,7 @@
error.m(null);
}
""",
-
'error.dart': ERROR_CODE,
-
'pkg/pkg_error1/pkg_error1.dart': """
import 'package:pkg_error2/pkg_error2.dart' as pkg2;
import 'package:pkg_noerror/pkg_noerror.dart' as pkg3;
@@ -46,7 +44,6 @@
pkg3.m(null);
}
""",
-
'pkg/pkg_error2/pkg_error2.dart': """
import 'package:pkg_error1/pkg_error1.dart' as pkg1;
import 'package:pkg_noerror/pkg_noerror.dart' as pkg3;
@@ -58,7 +55,6 @@
pkg3.m(null);
}
""",
-
'pkg/pkg_noerror/pkg_noerror.dart': """
import 'package:pkg_error1/pkg_error1.dart' as pkg1;
import 'package:pkg_error2/pkg_error2.dart' as pkg2;
@@ -69,20 +65,21 @@
m(null);
pkg2.m(null);
}
-"""};
+"""
+};
Future test(Uri entryPoint,
- {List<String> showPackageWarnings: null,
- int warnings: 0,
- int hints: 0,
- int infos: 0}) async {
+ {List<String> showPackageWarnings: null,
+ int warnings: 0,
+ int hints: 0,
+ int infos: 0}) async {
var options = [Flags.analyzeOnly];
if (showPackageWarnings != null) {
if (showPackageWarnings.isEmpty) {
options.add(Flags.showPackageWarnings);
} else {
- options.add(
- '${Flags.showPackageWarnings}=${showPackageWarnings.join(',')}');
+ options
+ .add('${Flags.showPackageWarnings}=${showPackageWarnings.join(',')}');
}
}
var collector = new DiagnosticCollector();
@@ -95,16 +92,16 @@
options: options,
packageRoot: Uri.parse('memory:pkg/'),
diagnosticHandler: collector);
- Expect.equals(0, collector.errors.length,
- 'Unexpected errors: ${collector.errors}');
+ Expect.equals(
+ 0, collector.errors.length, 'Unexpected errors: ${collector.errors}');
Expect.equals(warnings, collector.warnings.length,
- 'Unexpected warnings: ${collector.warnings}');
+ 'Unexpected warnings: ${collector.warnings}');
checkUriSchemes(collector.warnings);
- Expect.equals(hints, collector.hints.length,
- 'Unexpected hints: ${collector.hints}');
+ Expect.equals(
+ hints, collector.hints.length, 'Unexpected hints: ${collector.hints}');
checkUriSchemes(collector.hints);
- Expect.equals(infos, collector.infos.length,
- 'Unexpected infos: ${collector.infos}');
+ Expect.equals(
+ infos, collector.infos.length, 'Unexpected infos: ${collector.infos}');
checkUriSchemes(collector.infos);
}
@@ -119,55 +116,61 @@
void main() {
asyncTest(() async {
- await test(
- Uri.parse('memory:main.dart'),
+ await test(Uri.parse('memory:main.dart'),
showPackageWarnings: [],
// From error.dart, package:pkg_error1 and package:pkg_error2:
- warnings: 3, hints: 3, infos: 3);
- await test(
- Uri.parse('memory:main.dart'),
+ warnings: 3,
+ hints: 3,
+ infos: 3);
+ await test(Uri.parse('memory:main.dart'),
showPackageWarnings: ['pkg_error1'],
// From error.dart and package:pkg_error1:
- warnings: 2, hints: 2 + 1 /* from summary */, infos: 2);
- await test(
- Uri.parse('memory:main.dart'),
+ warnings: 2,
+ hints: 2 + 1 /* from summary */,
+ infos: 2);
+ await test(Uri.parse('memory:main.dart'),
showPackageWarnings: ['pkg_error1', 'pkg_error2'],
// From error.dart, package:pkg_error1 and package:pkg_error2:
- warnings: 3, hints: 3, infos: 3);
- await test(
- Uri.parse('memory:main.dart'),
+ warnings: 3,
+ hints: 3,
+ infos: 3);
+ await test(Uri.parse('memory:main.dart'),
showPackageWarnings: [],
// From error.dart, package:pkg_error1 and package:pkg_error2:
- warnings: 3, hints: 3, infos: 3);
- await test(
- Uri.parse('memory:main.dart'),
+ warnings: 3,
+ hints: 3,
+ infos: 3);
+ await test(Uri.parse('memory:main.dart'),
showPackageWarnings: null,
// From error.dart only:
- warnings: 1, hints: 1 + 2 /* from summary */, infos: 1);
- await test(
- Uri.parse('package:pkg_error1/pkg_error1.dart'),
+ warnings: 1,
+ hints: 1 + 2 /* from summary */,
+ infos: 1);
+ await test(Uri.parse('package:pkg_error1/pkg_error1.dart'),
showPackageWarnings: [],
// From package:pkg_error1 and package:pkg_error2:
- warnings: 2, hints: 2, infos: 2);
- await test(
- Uri.parse('package:pkg_error1/pkg_error1.dart'),
+ warnings: 2,
+ hints: 2,
+ infos: 2);
+ await test(Uri.parse('package:pkg_error1/pkg_error1.dart'),
showPackageWarnings: null,
// From package:pkg_error1/pkg_error1.dart only:
- warnings: 1, hints: 1 + 1 /* from summary */, infos: 1);
- await test(
- Uri.parse('package:pkg_noerror/pkg_noerror.dart'),
+ warnings: 1,
+ hints: 1 + 1 /* from summary */,
+ infos: 1);
+ await test(Uri.parse('package:pkg_noerror/pkg_noerror.dart'),
showPackageWarnings: [],
// From package:pkg_error1 and package:pkg_error2:
- warnings: 2, hints: 2, infos: 2);
- await test(
- Uri.parse('package:pkg_noerror/pkg_noerror.dart'),
+ warnings: 2,
+ hints: 2,
+ infos: 2);
+ await test(Uri.parse('package:pkg_noerror/pkg_noerror.dart'),
showPackageWarnings: ['pkg_error1'],
// From package:pkg_error1:
- warnings: 1, hints: 1 + 1 /* from summary */, infos: 1);
- await test(
- Uri.parse('package:pkg_noerror/pkg_noerror.dart'),
- showPackageWarnings: null,
- hints: 2 /* from summary */);
+ warnings: 1,
+ hints: 1 + 1 /* from summary */,
+ infos: 1);
+ await test(Uri.parse('package:pkg_noerror/pkg_noerror.dart'),
+ showPackageWarnings: null, hints: 2 /* from summary */);
});
}
-
diff --git a/tests/compiler/dart2js/side_effect_tdiv_regression_test.dart b/tests/compiler/dart2js/side_effect_tdiv_regression_test.dart
index 59d30805..8db68c8 100644
--- a/tests/compiler/dart2js/side_effect_tdiv_regression_test.dart
+++ b/tests/compiler/dart2js/side_effect_tdiv_regression_test.dart
@@ -24,6 +24,6 @@
void main() {
asyncTest(() => compileAll(TEST).then((generated) {
- Expect.isTrue(generated.contains('return c + c;'));
- }));
+ Expect.isTrue(generated.contains('return c + c;'));
+ }));
}
diff --git a/tests/compiler/dart2js/simple_function_subtype_test.dart b/tests/compiler/dart2js/simple_function_subtype_test.dart
index 3997dea..a1b3a73 100644
--- a/tests/compiler/dart2js/simple_function_subtype_test.dart
+++ b/tests/compiler/dart2js/simple_function_subtype_test.dart
@@ -52,12 +52,12 @@
main() {
asyncTest(() => compile(TEST, entry: 'foo', check: (String generated) {
- for (int i = 0 ; i <= 15 ; i++) {
- String predicateCheck = '.\$is_args$i';
- Expect.isTrue(generated.contains(predicateCheck),
- 'Expected predicate check $predicateCheck');
- }
- Expect.isFalse(generated.contains('checkFunctionSubtype'),
- 'Unexpected use of checkFunctionSubtype');
- }));
-}
\ No newline at end of file
+ for (int i = 0; i <= 15; i++) {
+ String predicateCheck = '.\$is_args$i';
+ Expect.isTrue(generated.contains(predicateCheck),
+ 'Expected predicate check $predicateCheck');
+ }
+ Expect.isFalse(generated.contains('checkFunctionSubtype'),
+ 'Unexpected use of checkFunctionSubtype');
+ }));
+}
diff --git a/tests/compiler/dart2js/simple_inferrer_and_or_test.dart b/tests/compiler/dart2js/simple_inferrer_and_or_test.dart
index e5a11bc..ac2e682 100644
--- a/tests/compiler/dart2js/simple_inferrer_and_or_test.dart
+++ b/tests/compiler/dart2js/simple_inferrer_and_or_test.dart
@@ -92,32 +92,36 @@
}
""";
-
void main() {
Uri uri = new Uri(scheme: 'source');
var compiler = compilerFor(TEST, uri);
asyncTest(() => compiler.run(uri).then((_) {
- var typesInferrer = compiler.globalInference.typesInferrer;
+ var typesInferrer = compiler.globalInference.typesInferrer;
- checkReturn(String name, type) {
- var element = findElement(compiler, name);
- Expect.equals(type,
- simplify(typesInferrer.getReturnTypeOfElement(element), compiler));
- }
+ checkReturn(String name, type) {
+ var element = findElement(compiler, name);
+ Expect.equals(
+ type,
+ simplify(
+ typesInferrer.getReturnTypeOfElement(element), compiler));
+ }
- var subclassOfInterceptor =
- findTypeMask(compiler, 'Interceptor', 'nonNullSubclass');
+ var subclassOfInterceptor =
+ findTypeMask(compiler, 'Interceptor', 'nonNullSubclass');
- checkReturn('returnDyn1', subclassOfInterceptor);
- checkReturn('returnDyn2', subclassOfInterceptor);
- checkReturn('returnDyn3', subclassOfInterceptor);
- checkReturn('returnDyn4', compiler.commonMasks.dynamicType.nonNullable());
- checkReturn('returnDyn5', compiler.commonMasks.dynamicType.nonNullable());
- checkReturn('returnDyn6', compiler.commonMasks.dynamicType.nonNullable());
- checkReturn('returnDyn7', subclassOfInterceptor);
- checkReturn('returnDyn7b', subclassOfInterceptor);
- checkReturn('returnDyn8', subclassOfInterceptor);
- checkReturn('returnDyn9', subclassOfInterceptor);
- checkReturn('returnString', compiler.commonMasks.stringType);
- }));
+ checkReturn('returnDyn1', subclassOfInterceptor);
+ checkReturn('returnDyn2', subclassOfInterceptor);
+ checkReturn('returnDyn3', subclassOfInterceptor);
+ checkReturn(
+ 'returnDyn4', compiler.commonMasks.dynamicType.nonNullable());
+ checkReturn(
+ 'returnDyn5', compiler.commonMasks.dynamicType.nonNullable());
+ checkReturn(
+ 'returnDyn6', compiler.commonMasks.dynamicType.nonNullable());
+ checkReturn('returnDyn7', subclassOfInterceptor);
+ checkReturn('returnDyn7b', subclassOfInterceptor);
+ checkReturn('returnDyn8', subclassOfInterceptor);
+ checkReturn('returnDyn9', subclassOfInterceptor);
+ checkReturn('returnString', compiler.commonMasks.stringType);
+ }));
}
diff --git a/tests/compiler/dart2js/simple_inferrer_callers_test.dart b/tests/compiler/dart2js/simple_inferrer_callers_test.dart
index b4f4c2a..85b537e 100644
--- a/tests/compiler/dart2js/simple_inferrer_callers_test.dart
+++ b/tests/compiler/dart2js/simple_inferrer_callers_test.dart
@@ -39,13 +39,13 @@
var inferrer = new MyInferrer(compiler, compiler.commonMasks);
compiler.globalInference.typesInferrer = inferrer;
asyncTest(() => compiler.run(uri).then((_) {
- var mainElement = findElement(compiler, 'main');
- var classA = findElement(compiler, 'A');
- var fieldA = classA.lookupLocalMember('field');
- var classB = findElement(compiler, 'B');
- var fieldB = classB.lookupLocalMember('field');
+ var mainElement = findElement(compiler, 'main');
+ var classA = findElement(compiler, 'A');
+ var fieldA = classA.lookupLocalMember('field');
+ var classB = findElement(compiler, 'B');
+ var fieldB = classB.lookupLocalMember('field');
- Expect.isTrue(inferrer.getCallersOf(fieldA).contains(mainElement));
- Expect.isTrue(inferrer.getCallersOf(fieldB).contains(mainElement));
- }));
+ Expect.isTrue(inferrer.getCallersOf(fieldA).contains(mainElement));
+ Expect.isTrue(inferrer.getCallersOf(fieldB).contains(mainElement));
+ }));
}
diff --git a/tests/compiler/dart2js/simple_inferrer_closure_test.dart b/tests/compiler/dart2js/simple_inferrer_closure_test.dart
index e9fc517..1ca210e 100644
--- a/tests/compiler/dart2js/simple_inferrer_closure_test.dart
+++ b/tests/compiler/dart2js/simple_inferrer_closure_test.dart
@@ -114,39 +114,46 @@
}
""";
-
void main() {
Uri uri = new Uri(scheme: 'source');
var compiler = compilerFor(TEST, uri);
asyncTest(() => compiler.run(uri).then((_) {
- var typesInferrer = compiler.globalInference.typesInferrer;
+ var typesInferrer = compiler.globalInference.typesInferrer;
- checkReturn(String name, type) {
- var element = findElement(compiler, name);
- Expect.equals(type,
- simplify(typesInferrer.getReturnTypeOfElement(element), compiler),
- name);
- }
+ checkReturn(String name, type) {
+ var element = findElement(compiler, name);
+ Expect.equals(
+ type,
+ simplify(typesInferrer.getReturnTypeOfElement(element), compiler),
+ name);
+ }
- checkReturn('returnInt1', compiler.commonMasks.uint31Type);
- checkReturn('returnInt2', compiler.commonMasks.uint31Type);
- checkReturn('returnInt3', compiler.commonMasks.uint31Type);
- checkReturn('returnInt4', compiler.commonMasks.uint31Type);
- checkReturn('returnIntOrNull', compiler.commonMasks.uint31Type.nullable());
+ checkReturn('returnInt1', compiler.commonMasks.uint31Type);
+ checkReturn('returnInt2', compiler.commonMasks.uint31Type);
+ checkReturn('returnInt3', compiler.commonMasks.uint31Type);
+ checkReturn('returnInt4', compiler.commonMasks.uint31Type);
+ checkReturn(
+ 'returnIntOrNull', compiler.commonMasks.uint31Type.nullable());
- checkReturn('returnDyn1', compiler.commonMasks.dynamicType.nonNullable());
- checkReturn('returnDyn2', compiler.commonMasks.dynamicType.nonNullable());
- checkReturn('returnDyn3', compiler.commonMasks.dynamicType.nonNullable());
- checkReturn('returnNum1', compiler.commonMasks.numType);
+ checkReturn(
+ 'returnDyn1', compiler.commonMasks.dynamicType.nonNullable());
+ checkReturn(
+ 'returnDyn2', compiler.commonMasks.dynamicType.nonNullable());
+ checkReturn(
+ 'returnDyn3', compiler.commonMasks.dynamicType.nonNullable());
+ checkReturn('returnNum1', compiler.commonMasks.numType);
- checkReturnInClass(String className, String methodName, type) {
- var cls = findElement(compiler, className);
- var element = cls.lookupLocalMember(methodName);
- Expect.equals(type,
- simplify(typesInferrer.getReturnTypeOfElement(element), compiler));
- }
- var cls = findElement(compiler, 'A');
- checkReturnInClass('A', 'foo', new TypeMask.nonNullExact(cls,
- compiler.world));
- }));
+ checkReturnInClass(String className, String methodName, type) {
+ var cls = findElement(compiler, className);
+ var element = cls.lookupLocalMember(methodName);
+ Expect.equals(
+ type,
+ simplify(
+ typesInferrer.getReturnTypeOfElement(element), compiler));
+ }
+
+ var cls = findElement(compiler, 'A');
+ checkReturnInClass(
+ 'A', 'foo', new TypeMask.nonNullExact(cls, compiler.world));
+ }));
}
diff --git a/tests/compiler/dart2js/simple_inferrer_const_closure2_test.dart b/tests/compiler/dart2js/simple_inferrer_const_closure2_test.dart
index 4ea68a9..175d716 100644
--- a/tests/compiler/dart2js/simple_inferrer_const_closure2_test.dart
+++ b/tests/compiler/dart2js/simple_inferrer_const_closure2_test.dart
@@ -24,21 +24,21 @@
}
""";
-
void main() {
Uri uri = new Uri(scheme: 'source');
var compiler = compilerFor(TEST, uri);
asyncTest(() => compiler.run(uri).then((_) {
- var typesInferrer = compiler.globalInference.typesInferrer;
+ var typesInferrer = compiler.globalInference.typesInferrer;
- checkReturn(String name, type) {
- var element = findElement(compiler, name);
- Expect.equals(type,
- typesInferrer.getReturnTypeOfElement(element).simplify(compiler),
- name);
- }
+ checkReturn(String name, type) {
+ var element = findElement(compiler, name);
+ Expect.equals(
+ type,
+ typesInferrer.getReturnTypeOfElement(element).simplify(compiler),
+ name);
+ }
- checkReturn('method', compiler.commonMasks.numType);
- checkReturn('returnNum', compiler.commonMasks.numType);
- }));
+ checkReturn('method', compiler.commonMasks.numType);
+ checkReturn('returnNum', compiler.commonMasks.numType);
+ }));
}
diff --git a/tests/compiler/dart2js/simple_inferrer_const_closure3_test.dart b/tests/compiler/dart2js/simple_inferrer_const_closure3_test.dart
index f7f759e..1a60bc8 100644
--- a/tests/compiler/dart2js/simple_inferrer_const_closure3_test.dart
+++ b/tests/compiler/dart2js/simple_inferrer_const_closure3_test.dart
@@ -24,22 +24,22 @@
}
""";
-
void main() {
Uri uri = new Uri(scheme: 'source');
var compiler = compilerFor(TEST, uri);
asyncTest(() => compiler.run(uri).then((_) {
- var typesInferrer = compiler.globalInference.typesInferrer;
+ var typesInferrer = compiler.globalInference.typesInferrer;
- checkArgument(String functionName, type) {
- var functionElement = findElement(compiler, functionName);
- var signature = functionElement.functionSignature;
- var element = signature.requiredParameters.first;
- Expect.equals(type,
- simplify(typesInferrer.getTypeOfElement(element), compiler),
- functionName);
- }
+ checkArgument(String functionName, type) {
+ var functionElement = findElement(compiler, functionName);
+ var signature = functionElement.functionSignature;
+ var element = signature.requiredParameters.first;
+ Expect.equals(
+ type,
+ simplify(typesInferrer.getTypeOfElement(element), compiler),
+ functionName);
+ }
- checkArgument('method', compiler.commonMasks.uint31Type);
- }));
+ checkArgument('method', compiler.commonMasks.uint31Type);
+ }));
}
diff --git a/tests/compiler/dart2js/simple_inferrer_const_closure4_test.dart b/tests/compiler/dart2js/simple_inferrer_const_closure4_test.dart
index 8728cfb..40914d4 100644
--- a/tests/compiler/dart2js/simple_inferrer_const_closure4_test.dart
+++ b/tests/compiler/dart2js/simple_inferrer_const_closure4_test.dart
@@ -25,23 +25,23 @@
}
""";
-
void main() {
Uri uri = new Uri(scheme: 'source');
var compiler = compilerFor(TEST, uri);
asyncTest(() => compiler.run(uri).then((_) {
- var typesInferrer = compiler.globalInference.typesInferrer;
+ var typesInferrer = compiler.globalInference.typesInferrer;
- checkArgument(String functionName, type) {
- var functionElement = findElement(compiler, functionName);
- var signature = functionElement.functionSignature;
- var element = signature.requiredParameters.first;
- Expect.equals(type,
- simplify(typesInferrer.getTypeOfElement(element), compiler),
- functionName);
- }
+ checkArgument(String functionName, type) {
+ var functionElement = findElement(compiler, functionName);
+ var signature = functionElement.functionSignature;
+ var element = signature.requiredParameters.first;
+ Expect.equals(
+ type,
+ simplify(typesInferrer.getTypeOfElement(element), compiler),
+ functionName);
+ }
- checkArgument('method', compiler.commonMasks.numType);
- checkArgument('returnNum', compiler.commonMasks.numType);
- }));
+ checkArgument('method', compiler.commonMasks.numType);
+ checkArgument('returnNum', compiler.commonMasks.numType);
+ }));
}
diff --git a/tests/compiler/dart2js/simple_inferrer_const_closure5_test.dart b/tests/compiler/dart2js/simple_inferrer_const_closure5_test.dart
index 834ccd7..413a385 100644
--- a/tests/compiler/dart2js/simple_inferrer_const_closure5_test.dart
+++ b/tests/compiler/dart2js/simple_inferrer_const_closure5_test.dart
@@ -25,22 +25,22 @@
}
""";
-
void main() {
Uri uri = new Uri(scheme: 'source');
var compiler = compilerFor(TEST, uri);
asyncTest(() => compiler.run(uri).then((_) {
- var typesInferrer = compiler.globalInference.typesInferrer;
+ var typesInferrer = compiler.globalInference.typesInferrer;
- checkArgument(String functionName, type) {
- var functionElement = findElement(compiler, functionName);
- var signature = functionElement.functionSignature;
- var element = signature.requiredParameters.first;
- Expect.equals(type,
- simplify(typesInferrer.getTypeOfElement(element), compiler),
- functionName);
- }
+ checkArgument(String functionName, type) {
+ var functionElement = findElement(compiler, functionName);
+ var signature = functionElement.functionSignature;
+ var element = signature.requiredParameters.first;
+ Expect.equals(
+ type,
+ simplify(typesInferrer.getTypeOfElement(element), compiler),
+ functionName);
+ }
- checkArgument('method', compiler.commonMasks.numType);
- }));
+ checkArgument('method', compiler.commonMasks.numType);
+ }));
}
diff --git a/tests/compiler/dart2js/simple_inferrer_const_closure_test.dart b/tests/compiler/dart2js/simple_inferrer_const_closure_test.dart
index 411269f..bb5e17e 100644
--- a/tests/compiler/dart2js/simple_inferrer_const_closure_test.dart
+++ b/tests/compiler/dart2js/simple_inferrer_const_closure_test.dart
@@ -33,24 +33,24 @@
}
""";
-
void main() {
Uri uri = new Uri(scheme: 'source');
var compiler = compilerFor(TEST, uri);
asyncTest(() => compiler.run(uri).then((_) {
- var typesInferrer = compiler.globalInference.typesInferrer;
+ var typesInferrer = compiler.globalInference.typesInferrer;
- checkReturn(String name, type) {
- var element = findElement(compiler, name);
- Expect.equals(type,
- typesInferrer.getReturnTypeOfElement(element).simplify(compiler),
- name);
- }
+ checkReturn(String name, type) {
+ var element = findElement(compiler, name);
+ Expect.equals(
+ type,
+ typesInferrer.getReturnTypeOfElement(element).simplify(compiler),
+ name);
+ }
- checkReturn('method1', compiler.commonMasks.uint31Type);
- checkReturn('returnInt1', compiler.commonMasks.uint31Type);
+ checkReturn('method1', compiler.commonMasks.uint31Type);
+ checkReturn('returnInt1', compiler.commonMasks.uint31Type);
- checkReturn('method2', compiler.commonMasks.uint31Type);
- checkReturn('returnInt2', compiler.commonMasks.uint31Type);
- }));
+ checkReturn('method2', compiler.commonMasks.uint31Type);
+ checkReturn('returnInt2', compiler.commonMasks.uint31Type);
+ }));
}
diff --git a/tests/compiler/dart2js/simple_inferrer_final_field2_test.dart b/tests/compiler/dart2js/simple_inferrer_final_field2_test.dart
index 1045fb3..0bb2985 100644
--- a/tests/compiler/dart2js/simple_inferrer_final_field2_test.dart
+++ b/tests/compiler/dart2js/simple_inferrer_final_field2_test.dart
@@ -28,15 +28,18 @@
Uri uri = new Uri(scheme: 'source');
var compiler = compilerFor(TEST, uri);
asyncTest(() => compiler.run(uri).then((_) {
- var typesInferrer = compiler.globalInference.typesInferrer;
+ var typesInferrer = compiler.globalInference.typesInferrer;
- checkFieldTypeInClass(String className, String fieldName, type) {
- var cls = findElement(compiler, className);
- var element = cls.lookupLocalMember(fieldName);
- Expect.isTrue(typesInferrer.getTypeOfElement(element).containsOnly(type));
- }
+ checkFieldTypeInClass(String className, String fieldName, type) {
+ var cls = findElement(compiler, className);
+ var element = cls.lookupLocalMember(fieldName);
+ Expect.isTrue(
+ typesInferrer.getTypeOfElement(element).containsOnly(type));
+ }
- checkFieldTypeInClass('A', 'intField', compiler.backend.uint31Implementation);
- checkFieldTypeInClass('A', 'stringField', compiler.backend.stringImplementation);
- }));
+ checkFieldTypeInClass(
+ 'A', 'intField', compiler.backend.uint31Implementation);
+ checkFieldTypeInClass(
+ 'A', 'stringField', compiler.backend.stringImplementation);
+ }));
}
diff --git a/tests/compiler/dart2js/simple_inferrer_final_field3_test.dart b/tests/compiler/dart2js/simple_inferrer_final_field3_test.dart
index 0d25714..caa821f 100644
--- a/tests/compiler/dart2js/simple_inferrer_final_field3_test.dart
+++ b/tests/compiler/dart2js/simple_inferrer_final_field3_test.dart
@@ -27,16 +27,16 @@
Uri uri = new Uri(scheme: 'source');
var compiler = compilerFor(TEST, uri);
asyncTest(() => compiler.run(uri).then((_) {
- var typesInferrer = compiler.globalInference.typesInferrer;
+ var typesInferrer = compiler.globalInference.typesInferrer;
- checkFieldTypeInClass(String className, String fieldName, type) {
- var cls = findElement(compiler, className);
- var element = cls.lookupLocalMember(fieldName);
- Expect.equals(type,
- simplify(typesInferrer.getTypeOfElement(element), compiler));
- }
+ checkFieldTypeInClass(String className, String fieldName, type) {
+ var cls = findElement(compiler, className);
+ var element = cls.lookupLocalMember(fieldName);
+ Expect.equals(type,
+ simplify(typesInferrer.getTypeOfElement(element), compiler));
+ }
- checkFieldTypeInClass('A', 'dynamicField',
- findTypeMask(compiler, 'Interceptor', 'nonNullSubclass'));
- }));
+ checkFieldTypeInClass('A', 'dynamicField',
+ findTypeMask(compiler, 'Interceptor', 'nonNullSubclass'));
+ }));
}
diff --git a/tests/compiler/dart2js/simple_inferrer_final_field_test.dart b/tests/compiler/dart2js/simple_inferrer_final_field_test.dart
index a3a2516..d36ffa9 100644
--- a/tests/compiler/dart2js/simple_inferrer_final_field_test.dart
+++ b/tests/compiler/dart2js/simple_inferrer_final_field_test.dart
@@ -31,20 +31,21 @@
Uri uri = new Uri(scheme: 'source');
var compiler = compilerFor(TEST, uri);
asyncTest(() => compiler.run(uri).then((_) {
- var typesInferrer = compiler.globalInference.typesInferrer;
+ var typesInferrer = compiler.globalInference.typesInferrer;
- checkFieldTypeInClass(String className, String fieldName, type) {
- var cls = findElement(compiler, className);
- var element = cls.lookupLocalMember(fieldName);
- Expect.equals(type,
- simplify(typesInferrer.getTypeOfElement(element), compiler));
- }
+ checkFieldTypeInClass(String className, String fieldName, type) {
+ var cls = findElement(compiler, className);
+ var element = cls.lookupLocalMember(fieldName);
+ Expect.equals(type,
+ simplify(typesInferrer.getTypeOfElement(element), compiler));
+ }
- checkFieldTypeInClass('A', 'intField', compiler.commonMasks.uint31Type);
- checkFieldTypeInClass('A', 'giveUpField1',
- findTypeMask(compiler, 'Interceptor', 'nonNullSubclass'));
- checkFieldTypeInClass('A', 'giveUpField2',
- compiler.commonMasks.dynamicType.nonNullable());
- checkFieldTypeInClass('A', 'fieldParameter', compiler.commonMasks.uint31Type);
- }));
+ checkFieldTypeInClass('A', 'intField', compiler.commonMasks.uint31Type);
+ checkFieldTypeInClass('A', 'giveUpField1',
+ findTypeMask(compiler, 'Interceptor', 'nonNullSubclass'));
+ checkFieldTypeInClass('A', 'giveUpField2',
+ compiler.commonMasks.dynamicType.nonNullable());
+ checkFieldTypeInClass(
+ 'A', 'fieldParameter', compiler.commonMasks.uint31Type);
+ }));
}
diff --git a/tests/compiler/dart2js/simple_inferrer_global_field_closure2_test.dart b/tests/compiler/dart2js/simple_inferrer_global_field_closure2_test.dart
index cd5715d..c2e7492 100644
--- a/tests/compiler/dart2js/simple_inferrer_global_field_closure2_test.dart
+++ b/tests/compiler/dart2js/simple_inferrer_global_field_closure2_test.dart
@@ -24,22 +24,22 @@
}
""";
-
void main() {
Uri uri = new Uri(scheme: 'source');
var compiler = compilerFor(TEST, uri);
asyncTest(() => compiler.run(uri).then((_) {
- var typesInferrer = compiler.globalInference.typesInferrer;
+ var typesInferrer = compiler.globalInference.typesInferrer;
- checkArgument(String functionName, type) {
- var functionElement = findElement(compiler, functionName);
- var signature = functionElement.functionSignature;
- var element = signature.requiredParameters.first;
- Expect.equals(type,
- simplify(typesInferrer.getTypeOfElement(element), compiler),
- functionName);
- }
+ checkArgument(String functionName, type) {
+ var functionElement = findElement(compiler, functionName);
+ var signature = functionElement.functionSignature;
+ var element = signature.requiredParameters.first;
+ Expect.equals(
+ type,
+ simplify(typesInferrer.getTypeOfElement(element), compiler),
+ functionName);
+ }
- checkArgument('method', compiler.commonMasks.uint31Type);
- }));
+ checkArgument('method', compiler.commonMasks.uint31Type);
+ }));
}
diff --git a/tests/compiler/dart2js/simple_inferrer_global_field_closure_test.dart b/tests/compiler/dart2js/simple_inferrer_global_field_closure_test.dart
index 06bb0c4..eb486bc 100644
--- a/tests/compiler/dart2js/simple_inferrer_global_field_closure_test.dart
+++ b/tests/compiler/dart2js/simple_inferrer_global_field_closure_test.dart
@@ -33,24 +33,24 @@
}
""";
-
void main() {
Uri uri = new Uri(scheme: 'source');
var compiler = compilerFor(TEST, uri);
asyncTest(() => compiler.run(uri).then((_) {
- var typesInferrer = compiler.globalInference.typesInferrer;
+ var typesInferrer = compiler.globalInference.typesInferrer;
- checkReturn(String name, type) {
- var element = findElement(compiler, name);
- Expect.equals(type,
- typesInferrer.getReturnTypeOfElement(element).simplify(compiler),
- name);
- }
+ checkReturn(String name, type) {
+ var element = findElement(compiler, name);
+ Expect.equals(
+ type,
+ typesInferrer.getReturnTypeOfElement(element).simplify(compiler),
+ name);
+ }
- checkReturn('method1', compiler.commonMasks.uint31Type);
- checkReturn('returnInt1', compiler.commonMasks.uint31Type);
+ checkReturn('method1', compiler.commonMasks.uint31Type);
+ checkReturn('returnInt1', compiler.commonMasks.uint31Type);
- checkReturn('method2', compiler.commonMasks.uint31Type);
- checkReturn('returnInt2', compiler.commonMasks.uint31Type);
- }));
+ checkReturn('method2', compiler.commonMasks.uint31Type);
+ checkReturn('returnInt2', compiler.commonMasks.uint31Type);
+ }));
}
diff --git a/tests/compiler/dart2js/simple_inferrer_no_such_method_test.dart b/tests/compiler/dart2js/simple_inferrer_no_such_method_test.dart
index 0e6a7a3..96ede85 100644
--- a/tests/compiler/dart2js/simple_inferrer_no_such_method_test.dart
+++ b/tests/compiler/dart2js/simple_inferrer_no_such_method_test.dart
@@ -174,51 +174,51 @@
var compiler1 = compilerFor(TEST1, uri);
asyncTest(() => compiler1.run(uri).then((_) {
- checkReturn(compiler1, 'test1', compiler1.commonMasks.uint31Type);
- checkReturn(compiler1, 'test2',
- compiler1.commonMasks.dynamicType.nonNullable());
- checkReturn(compiler1, 'test3', compiler1.commonMasks.uint31Type);
- checkReturn(compiler1, 'test4', compiler1.commonMasks.mapType);
- checkReturn(compiler1, 'test5',
- compiler1.commonMasks.dynamicType.nonNullable());
- checkReturn(compiler1, 'test6',
- compiler1.commonMasks.dynamicType.nonNullable());
- }));
+ checkReturn(compiler1, 'test1', compiler1.commonMasks.uint31Type);
+ checkReturn(compiler1, 'test2',
+ compiler1.commonMasks.dynamicType.nonNullable());
+ checkReturn(compiler1, 'test3', compiler1.commonMasks.uint31Type);
+ checkReturn(compiler1, 'test4', compiler1.commonMasks.mapType);
+ checkReturn(compiler1, 'test5',
+ compiler1.commonMasks.dynamicType.nonNullable());
+ checkReturn(compiler1, 'test6',
+ compiler1.commonMasks.dynamicType.nonNullable());
+ }));
var compiler2 = compilerFor(TEST2, uri);
asyncTest(() => compiler2.run(uri).then((_) {
- checkReturn(compiler2, 'test1',
- compiler2.commonMasks.mapType.nonNullable());
- checkReturn(compiler2, 'test2', compiler2.commonMasks.mapType);
- checkReturn(compiler2, 'test3', compiler2.commonMasks.mapType);
- checkReturn(compiler2, 'test4', compiler2.commonMasks.mapType);
- checkReturn(compiler2, 'test5', compiler2.commonMasks.mapType);
+ checkReturn(
+ compiler2, 'test1', compiler2.commonMasks.mapType.nonNullable());
+ checkReturn(compiler2, 'test2', compiler2.commonMasks.mapType);
+ checkReturn(compiler2, 'test3', compiler2.commonMasks.mapType);
+ checkReturn(compiler2, 'test4', compiler2.commonMasks.mapType);
+ checkReturn(compiler2, 'test5', compiler2.commonMasks.mapType);
- checkReturn(compiler2, 'test6', compiler2.commonMasks.numType);
- checkReturn(compiler2, 'test7', compiler2.commonMasks.uint31Type);
- checkReturn(compiler2, 'test8', compiler2.commonMasks.uint31Type);
- checkReturn(compiler2, 'test9', compiler2.commonMasks.uint31Type);
- checkReturn(compiler2, 'test10', compiler2.commonMasks.numType);
- checkReturn(compiler2, 'test11', compiler2.commonMasks.doubleType);
- }));
+ checkReturn(compiler2, 'test6', compiler2.commonMasks.numType);
+ checkReturn(compiler2, 'test7', compiler2.commonMasks.uint31Type);
+ checkReturn(compiler2, 'test8', compiler2.commonMasks.uint31Type);
+ checkReturn(compiler2, 'test9', compiler2.commonMasks.uint31Type);
+ checkReturn(compiler2, 'test10', compiler2.commonMasks.numType);
+ checkReturn(compiler2, 'test11', compiler2.commonMasks.doubleType);
+ }));
var compiler3 = compilerFor(TEST3, uri);
asyncTest(() => compiler3.run(uri).then((_) {
- checkReturn(compiler3, 'test1', const TypeMask.nonNullEmpty());
- checkReturn(compiler3, 'test2', compiler3.commonMasks.mapType);
- checkReturn(compiler3, 'test3', compiler3.commonMasks.mapType);
- checkReturn(compiler3, 'test4', compiler3.commonMasks.mapType);
- checkReturn(compiler3, 'test5', compiler3.commonMasks.mapType);
- checkReturn(compiler3, 'test6', compiler3.commonMasks.mapType);
- }));
+ checkReturn(compiler3, 'test1', const TypeMask.nonNullEmpty());
+ checkReturn(compiler3, 'test2', compiler3.commonMasks.mapType);
+ checkReturn(compiler3, 'test3', compiler3.commonMasks.mapType);
+ checkReturn(compiler3, 'test4', compiler3.commonMasks.mapType);
+ checkReturn(compiler3, 'test5', compiler3.commonMasks.mapType);
+ checkReturn(compiler3, 'test6', compiler3.commonMasks.mapType);
+ }));
var compiler4 = compilerFor(TEST4, uri);
asyncTest(() => compiler4.run(uri).then((_) {
- checkReturn(compiler4, 'test1', const TypeMask.nonNullEmpty());
- checkReturn(compiler4, 'test2', compiler4.commonMasks.mapType);
- checkReturn(compiler4, 'test3', compiler4.commonMasks.mapType);
- checkReturn(compiler4, 'test4', compiler4.commonMasks.mapType);
- checkReturn(compiler4, 'test5', compiler4.commonMasks.mapType);
- checkReturn(compiler4, 'test6', compiler4.commonMasks.mapType);
- }));
+ checkReturn(compiler4, 'test1', const TypeMask.nonNullEmpty());
+ checkReturn(compiler4, 'test2', compiler4.commonMasks.mapType);
+ checkReturn(compiler4, 'test3', compiler4.commonMasks.mapType);
+ checkReturn(compiler4, 'test4', compiler4.commonMasks.mapType);
+ checkReturn(compiler4, 'test5', compiler4.commonMasks.mapType);
+ checkReturn(compiler4, 'test6', compiler4.commonMasks.mapType);
+ }));
}
diff --git a/tests/compiler/dart2js/simple_inferrer_postfix_prefix_test.dart b/tests/compiler/dart2js/simple_inferrer_postfix_prefix_test.dart
index 2a94b4b..3b308f0 100644
--- a/tests/compiler/dart2js/simple_inferrer_postfix_prefix_test.dart
+++ b/tests/compiler/dart2js/simple_inferrer_postfix_prefix_test.dart
@@ -66,35 +66,40 @@
Uri uri = new Uri(scheme: 'source');
var compiler = compilerFor(TEST, uri);
asyncTest(() => compiler.run(uri).then((_) {
- var commonMasks = compiler.commonMasks;
- var typesInferrer = compiler.globalInference.typesInferrer;
+ var commonMasks = compiler.commonMasks;
+ var typesInferrer = compiler.globalInference.typesInferrer;
- checkReturnInClass(String className, String methodName, type) {
- var cls = findElement(compiler, className);
- var element = cls.lookupLocalMember(methodName);
- Expect.equals(type,
- simplify(typesInferrer.getReturnTypeOfElement(element), compiler),
- methodName);
- }
+ checkReturnInClass(String className, String methodName, type) {
+ var cls = findElement(compiler, className);
+ var element = cls.lookupLocalMember(methodName);
+ Expect.equals(
+ type,
+ simplify(typesInferrer.getReturnTypeOfElement(element), compiler),
+ methodName);
+ }
- var subclassOfInterceptor =
- findTypeMask(compiler, 'Interceptor', 'nonNullSubclass');
+ var subclassOfInterceptor =
+ findTypeMask(compiler, 'Interceptor', 'nonNullSubclass');
- checkReturnInClass('A', 'returnNum1', commonMasks.numType);
- checkReturnInClass('A', 'returnNum2', commonMasks.numType);
- checkReturnInClass('A', 'returnNum3', commonMasks.numType);
- checkReturnInClass('A', 'returnNum4', commonMasks.numType);
- checkReturnInClass('A', 'returnEmpty1', const TypeMask.nonNullEmpty());
- checkReturnInClass('A', 'returnEmpty2', const TypeMask.nonNullEmpty());
- checkReturnInClass('A', 'returnDynamic1', subclassOfInterceptor);
- checkReturnInClass('A', 'returnDynamic2', subclassOfInterceptor);
- checkReturnInClass('A', 'returnEmpty3', const TypeMask.nonNullEmpty());
+ checkReturnInClass('A', 'returnNum1', commonMasks.numType);
+ checkReturnInClass('A', 'returnNum2', commonMasks.numType);
+ checkReturnInClass('A', 'returnNum3', commonMasks.numType);
+ checkReturnInClass('A', 'returnNum4', commonMasks.numType);
+ checkReturnInClass('A', 'returnEmpty1', const TypeMask.nonNullEmpty());
+ checkReturnInClass('A', 'returnEmpty2', const TypeMask.nonNullEmpty());
+ checkReturnInClass('A', 'returnDynamic1', subclassOfInterceptor);
+ checkReturnInClass('A', 'returnDynamic2', subclassOfInterceptor);
+ checkReturnInClass('A', 'returnEmpty3', const TypeMask.nonNullEmpty());
- checkReturnInClass('B', 'returnString1', commonMasks.stringType);
- checkReturnInClass('B', 'returnString2', commonMasks.stringType);
- checkReturnInClass('B', 'returnDynamic1', const TypeMask.nonNullEmpty());
- checkReturnInClass('B', 'returnDynamic2', const TypeMask.nonNullEmpty());
- checkReturnInClass('B', 'returnDynamic3', const TypeMask.nonNullEmpty());
- checkReturnInClass('B', 'returnDynamic4', const TypeMask.nonNullEmpty());
- }));
+ checkReturnInClass('B', 'returnString1', commonMasks.stringType);
+ checkReturnInClass('B', 'returnString2', commonMasks.stringType);
+ checkReturnInClass(
+ 'B', 'returnDynamic1', const TypeMask.nonNullEmpty());
+ checkReturnInClass(
+ 'B', 'returnDynamic2', const TypeMask.nonNullEmpty());
+ checkReturnInClass(
+ 'B', 'returnDynamic3', const TypeMask.nonNullEmpty());
+ checkReturnInClass(
+ 'B', 'returnDynamic4', const TypeMask.nonNullEmpty());
+ }));
}
diff --git a/tests/compiler/dart2js/simple_inferrer_relations_test.dart b/tests/compiler/dart2js/simple_inferrer_relations_test.dart
index a076955..db2e48d 100644
--- a/tests/compiler/dart2js/simple_inferrer_relations_test.dart
+++ b/tests/compiler/dart2js/simple_inferrer_relations_test.dart
@@ -49,9 +49,9 @@
void main() {
asyncTest(() => compileAll(TEST).then((generated) {
- if (generated.contains(r'=== true')) {
- print(generated);
- Expect.fail("missing elision of '=== true'");
- }
- }));
+ if (generated.contains(r'=== true')) {
+ print(generated);
+ Expect.fail("missing elision of '=== true'");
+ }
+ }));
}
diff --git a/tests/compiler/dart2js/simple_inferrer_test.dart b/tests/compiler/dart2js/simple_inferrer_test.dart
index 295784a..70270da 100644
--- a/tests/compiler/dart2js/simple_inferrer_test.dart
+++ b/tests/compiler/dart2js/simple_inferrer_test.dart
@@ -727,152 +727,163 @@
var compiler = compilerFor(TEST, uri);
compiler.diagnosticHandler = createHandler(compiler, TEST);
asyncTest(() => compiler.run(uri).then((_) {
- var commonMasks = compiler.commonMasks;
- var typesInferrer = compiler.globalInference.typesInferrer;
- var world = compiler.world;
+ var commonMasks = compiler.commonMasks;
+ var typesInferrer = compiler.globalInference.typesInferrer;
+ var world = compiler.world;
- checkReturn(String name, type) {
- var element = findElement(compiler, name);
- Expect.equals(
- type,
- simplify(typesInferrer.getReturnTypeOfElement(element), compiler),
- name);
- }
- var interceptorType =
- findTypeMask(compiler, 'Interceptor', 'nonNullSubclass');
+ checkReturn(String name, type) {
+ var element = findElement(compiler, name);
+ Expect.equals(
+ type,
+ simplify(typesInferrer.getReturnTypeOfElement(element), compiler),
+ name);
+ }
- checkReturn('returnNum1', commonMasks.numType);
- checkReturn('returnNum2', commonMasks.numType);
- checkReturn('returnInt1', commonMasks.uint31Type);
- checkReturn('returnInt2', commonMasks.uint31Type);
- checkReturn('returnDouble', commonMasks.doubleType);
- checkReturn('returnGiveUp', interceptorType);
- checkReturn('returnInt5', commonMasks.uint32Type); // uint31+uint31->uint32
- checkReturn('returnInt6', commonMasks.uint32Type); // uint31+uint31->uint32
- checkReturn('returnIntOrNull', commonMasks.uint31Type.nullable());
- checkReturn('returnInt3', commonMasks.uint31Type);
- checkReturn('returnDynamic', commonMasks.dynamicType);
- checkReturn('returnInt4', commonMasks.uint31Type);
- checkReturn('returnInt7', commonMasks.positiveIntType);
- checkReturn('returnInt8', commonMasks.positiveIntType);
- checkReturn('returnEmpty1', const TypeMask.nonNullEmpty());
- checkReturn('returnEmpty2', const TypeMask.nonNullEmpty());
- TypeMask intType = new TypeMask.nonNullSubtype(
- compiler.coreClasses.intClass, compiler.world);
- checkReturn('testIsCheck1', intType);
- checkReturn('testIsCheck2', intType);
- checkReturn('testIsCheck3', intType.nullable());
- checkReturn('testIsCheck4', intType);
- checkReturn('testIsCheck5', intType);
- checkReturn('testIsCheck6', commonMasks.dynamicType);
- checkReturn('testIsCheck7', intType);
- checkReturn('testIsCheck8', commonMasks.dynamicType);
- checkReturn('testIsCheck9', intType);
- checkReturn('testIsCheck10', commonMasks.dynamicType);
- checkReturn('testIsCheck11', intType);
- checkReturn('testIsCheck12', commonMasks.dynamicType);
- checkReturn('testIsCheck13', intType);
- checkReturn('testIsCheck14', commonMasks.dynamicType);
- checkReturn('testIsCheck15', intType);
- checkReturn('testIsCheck16', commonMasks.dynamicType);
- checkReturn('testIsCheck17', intType);
- checkReturn('testIsCheck18', commonMasks.dynamicType);
- checkReturn('testIsCheck19', commonMasks.dynamicType);
- checkReturn('testIsCheck20', interceptorType);
- checkReturn('testIsCheck21', commonMasks.dynamicType);
- checkReturn('testIsCheck22', commonMasks.dynamicType);
- checkReturn('testIsCheck23', intType);
- checkReturn('testIsCheck24', intType);
- checkReturn('testIsCheck25', commonMasks.dynamicType);
- checkReturn('testIsCheck26', intType);
- checkReturn('testIsCheck27', intType);
- checkReturn('testIsCheck28', commonMasks.dynamicType);
- checkReturn('testIsCheck29', commonMasks.dynamicType);
- checkReturn('testIf1', commonMasks.uint31Type.nullable());
- checkReturn('testIf2', commonMasks.uint31Type.nullable());
- checkReturn('returnAsString', new TypeMask.subtype(
- compiler.coreClasses.stringClass, compiler.world));
- checkReturn('returnIntAsNum', commonMasks.uint31Type);
- checkReturn('returnAsTypedef', commonMasks.functionType.nullable());
- checkReturn('returnTopLevelGetter', commonMasks.uint31Type);
- checkReturn('testDeadCode', commonMasks.uint31Type);
- checkReturn('testLabeledIf', commonMasks.uint31Type.nullable());
- checkReturn('testSwitch1', simplify(
- commonMasks.intType
- .union(commonMasks.doubleType, compiler.world)
- .nullable(),
- compiler));
- checkReturn('testSwitch2', commonMasks.uint31Type);
- checkReturn('testSwitch3', interceptorType.nullable());
- checkReturn('testSwitch4', commonMasks.uint31Type);
- checkReturn('testSwitch5', commonMasks.uint31Type);
- checkReturn('testContinue1', interceptorType.nullable());
- checkReturn('testBreak1', interceptorType.nullable());
- checkReturn('testContinue2', interceptorType.nullable());
- checkReturn('testBreak2', commonMasks.uint32Type.nullable());
- checkReturn('testReturnElementOfConstList1', commonMasks.uint31Type);
- checkReturn('testReturnElementOfConstList2', commonMasks.uint31Type);
- checkReturn('testReturnItselfOrInt', commonMasks.uint31Type);
- checkReturn('testReturnInvokeDynamicGetter', commonMasks.dynamicType);
+ var interceptorType =
+ findTypeMask(compiler, 'Interceptor', 'nonNullSubclass');
- checkReturn('testDoWhile1', commonMasks.stringType);
- checkReturn('testDoWhile2', commonMasks.nullType);
- checkReturn('testDoWhile3', commonMasks.uint31Type);
- checkReturn('testDoWhile4', commonMasks.numType);
+ checkReturn('returnNum1', commonMasks.numType);
+ checkReturn('returnNum2', commonMasks.numType);
+ checkReturn('returnInt1', commonMasks.uint31Type);
+ checkReturn('returnInt2', commonMasks.uint31Type);
+ checkReturn('returnDouble', commonMasks.doubleType);
+ checkReturn('returnGiveUp', interceptorType);
+ checkReturn(
+ 'returnInt5', commonMasks.uint32Type); // uint31+uint31->uint32
+ checkReturn(
+ 'returnInt6', commonMasks.uint32Type); // uint31+uint31->uint32
+ checkReturn('returnIntOrNull', commonMasks.uint31Type.nullable());
+ checkReturn('returnInt3', commonMasks.uint31Type);
+ checkReturn('returnDynamic', commonMasks.dynamicType);
+ checkReturn('returnInt4', commonMasks.uint31Type);
+ checkReturn('returnInt7', commonMasks.positiveIntType);
+ checkReturn('returnInt8', commonMasks.positiveIntType);
+ checkReturn('returnEmpty1', const TypeMask.nonNullEmpty());
+ checkReturn('returnEmpty2', const TypeMask.nonNullEmpty());
+ TypeMask intType = new TypeMask.nonNullSubtype(
+ compiler.coreClasses.intClass, compiler.world);
+ checkReturn('testIsCheck1', intType);
+ checkReturn('testIsCheck2', intType);
+ checkReturn('testIsCheck3', intType.nullable());
+ checkReturn('testIsCheck4', intType);
+ checkReturn('testIsCheck5', intType);
+ checkReturn('testIsCheck6', commonMasks.dynamicType);
+ checkReturn('testIsCheck7', intType);
+ checkReturn('testIsCheck8', commonMasks.dynamicType);
+ checkReturn('testIsCheck9', intType);
+ checkReturn('testIsCheck10', commonMasks.dynamicType);
+ checkReturn('testIsCheck11', intType);
+ checkReturn('testIsCheck12', commonMasks.dynamicType);
+ checkReturn('testIsCheck13', intType);
+ checkReturn('testIsCheck14', commonMasks.dynamicType);
+ checkReturn('testIsCheck15', intType);
+ checkReturn('testIsCheck16', commonMasks.dynamicType);
+ checkReturn('testIsCheck17', intType);
+ checkReturn('testIsCheck18', commonMasks.dynamicType);
+ checkReturn('testIsCheck19', commonMasks.dynamicType);
+ checkReturn('testIsCheck20', interceptorType);
+ checkReturn('testIsCheck21', commonMasks.dynamicType);
+ checkReturn('testIsCheck22', commonMasks.dynamicType);
+ checkReturn('testIsCheck23', intType);
+ checkReturn('testIsCheck24', intType);
+ checkReturn('testIsCheck25', commonMasks.dynamicType);
+ checkReturn('testIsCheck26', intType);
+ checkReturn('testIsCheck27', intType);
+ checkReturn('testIsCheck28', commonMasks.dynamicType);
+ checkReturn('testIsCheck29', commonMasks.dynamicType);
+ checkReturn('testIf1', commonMasks.uint31Type.nullable());
+ checkReturn('testIf2', commonMasks.uint31Type.nullable());
+ checkReturn(
+ 'returnAsString',
+ new TypeMask.subtype(
+ compiler.coreClasses.stringClass, compiler.world));
+ checkReturn('returnIntAsNum', commonMasks.uint31Type);
+ checkReturn('returnAsTypedef', commonMasks.functionType.nullable());
+ checkReturn('returnTopLevelGetter', commonMasks.uint31Type);
+ checkReturn('testDeadCode', commonMasks.uint31Type);
+ checkReturn('testLabeledIf', commonMasks.uint31Type.nullable());
+ checkReturn(
+ 'testSwitch1',
+ simplify(
+ commonMasks.intType
+ .union(commonMasks.doubleType, compiler.world)
+ .nullable(),
+ compiler));
+ checkReturn('testSwitch2', commonMasks.uint31Type);
+ checkReturn('testSwitch3', interceptorType.nullable());
+ checkReturn('testSwitch4', commonMasks.uint31Type);
+ checkReturn('testSwitch5', commonMasks.uint31Type);
+ checkReturn('testContinue1', interceptorType.nullable());
+ checkReturn('testBreak1', interceptorType.nullable());
+ checkReturn('testContinue2', interceptorType.nullable());
+ checkReturn('testBreak2', commonMasks.uint32Type.nullable());
+ checkReturn('testReturnElementOfConstList1', commonMasks.uint31Type);
+ checkReturn('testReturnElementOfConstList2', commonMasks.uint31Type);
+ checkReturn('testReturnItselfOrInt', commonMasks.uint31Type);
+ checkReturn('testReturnInvokeDynamicGetter', commonMasks.dynamicType);
- checkReturnInClass(String className, String methodName, type) {
- var cls = findElement(compiler, className);
- var element = cls.lookupLocalMember(methodName);
- Expect.equals(type,
- simplify(typesInferrer.getReturnTypeOfElement(element), compiler),
- '$className:$methodName');
- }
+ checkReturn('testDoWhile1', commonMasks.stringType);
+ checkReturn('testDoWhile2', commonMasks.nullType);
+ checkReturn('testDoWhile3', commonMasks.uint31Type);
+ checkReturn('testDoWhile4', commonMasks.numType);
- checkReturnInClass('A', 'returnInt1', commonMasks.uint32Type);
- checkReturnInClass('A', 'returnInt2', commonMasks.uint32Type);
- checkReturnInClass('A', 'returnInt3', commonMasks.uint32Type);
- checkReturnInClass('A', 'returnInt4', commonMasks.uint32Type);
- checkReturnInClass('A', 'returnInt5', commonMasks.uint32Type);
- checkReturnInClass('A', 'returnInt6', commonMasks.uint32Type);
- checkReturnInClass('A', '==', interceptorType);
+ checkReturnInClass(String className, String methodName, type) {
+ var cls = findElement(compiler, className);
+ var element = cls.lookupLocalMember(methodName);
+ Expect.equals(
+ type,
+ simplify(typesInferrer.getReturnTypeOfElement(element), compiler),
+ '$className:$methodName');
+ }
- checkReturnInClass('B', 'returnInt1', commonMasks.uint32Type);
- checkReturnInClass('B', 'returnInt2', commonMasks.uint32Type);
- checkReturnInClass('B', 'returnInt3', commonMasks.uint32Type);
- checkReturnInClass('B', 'returnInt4', commonMasks.uint32Type);
- checkReturnInClass('B', 'returnInt5', commonMasks.uint32Type);
- checkReturnInClass('B', 'returnInt6', commonMasks.uint32Type);
- checkReturnInClass('B', 'returnInt7', commonMasks.uint32Type);
- checkReturnInClass('B', 'returnInt8', commonMasks.uint32Type);
- checkReturnInClass('B', 'returnInt9', commonMasks.uint31Type);
+ checkReturnInClass('A', 'returnInt1', commonMasks.uint32Type);
+ checkReturnInClass('A', 'returnInt2', commonMasks.uint32Type);
+ checkReturnInClass('A', 'returnInt3', commonMasks.uint32Type);
+ checkReturnInClass('A', 'returnInt4', commonMasks.uint32Type);
+ checkReturnInClass('A', 'returnInt5', commonMasks.uint32Type);
+ checkReturnInClass('A', 'returnInt6', commonMasks.uint32Type);
+ checkReturnInClass('A', '==', interceptorType);
- checkReturnInClass('C', 'returnInt1', commonMasks.positiveIntType);
- checkReturnInClass('C', 'returnInt2', commonMasks.positiveIntType);
- checkReturnInClass('C', 'returnInt3', commonMasks.positiveIntType);
- checkReturnInClass('C', 'returnInt4', commonMasks.positiveIntType);
- checkReturnInClass('C', 'returnInt5', commonMasks.positiveIntType);
- checkReturnInClass('C', 'returnInt6', commonMasks.positiveIntType);
+ checkReturnInClass('B', 'returnInt1', commonMasks.uint32Type);
+ checkReturnInClass('B', 'returnInt2', commonMasks.uint32Type);
+ checkReturnInClass('B', 'returnInt3', commonMasks.uint32Type);
+ checkReturnInClass('B', 'returnInt4', commonMasks.uint32Type);
+ checkReturnInClass('B', 'returnInt5', commonMasks.uint32Type);
+ checkReturnInClass('B', 'returnInt6', commonMasks.uint32Type);
+ checkReturnInClass('B', 'returnInt7', commonMasks.uint32Type);
+ checkReturnInClass('B', 'returnInt8', commonMasks.uint32Type);
+ checkReturnInClass('B', 'returnInt9', commonMasks.uint31Type);
- checkFactoryConstructor(String className, String factoryName) {
- var cls = findElement(compiler, className);
- var element = cls.localLookup(factoryName);
- Expect.equals(new TypeMask.nonNullExact(cls, world),
- typesInferrer.getReturnTypeOfElement(element));
- }
- checkFactoryConstructor('A', '');
+ checkReturnInClass('C', 'returnInt1', commonMasks.positiveIntType);
+ checkReturnInClass('C', 'returnInt2', commonMasks.positiveIntType);
+ checkReturnInClass('C', 'returnInt3', commonMasks.positiveIntType);
+ checkReturnInClass('C', 'returnInt4', commonMasks.positiveIntType);
+ checkReturnInClass('C', 'returnInt5', commonMasks.positiveIntType);
+ checkReturnInClass('C', 'returnInt6', commonMasks.positiveIntType);
- checkReturn('testCascade1', commonMasks.growableListType);
- checkReturn('testCascade2', new TypeMask.nonNullExact(
- findElement(compiler, 'CascadeHelper'), world));
- checkReturn('testSpecialization1', commonMasks.numType);
- checkReturn('testSpecialization2', commonMasks.dynamicType);
- checkReturn('testSpecialization3', commonMasks.uint31Type.nullable());
- checkReturn('testReturnNull1', commonMasks.nullType);
- checkReturn('testReturnNull2', commonMasks.nullType);
- checkReturn('testReturnNull3', commonMasks.dynamicType);
- checkReturn('testReturnNull4', commonMasks.nullType);
- checkReturn('testReturnNull5', commonMasks.nullType);
- checkReturn('testReturnNull6', commonMasks.dynamicType);
- checkReturn('testReturnNotEquals', commonMasks.boolType);
- }));
+ checkFactoryConstructor(String className, String factoryName) {
+ var cls = findElement(compiler, className);
+ var element = cls.localLookup(factoryName);
+ Expect.equals(new TypeMask.nonNullExact(cls, world),
+ typesInferrer.getReturnTypeOfElement(element));
+ }
+
+ checkFactoryConstructor('A', '');
+
+ checkReturn('testCascade1', commonMasks.growableListType);
+ checkReturn(
+ 'testCascade2',
+ new TypeMask.nonNullExact(
+ findElement(compiler, 'CascadeHelper'), world));
+ checkReturn('testSpecialization1', commonMasks.numType);
+ checkReturn('testSpecialization2', commonMasks.dynamicType);
+ checkReturn('testSpecialization3', commonMasks.uint31Type.nullable());
+ checkReturn('testReturnNull1', commonMasks.nullType);
+ checkReturn('testReturnNull2', commonMasks.nullType);
+ checkReturn('testReturnNull3', commonMasks.dynamicType);
+ checkReturn('testReturnNull4', commonMasks.nullType);
+ checkReturn('testReturnNull5', commonMasks.nullType);
+ checkReturn('testReturnNull6', commonMasks.dynamicType);
+ checkReturn('testReturnNotEquals', commonMasks.boolType);
+ }));
}
diff --git a/tests/compiler/dart2js/simple_inferrer_try_catch_test.dart b/tests/compiler/dart2js/simple_inferrer_try_catch_test.dart
index fb8ea18..f17308b 100644
--- a/tests/compiler/dart2js/simple_inferrer_try_catch_test.dart
+++ b/tests/compiler/dart2js/simple_inferrer_try_catch_test.dart
@@ -4,8 +4,7 @@
import 'package:expect/expect.dart';
import "package:async_helper/async_helper.dart";
-import 'package:compiler/src/types/types.dart'
- show TypeMask;
+import 'package:compiler/src/types/types.dart' show TypeMask;
import 'compiler_helper.dart';
import 'type_mask_test_helper.dart';
@@ -164,36 +163,39 @@
}
""";
-
void main() {
Uri uri = new Uri(scheme: 'source');
var compiler = compilerFor(TEST, uri);
asyncTest(() => compiler.run(uri).then((_) {
- var commonMasks = compiler.commonMasks;
- var typesInferrer = compiler.globalInference.typesInferrer;
+ var commonMasks = compiler.commonMasks;
+ var typesInferrer = compiler.globalInference.typesInferrer;
- checkReturn(String name, type) {
- var element = findElement(compiler, name);
- Expect.equals(type,
- simplify(typesInferrer.getReturnTypeOfElement(element), compiler));
- }
+ checkReturn(String name, type) {
+ var element = findElement(compiler, name);
+ Expect.equals(
+ type,
+ simplify(
+ typesInferrer.getReturnTypeOfElement(element), compiler));
+ }
- checkReturn('returnInt1', commonMasks.uint31Type);
- checkReturn('returnInt2', commonMasks.uint31Type);
- checkReturn('returnInt3', commonMasks.uint31Type);
- checkReturn('returnInt4', commonMasks.uint31Type);
- checkReturn('returnInt5', commonMasks.uint31Type);
- checkReturn('returnInt6', new TypeMask.nonNullSubtype(
- compiler.coreClasses.intClass, compiler.world));
+ checkReturn('returnInt1', commonMasks.uint31Type);
+ checkReturn('returnInt2', commonMasks.uint31Type);
+ checkReturn('returnInt3', commonMasks.uint31Type);
+ checkReturn('returnInt4', commonMasks.uint31Type);
+ checkReturn('returnInt5', commonMasks.uint31Type);
+ checkReturn(
+ 'returnInt6',
+ new TypeMask.nonNullSubtype(
+ compiler.coreClasses.intClass, compiler.world));
- var subclassOfInterceptor =
- findTypeMask(compiler, 'Interceptor', 'nonNullSubclass');
+ var subclassOfInterceptor =
+ findTypeMask(compiler, 'Interceptor', 'nonNullSubclass');
- checkReturn('returnDyn1', subclassOfInterceptor);
- checkReturn('returnDyn2', subclassOfInterceptor);
- checkReturn('returnDyn3', subclassOfInterceptor);
- checkReturn('returnDyn4', subclassOfInterceptor);
- checkReturn('returnDyn5', subclassOfInterceptor);
- checkReturn('returnDyn6', commonMasks.dynamicType);
- }));
+ checkReturn('returnDyn1', subclassOfInterceptor);
+ checkReturn('returnDyn2', subclassOfInterceptor);
+ checkReturn('returnDyn3', subclassOfInterceptor);
+ checkReturn('returnDyn4', subclassOfInterceptor);
+ checkReturn('returnDyn5', subclassOfInterceptor);
+ checkReturn('returnDyn6', commonMasks.dynamicType);
+ }));
}
diff --git a/tests/compiler/dart2js/simple_inferrer_unregister_call_test.dart b/tests/compiler/dart2js/simple_inferrer_unregister_call_test.dart
index 96cce73..1253b83 100644
--- a/tests/compiler/dart2js/simple_inferrer_unregister_call_test.dart
+++ b/tests/compiler/dart2js/simple_inferrer_unregister_call_test.dart
@@ -28,19 +28,18 @@
}
""";
-
void main() {
Uri uri = new Uri(scheme: 'source');
var compiler = compilerFor(TEST, uri);
asyncTest(() => compiler.run(uri).then((_) {
- var typesInferrer = compiler.globalInference.typesInferrer;
+ var typesInferrer = compiler.globalInference.typesInferrer;
- checkReturnInClass(String className, String methodName, type) {
- var cls = findElement(compiler, className);
- var element = cls.lookupLocalMember(methodName);
- Expect.equals(type, typesInferrer.getReturnTypeOfElement(element));
- }
+ checkReturnInClass(String className, String methodName, type) {
+ var cls = findElement(compiler, className);
+ var element = cls.lookupLocalMember(methodName);
+ Expect.equals(type, typesInferrer.getReturnTypeOfElement(element));
+ }
- checkReturnInClass('A', '+', compiler.commonMasks.uint31Type);
- }));
+ checkReturnInClass('A', '+', compiler.commonMasks.uint31Type);
+ }));
}
diff --git a/tests/compiler/dart2js/size_test.dart b/tests/compiler/dart2js/size_test.dart
index 48bf71b..74f5106 100644
--- a/tests/compiler/dart2js/size_test.dart
+++ b/tests/compiler/dart2js/size_test.dart
@@ -26,13 +26,13 @@
};
main() {
- asyncTest(() => compileAll(TEST, coreSource: DEFAULT_CORELIB_WITH_LIST).
- then((generated) {
- return MockCompiler.create((MockCompiler compiler) {
- var backend = compiler.backend;
+ asyncTest(() =>
+ compileAll(TEST, coreSource: DEFAULT_CORELIB_WITH_LIST).then((generated) {
+ return MockCompiler.create((MockCompiler compiler) {
+ var backend = compiler.backend;
- // Make sure no class is emitted.
- Expect.isFalse(generated.contains('finishClasses'));
- });
- }));
+ // Make sure no class is emitted.
+ Expect.isFalse(generated.contains('finishClasses'));
+ });
+ }));
}
diff --git a/tests/compiler/dart2js/source_map_d2js_validity_test.dart b/tests/compiler/dart2js/source_map_d2js_validity_test.dart
index 3829144..fe4ff6e 100644
--- a/tests/compiler/dart2js/source_map_d2js_validity_test.dart
+++ b/tests/compiler/dart2js/source_map_d2js_validity_test.dart
@@ -16,24 +16,21 @@
String mainFile =
'tests/compiler/dart2js/source_map_validator_test_file.dart';
asyncTest(() => createTempDir().then((Directory tmpDir) {
- print(
- 'Compiling tests/compiler/dart2js/source_map_validator_test_file.dart');
- Future<CompilationResult> result = entry.internalMain(
- [mainFile,
- '-o${tmpDir.path}/out.js',
- '--library-root=sdk']);
- return result.then((CompilationResult result) {
- CompilerImpl compiler = result.compiler;
- Uri uri =
- new Uri.file('${tmpDir.path}/out.js', windows: Platform.isWindows);
- validateSourceMap(uri,
- mainUri: Uri.base.resolve(mainFile),
- mainPosition: const Position(13, 1),
- compiler: compiler);
+ print(
+ 'Compiling tests/compiler/dart2js/source_map_validator_test_file.dart');
+ Future<CompilationResult> result = entry.internalMain(
+ [mainFile, '-o${tmpDir.path}/out.js', '--library-root=sdk']);
+ return result.then((CompilationResult result) {
+ CompilerImpl compiler = result.compiler;
+ Uri uri = new Uri.file('${tmpDir.path}/out.js',
+ windows: Platform.isWindows);
+ validateSourceMap(uri,
+ mainUri: Uri.base.resolve(mainFile),
+ mainPosition: const Position(13, 1),
+ compiler: compiler);
- print("Deleting '${tmpDir.path}'.");
- tmpDir.deleteSync(recursive: true);
- });
- }));
+ print("Deleting '${tmpDir.path}'.");
+ tmpDir.deleteSync(recursive: true);
+ });
+ }));
}
-
diff --git a/tests/compiler/dart2js/source_map_deferred_d2js_validity_test.dart b/tests/compiler/dart2js/source_map_deferred_d2js_validity_test.dart
index 0afe96e..e15471c 100644
--- a/tests/compiler/dart2js/source_map_deferred_d2js_validity_test.dart
+++ b/tests/compiler/dart2js/source_map_deferred_d2js_validity_test.dart
@@ -14,28 +14,25 @@
void main() {
asyncTest(() => createTempDir().then((Directory tmpDir) {
- String file =
- 'tests/compiler/dart2js/source_map_deferred_validator_test_file.dart';
- print("Compiling $file");
- Future result = entry.internalMain(
- [file,
- '-o${tmpDir.path}/out.js',
- '--library-root=sdk']);
- return result.then((CompilationResult result) {
- CompilerImpl compiler = result.compiler;
- Uri mainUri = new Uri.file('${tmpDir.path}/out.js',
- windows: Platform.isWindows);
- Uri deferredUri = new Uri.file('${tmpDir.path}/out.js_1.part.js',
- windows: Platform.isWindows);
- validateSourceMap(mainUri,
- mainUri: Uri.base.resolve(file),
- mainPosition: const Position(7, 1),
- compiler: compiler);
- validateSourceMap(deferredUri,
- compiler: compiler);
+ String file =
+ 'tests/compiler/dart2js/source_map_deferred_validator_test_file.dart';
+ print("Compiling $file");
+ Future result = entry.internalMain(
+ [file, '-o${tmpDir.path}/out.js', '--library-root=sdk']);
+ return result.then((CompilationResult result) {
+ CompilerImpl compiler = result.compiler;
+ Uri mainUri = new Uri.file('${tmpDir.path}/out.js',
+ windows: Platform.isWindows);
+ Uri deferredUri = new Uri.file('${tmpDir.path}/out.js_1.part.js',
+ windows: Platform.isWindows);
+ validateSourceMap(mainUri,
+ mainUri: Uri.base.resolve(file),
+ mainPosition: const Position(7, 1),
+ compiler: compiler);
+ validateSourceMap(deferredUri, compiler: compiler);
- print("Deleting '${tmpDir.path}'.");
- tmpDir.deleteSync(recursive: true);
- });
- }));
+ print("Deleting '${tmpDir.path}'.");
+ tmpDir.deleteSync(recursive: true);
+ });
+ }));
}
diff --git a/tests/compiler/dart2js/source_map_deferred_validator_test_file.dart b/tests/compiler/dart2js/source_map_deferred_validator_test_file.dart
index 08ae57f..1064e2e 100644
--- a/tests/compiler/dart2js/source_map_deferred_validator_test_file.dart
+++ b/tests/compiler/dart2js/source_map_deferred_validator_test_file.dart
@@ -11,4 +11,4 @@
helloClass.printHello();
}();
});
-}
\ No newline at end of file
+}
diff --git a/tests/compiler/dart2js/source_map_name_test.dart b/tests/compiler/dart2js/source_map_name_test.dart
index fae5649..f0e1ec4 100644
--- a/tests/compiler/dart2js/source_map_name_test.dart
+++ b/tests/compiler/dart2js/source_map_name_test.dart
@@ -73,9 +73,7 @@
check(Element element, String expectedName) {
String name = computeElementNameForSourceMaps(element);
- Expect.equals(
- expectedName,
- name,
+ Expect.equals(expectedName, name,
"Unexpected name '$name' for $element, expected '$expectedName'.");
}
@@ -101,8 +99,7 @@
}
void checkName(String expectedName,
- [List<String> expectedClosureNames,
- String lookupName]) {
+ [List<String> expectedClosureNames, String lookupName]) {
if (lookupName == null) {
lookupName = expectedName;
}
@@ -111,8 +108,8 @@
if (element.isConstructor) {
var constructorBody =
element.enclosingClass.lookupBackendMember(element.name);
- Expect.isNotNull(element,
- "Constructor body '${element.name}' not found.");
+ Expect.isNotNull(
+ element, "Constructor body '${element.name}' not found.");
check(constructorBody, expectedName);
}
@@ -130,37 +127,29 @@
checkName('toplevelField');
checkName('toplevelMethod');
- checkName('toplevelAnonymous',
- ['toplevelAnonymous.<anonymous function>']);
- checkName('toplevelLocal',
- ['toplevelLocal.localMethod']);
+ checkName('toplevelAnonymous', ['toplevelAnonymous.<anonymous function>']);
+ checkName('toplevelLocal', ['toplevelLocal.localMethod']);
checkName('Class');
checkName('main');
checkName('Class.staticField');
checkName('Class.staticMethod');
checkName('Class.staticAnonymous',
- ['Class.staticAnonymous.<anonymous function>']);
- checkName('Class.staticLocal',
- ['Class.staticLocal.localMethod']);
+ ['Class.staticAnonymous.<anonymous function>']);
+ checkName('Class.staticLocal', ['Class.staticLocal.localMethod']);
- checkName('Class',
- ['Class.<anonymous function>'],
- 'Class.');
- checkName('Class.named',
- ['Class.named.localMethod']);
+ checkName('Class', ['Class.<anonymous function>'], 'Class.');
+ checkName('Class.named', ['Class.named.localMethod']);
checkName('Class.instanceField');
checkName('Class.instanceMethod');
checkName('Class.instanceAnonymous',
- ['Class.instanceAnonymous.<anonymous function>']);
- checkName('Class.instanceLocal',
- ['Class.instanceLocal.localMethod']);
- checkName('Class.instanceNestedLocal',
- ['Class.instanceNestedLocal.localMethod',
- 'Class.instanceNestedLocal.localMethod.<anonymous function>',
- 'Class.instanceNestedLocal.localMethod.nestedLocalMethod']);
-
-
+ ['Class.instanceAnonymous.<anonymous function>']);
+ checkName('Class.instanceLocal', ['Class.instanceLocal.localMethod']);
+ checkName('Class.instanceNestedLocal', [
+ 'Class.instanceNestedLocal.localMethod',
+ 'Class.instanceNestedLocal.localMethod.<anonymous function>',
+ 'Class.instanceNestedLocal.localMethod.nestedLocalMethod'
+ ]);
});
-}
\ No newline at end of file
+}
diff --git a/tests/compiler/dart2js/source_map_pub_build_validity_test.dart b/tests/compiler/dart2js/source_map_pub_build_validity_test.dart
index 71fd04c..5eaff5b 100644
--- a/tests/compiler/dart2js/source_map_pub_build_validity_test.dart
+++ b/tests/compiler/dart2js/source_map_pub_build_validity_test.dart
@@ -20,20 +20,20 @@
copyDirectory(sunflowerDir, tmpDir);
String ext = Platform.isWindows ? '.bat' : '';
String command = path.normalize(path.join(
- path.fromUri(Platform.script),
- '../../../../sdk/bin/pub${ext}'));
+ path.fromUri(Platform.script), '../../../../sdk/bin/pub${ext}'));
String file = path.join(tmpDir.path, 'build/web/sunflower.dart.js');
print("Running '$command get' from '${tmpDir}'.");
- ProcessResult getResult = await Process.run(
- command, ['get'], workingDirectory: tmpDir.path);
+ ProcessResult getResult =
+ await Process.run(command, ['get'], workingDirectory: tmpDir.path);
print(getResult.stdout);
print(getResult.stderr);
Expect.equals(0, getResult.exitCode, 'Unexpected exitCode from pub get');
print("Running '$command build --mode=debug' from '${tmpDir}'.");
ProcessResult buildResult = await Process.run(
- command, ['build','--mode=debug'], workingDirectory: tmpDir.path);
+ command, ['build', '--mode=debug'],
+ workingDirectory: tmpDir.path);
print(buildResult.stdout);
print(buildResult.stderr);
Expect.equals(0, buildResult.exitCode, 'Unexpected exitCode from pub');
diff --git a/tests/compiler/dart2js/source_map_test.dart b/tests/compiler/dart2js/source_map_test.dart
index 3d3c2ea..4d8cb5a 100644
--- a/tests/compiler/dart2js/source_map_test.dart
+++ b/tests/compiler/dart2js/source_map_test.dart
@@ -24,7 +24,8 @@
Expect.isTrue(found, 'Expected "$substring" in:\n$text');
}
if (!expected && found) {
- Expect.isFalse(found,
+ Expect.isFalse(
+ found,
'Unexpected "$substring" in:\n'
'${text.substring(text.indexOf(substring))}');
}
@@ -67,9 +68,15 @@
await test();
await test(sourceMap: 'file:/out.js.map');
await test(out: 'file:/out.js');
- await test(out: 'file:/out.js', sourceMap: 'file:/out.js.map',
- file: 'out.js', mapping: 'out.js.map');
- await test(out: 'file:/dir/out.js', sourceMap: 'file:/dir/out.js.map',
- file: 'out.js', mapping: 'out.js.map');
+ await test(
+ out: 'file:/out.js',
+ sourceMap: 'file:/out.js.map',
+ file: 'out.js',
+ mapping: 'out.js.map');
+ await test(
+ out: 'file:/dir/out.js',
+ sourceMap: 'file:/dir/out.js.map',
+ file: 'out.js',
+ mapping: 'out.js.map');
});
-}
\ No newline at end of file
+}
diff --git a/tests/compiler/dart2js/source_map_validator_helper.dart b/tests/compiler/dart2js/source_map_validator_helper.dart
index ef0aff1..7fe628d 100644
--- a/tests/compiler/dart2js/source_map_validator_helper.dart
+++ b/tests/compiler/dart2js/source_map_validator_helper.dart
@@ -11,21 +11,20 @@
import 'package:source_maps/source_maps.dart';
import 'package:compiler/src/apiimpl.dart';
import 'package:compiler/src/elements/elements.dart'
- show AstElement,
- ClassElement,
- CompilationUnitElement,
- Element,
- FunctionElement,
- LibraryElement,
- MemberElement;
+ show
+ AstElement,
+ ClassElement,
+ CompilationUnitElement,
+ Element,
+ FunctionElement,
+ LibraryElement,
+ MemberElement;
import 'package:compiler/src/io/source_file.dart' show SourceFile;
import 'package:compiler/src/io/source_information.dart'
show computeElementNameForSourceMaps;
validateSourceMap(Uri targetUri,
- {Uri mainUri,
- Position mainPosition,
- CompilerImpl compiler}) {
+ {Uri mainUri, Position mainPosition, CompilerImpl compiler}) {
Uri mapUri = getMapUri(targetUri);
List<String> targetLines = new File.fromUri(targetUri).readAsLinesSync();
SingleMapping sourceMap = getSourceMap(mapUri);
@@ -36,19 +35,19 @@
checkNames(targetUri, mapUri, sourceMap, compiler);
}
if (mainUri != null && mainPosition != null) {
- checkMainPosition(targetUri, targetLines ,sourceMap, mainUri, mainPosition);
+ checkMainPosition(targetUri, targetLines, sourceMap, mainUri, mainPosition);
}
}
-checkIndexReferences(List<String> targetLines,
- Uri mapUri,
- SingleMapping sourceMap) {
+checkIndexReferences(
+ List<String> targetLines, Uri mapUri, SingleMapping sourceMap) {
int urlsLength = sourceMap.urls.length;
List<List<String>> sources = new List(urlsLength);
print('Reading sources');
for (int i = 0; i < urlsLength; i++) {
- sources[i] = new File.fromUri(mapUri.resolve(sourceMap.urls[i])).
- readAsStringSync().split('\n');
+ sources[i] = new File.fromUri(mapUri.resolve(sourceMap.urls[i]))
+ .readAsStringSync()
+ .split('\n');
}
sourceMap.lines.forEach((TargetLineEntry line) {
@@ -62,17 +61,17 @@
//
// Expect.isTrue(entry.column < target[line.line].length);
Expect.isTrue(entry.column >= 0);
- Expect.isTrue(urlIndex == null ||
- (urlIndex >= 0 && urlIndex < urlsLength));
+ Expect
+ .isTrue(urlIndex == null || (urlIndex >= 0 && urlIndex < urlsLength));
Expect.isTrue(entry.sourceLine == null ||
(entry.sourceLine >= 0 &&
- entry.sourceLine < sources[urlIndex].length));
+ entry.sourceLine < sources[urlIndex].length));
Expect.isTrue(entry.sourceColumn == null ||
(entry.sourceColumn >= 0 &&
- entry.sourceColumn < sources[urlIndex][entry.sourceLine].length));
+ entry.sourceColumn < sources[urlIndex][entry.sourceLine].length));
Expect.isTrue(entry.sourceNameId == null ||
(entry.sourceNameId >= 0 &&
- entry.sourceNameId < sourceMap.names.length));
+ entry.sourceNameId < sourceMap.names.length));
}
});
}
@@ -90,7 +89,8 @@
TargetEntry previous = null;
for (TargetEntry next in line.entries) {
if (previous != null) {
- Expect.isFalse(sameSourcePoint(previous, next),
+ Expect.isFalse(
+ sameSourcePoint(previous, next),
'$previous and $next are consecutive entries on line $line in the '
'source map but point to same source locations');
}
@@ -99,8 +99,8 @@
});
}
-checkNames(Uri targetUri, Uri mapUri,
- SingleMapping sourceMap, CompilerImpl compiler) {
+checkNames(
+ Uri targetUri, Uri mapUri, SingleMapping sourceMap, CompilerImpl compiler) {
Map<Uri, CompilationUnitElement> compilationUnitMap = {};
void mapCompilationUnits(LibraryElement library) {
@@ -120,15 +120,14 @@
for (TargetEntry entry in line.entries) {
if (entry.sourceNameId != null) {
Uri uri = mapUri.resolve(sourceMap.urls[entry.sourceUrlId]);
- Position targetPosition =
- new Position(line.line, entry.column);
+ Position targetPosition = new Position(line.line, entry.column);
Position sourcePosition =
new Position(entry.sourceLine, entry.sourceColumn);
String name = sourceMap.names[entry.sourceNameId];
CompilationUnitElement compilationUnit = compilationUnitMap[uri];
- Expect.isNotNull(compilationUnit,
- "No compilation unit found for $uri.");
+ Expect.isNotNull(
+ compilationUnit, "No compilation unit found for $uri.");
SourceFile sourceFile = compilationUnit.script.file;
@@ -144,8 +143,8 @@
var begin = element.node.getBeginToken().charOffset;
var end = element.node.getEndToken();
end = end.charOffset + end.charCount;
- return new Interval(positionFromOffset(begin),
- positionFromOffset(end));
+ return new Interval(
+ positionFromOffset(begin), positionFromOffset(end));
}
AstElement findInnermost(AstElement element) {
@@ -177,8 +176,7 @@
Interval interval = intervalFromElement(element);
if (interval != null && interval.contains(sourcePosition)) {
AstElement innerElement = findInnermost(element);
- String expectedName =
- computeElementNameForSourceMaps(innerElement);
+ String expectedName = computeElementNameForSourceMaps(innerElement);
if (name != expectedName) {
// For the code
// (){}();
@@ -191,12 +189,15 @@
var enclosingElement = innerElement.enclosingElement;
String expectedName2 =
computeElementNameForSourceMaps(enclosingElement);
- Expect.isTrue(name == expectedName2,
+ Expect.isTrue(
+ name == expectedName2,
"Unexpected name '${name}', "
"expected '${expectedName}' for $innerElement "
"or '${expectedName2}' for $enclosingElement.");
} else {
- Expect.equals(expectedName, name,
+ Expect.equals(
+ expectedName,
+ name,
"Unexpected name '${name}', "
"expected '${expectedName}' or for $innerElement.");
}
@@ -221,11 +222,8 @@
// Check that the line pointing to by [mainPosition] in [mainUri] contains
// the main function signature.
-checkMainPosition(Uri targetUri,
- List<String> targetLines,
- SingleMapping sourceMap,
- Uri mainUri,
- Position mainPosition) {
+checkMainPosition(Uri targetUri, List<String> targetLines,
+ SingleMapping sourceMap, Uri mainUri, Position mainPosition) {
bool mainPositionFound = false;
sourceMap.lines.forEach((TargetLineEntry lineEntry) {
lineEntry.entries.forEach((TargetEntry entry) {
@@ -234,13 +232,13 @@
if (sourceUri != mainUri) return;
if (entry.sourceLine + 1 == mainPosition.line &&
entry.sourceColumn + 1 == mainPosition.column) {
- Expect.isNotNull(entry.sourceNameId,
- "Main position has no name.");
+ Expect.isNotNull(entry.sourceNameId, "Main position has no name.");
String name = sourceMap.names[entry.sourceNameId];
- Expect.equals('main', name,
- "Main position name is not '$name', not 'main'.");
+ Expect.equals(
+ 'main', name, "Main position name is not '$name', not 'main'.");
String line = targetLines[lineEntry.line];
- Expect.isTrue(line.contains(mainSignaturePrefix),
+ Expect.isTrue(
+ line.contains(mainSignaturePrefix),
"Line mapped to main position "
"([${lineEntry.line + 1},${entry.column + 1}]) "
"expected to contain '${mainSignaturePrefix.pattern}':\n$line\n");
@@ -248,14 +246,12 @@
}
});
});
- Expect.isTrue(mainPositionFound,
- 'No main position $mainPosition found in $mainUri');
+ Expect.isTrue(
+ mainPositionFound, 'No main position $mainPosition found in $mainUri');
}
-
sameSourcePoint(TargetEntry entry, TargetEntry otherEntry) {
- return
- (entry.sourceUrlId == otherEntry.sourceUrlId) &&
+ return (entry.sourceUrlId == otherEntry.sourceUrlId) &&
(entry.sourceLine == otherEntry.sourceLine) &&
(entry.sourceColumn == otherEntry.sourceColumn) &&
(entry.sourceNameId == otherEntry.sourceNameId);
@@ -276,14 +272,13 @@
print('Accessing $mapUri');
File mapFile = new File.fromUri(mapUri);
Expect.isTrue(mapFile.existsSync());
- return new SingleMapping.fromJson(
- JSON.decode(mapFile.readAsStringSync()));
+ return new SingleMapping.fromJson(JSON.decode(mapFile.readAsStringSync()));
}
copyDirectory(Directory sourceDir, Directory destinationDir) {
sourceDir.listSync().forEach((FileSystemEntity element) {
- String newPath = path.join(destinationDir.path,
- path.basename(element.path));
+ String newPath =
+ path.join(destinationDir.path, path.basename(element.path));
if (element is File) {
element.copySync(newPath);
} else if (element is Directory) {
@@ -309,8 +304,7 @@
const Position(this.line, this.column);
bool operator <=(Position other) {
- return line < other.line ||
- line == other.line && column <= other.column;
+ return line < other.line || line == other.line && column <= other.column;
}
String toString() => '[${line + 1},${column + 1}]';
@@ -327,4 +321,4 @@
}
String toString() => '$begin-$end';
-}
\ No newline at end of file
+}
diff --git a/tests/compiler/dart2js/source_map_validator_test_file.dart b/tests/compiler/dart2js/source_map_validator_test_file.dart
index fa3c33d..4df2443 100644
--- a/tests/compiler/dart2js/source_map_validator_test_file.dart
+++ b/tests/compiler/dart2js/source_map_validator_test_file.dart
@@ -15,4 +15,4 @@
HelloClass helloClass = new HelloClass();
helloClass.printHello();
}();
-}
\ No newline at end of file
+}
diff --git a/tests/compiler/dart2js/source_mapping_test.dart b/tests/compiler/dart2js/source_mapping_test.dart
index c061f99..db08551 100644
--- a/tests/compiler/dart2js/source_mapping_test.dart
+++ b/tests/compiler/dart2js/source_mapping_test.dart
@@ -9,8 +9,8 @@
import 'package:compiler/src/io/source_file.dart';
import 'package:compiler/src/io/source_information.dart';
import 'package:compiler/src/js_backend/js_backend.dart';
-import 'package:compiler/src/js_emitter/full_emitter/emitter.dart'
- as full show Emitter;
+import 'package:compiler/src/js_emitter/full_emitter/emitter.dart' as full
+ show Emitter;
import 'mock_compiler.dart';
@@ -23,8 +23,7 @@
// TODO(floitsch): the outputBuffers are only accessible in the full
// emitter.
full.Emitter fullEmitter = backend.emitter.emitter;
- return fullEmitter
- .outputBuffers[compiler.deferredLoadTask.mainOutputUnit];
+ return fullEmitter.outputBuffers[compiler.deferredLoadTask.mainOutputUnit];
});
}
@@ -39,26 +38,27 @@
SourceFile sourceFile = new StringSourceFile.fromName('<test script>', code);
asyncTest(() => compileAll(sourceFile).then((CodeOutput output) {
- Set<int> locations = new Set<int>();
- output.forEachSourceLocation((int offset, SourceLocation sourcePosition) {
- if (sourcePosition != null &&
- sourcePosition.sourceUri == sourceFile.uri) {
- locations.add(sourcePosition.offset);
- }
- });
+ Set<int> locations = new Set<int>();
+ output
+ .forEachSourceLocation((int offset, SourceLocation sourcePosition) {
+ if (sourcePosition != null &&
+ sourcePosition.sourceUri == sourceFile.uri) {
+ locations.add(sourcePosition.offset);
+ }
+ });
- for (int i = 0; i < expectedLocations.length; ++i) {
- int expectedLocation = expectedLocations[i];
- if (!locations.contains(expectedLocation)) {
- int originalLocation = expectedLocation + i;
- SourceFile sourceFileWithMarkers =
- new StringSourceFile.fromName('<test script>', codeWithMarkers);
- String message = sourceFileWithMarkers.getLocationMessage(
- 'Missing location', originalLocation, originalLocation + 1);
- Expect.fail(message);
- }
- }
- }));
+ for (int i = 0; i < expectedLocations.length; ++i) {
+ int expectedLocation = expectedLocations[i];
+ if (!locations.contains(expectedLocation)) {
+ int originalLocation = expectedLocation + i;
+ SourceFile sourceFileWithMarkers =
+ new StringSourceFile.fromName('<test script>', codeWithMarkers);
+ String message = sourceFileWithMarkers.getLocationMessage(
+ 'Missing location', originalLocation, originalLocation + 1);
+ Expect.fail(message);
+ }
+ }
+ }));
}
String FUNCTIONS_TEST = '''
@@ -72,7 +72,8 @@
String UNARY_TEST = 'void main() { ((x, y) { print(@-x + @~y); })(1,2); }';
-String BINARY_TEST = 'void main() { ((x, y) { if (x @!= y) print(x @* y); })(1,2); }';
+String BINARY_TEST =
+ 'void main() { ((x, y) { if (x @!= y) print(x @* y); })(1,2); }';
String SEND_TEST = '''
void main() {
diff --git a/tests/compiler/dart2js/sourcemaps/colors.dart b/tests/compiler/dart2js/sourcemaps/colors.dart
index b6fa6b4..4595382 100644
--- a/tests/compiler/dart2js/sourcemaps/colors.dart
+++ b/tests/compiler/dart2js/sourcemaps/colors.dart
@@ -72,7 +72,6 @@
return sb.toString();
}
-
}
/// A web color defined as HSV.
@@ -95,12 +94,12 @@
// Grey.
return new RGB(v, v, v);
}
- h /= 60.0; // Sector 0 to 5.
+ h /= 60.0; // Sector 0 to 5.
int i = h.floor();
double f = h - i; // Factorial part of [h].
double p = v * (1.0 - s);
double q = v * (1.0 - s * f);
- double t = v * (1.0 - s * (1.0 - f ));
+ double t = v * (1.0 - s * (1.0 - f));
switch (i) {
case 0:
return new RGB(v, t, p);
@@ -112,7 +111,7 @@
return new RGB(p, q, v);
case 4:
return new RGB(t, p, v);
- default: // case 5:
+ default: // case 5:
return new RGB(v, p, q);
}
}
diff --git a/tests/compiler/dart2js/sourcemaps/data/invokes_test_file.dart b/tests/compiler/dart2js/sourcemaps/data/invokes_test_file.dart
index 91670bc..be230b5 100644
--- a/tests/compiler/dart2js/sourcemaps/data/invokes_test_file.dart
+++ b/tests/compiler/dart2js/sourcemaps/data/invokes_test_file.dart
@@ -54,8 +54,8 @@
const toplevelConstField = toplevelFunction;
get toplevelGetter => () {
- counter++;
-};
+ counter++;
+ };
typedef F();
@@ -71,9 +71,8 @@
};
get superGetter => () {
- counter++;
- };
-
+ counter++;
+ };
}
class C<T> extends B {
@@ -92,8 +91,8 @@
static const staticConstField = staticFunction;
static get staticGetter => () {
- counter++;
- };
+ counter++;
+ };
instanceMethod() {
counter++;
@@ -104,8 +103,8 @@
};
get instanceGetter => () {
- counter++;
- };
+ counter++;
+ };
instanceInvokes() {
instanceMethod();
@@ -124,4 +123,4 @@
F();
T();
}
-}
\ No newline at end of file
+}
diff --git a/tests/compiler/dart2js/sourcemaps/data/operators_test_file.dart b/tests/compiler/dart2js/sourcemaps/data/operators_test_file.dart
index bbd85c0..6175e10 100644
--- a/tests/compiler/dart2js/sourcemaps/data/operators_test_file.dart
+++ b/tests/compiler/dart2js/sourcemaps/data/operators_test_file.dart
@@ -12,8 +12,8 @@
main(args) {
counter++;
- operations(args.length > 0,
- 0, 1.5, args[0], new Complex(0, 1), new Complex(1.5, 2.5));
+ operations(args.length > 0, 0, 1.5, args[0], new Complex(0, 1),
+ new Complex(1.5, 2.5));
return counter;
}
diff --git a/tests/compiler/dart2js/sourcemaps/diff.dart b/tests/compiler/dart2js/sourcemaps/diff.dart
index 4fd31c1..7505892 100644
--- a/tests/compiler/dart2js/sourcemaps/diff.dart
+++ b/tests/compiler/dart2js/sourcemaps/diff.dart
@@ -68,17 +68,15 @@
for (CodeLine codeLine in jsCodeLines) {
htmlBuffer.write('<tr><td class="${ClassNames.innerCell}">');
codeLine.printHtmlOn(htmlBuffer, context);
- htmlBuffer.write(
- '</td><td '
+ htmlBuffer.write('</td><td '
'class="${ClassNames.innerCell} ${ClassNames.sourceMapped}">');
List<CodeLine> lines = jsToDartMap[codeLine];
if (lines != null) {
for (CodeLine line in lines) {
- line.printHtmlOn(htmlBuffer,
- context.from(includeAnnotation: (a) {
- CodeLineAnnotation annotation = a.data;
- return annotation.annotationType.isSourceMapped;
- }));
+ line.printHtmlOn(htmlBuffer, context.from(includeAnnotation: (a) {
+ CodeLineAnnotation annotation = a.data;
+ return annotation.annotationType.isSourceMapped;
+ }));
}
}
htmlBuffer.write('</td></tr>');
@@ -101,9 +99,8 @@
Iterable<DiffColumn> get columns => _columns.keys;
- void printHtmlOn(DiffColumn column,
- StringBuffer htmlBuffer,
- HtmlPrintContext context) {
+ void printHtmlOn(
+ DiffColumn column, StringBuffer htmlBuffer, HtmlPrintContext context) {
DiffColumnBlock block = _columns[column];
if (block != null) {
block.printHtmlOn(htmlBuffer, context);
@@ -111,7 +108,6 @@
}
}
-
/// Align the content of [list1] and [list2].
///
/// If provided, [range1] and [range2] aligned the subranges of [list1] and
@@ -127,14 +123,13 @@
///
/// [handleUnmatched] is called when two indices don't match up (none are found
/// in the other list).
-void align(List list1,
- List list2,
- {Interval range1,
- Interval range2,
- bool match(a, b),
- void handleSkew(int listIndex, Interval range),
- void handleMatched(List<int> indices),
- void handleUnmatched(List<int> indices)}) {
+void align(List list1, List list2,
+ {Interval range1,
+ Interval range2,
+ bool match(a, b),
+ void handleSkew(int listIndex, Interval range),
+ void handleMatched(List<int> indices),
+ void handleUnmatched(List<int> indices)}) {
if (match == null) {
match = (a, b) => a == b;
}
@@ -146,16 +141,15 @@
range2 = new Interval(0, list2.length);
}
- Interval findInOther(
- List thisLines, Interval thisRange,
- List otherLines, Interval otherRange) {
+ Interval findInOther(List thisLines, Interval thisRange, List otherLines,
+ Interval otherRange) {
for (int index = otherRange.from; index < otherRange.to; index++) {
if (match(thisLines[thisRange.from], otherLines[index])) {
int offset = 1;
while (thisRange.from + offset < thisRange.to &&
- otherRange.from + offset < otherRange.to &&
- match(thisLines[thisRange.from + offset],
- otherLines[otherRange.from + offset])) {
+ otherRange.from + offset < otherRange.to &&
+ match(thisLines[thisRange.from + offset],
+ otherLines[otherRange.from + offset])) {
offset++;
}
return new Interval(index, index + offset);
@@ -229,8 +223,7 @@
/// Create a list of blocks containing the diff of the two output [structures]
/// and the corresponding Dart code.
List<DiffBlock> createDiffBlocks(
- List<OutputStructure> structures,
- SourceFileManager sourceFileManager) {
+ List<OutputStructure> structures, SourceFileManager sourceFileManager) {
return new DiffCreator(structures, sourceFileManager).computeBlocks();
}
@@ -263,25 +256,23 @@
/// [mainSources] are tagged as original code sources, the rest as inlined
/// code sources.
DiffColumnBlock codeLinesFromCodeSources(
- Iterable<CodeSource> mainSources,
- Iterable<CodeSource> codeSources) {
+ Iterable<CodeSource> mainSources, Iterable<CodeSource> codeSources) {
List<HtmlPart> parts = <HtmlPart>[];
for (CodeSource codeSource in codeSources) {
//parts.addAll(codeLinesFromCodeSource(codeSource));
- String className =
- mainSources.contains(codeSource)
- ? ClassNames.originalDart : ClassNames.inlinedDart;
- parts.add(
- new TagPart('div',
- properties: {'class': className},
- content: codeLinesFromCodeSource(codeSource)));
+ String className = mainSources.contains(codeSource)
+ ? ClassNames.originalDart
+ : ClassNames.inlinedDart;
+ parts.add(new TagPart('div',
+ properties: {'class': className},
+ content: codeLinesFromCodeSource(codeSource)));
}
return new PartsColumnBlock(parts);
}
/// Adds all [CodeSource]s used in [dartCodeLines] to [codeSourceSet].
void collectCodeSources(Set<CodeSource> codeSourceSet,
- Map<CodeLine, List<CodeLine>> dartCodeLines) {
+ Map<CodeLine, List<CodeLine>> dartCodeLines) {
for (List<CodeLine> codeLines in dartCodeLines.values) {
for (CodeLine dartCodeLine in codeLines) {
if (dartCodeLine.lineAnnotation != null) {
@@ -316,9 +307,7 @@
/// Creates a block containing the code lines in [range] from input number
/// [index]. If [codeSource] is provided, the block will contain a
/// corresponding Dart code column.
- void handleSkew(
- int index,
- Interval range,
+ void handleSkew(int index, Interval range,
[Iterable<CodeSource> mainCodeSources = const <CodeSource>[]]) {
if (range.isEmpty) return;
@@ -331,14 +320,12 @@
inputLines[index].sublist(range.from, range.to);
Map<CodeLine, List<CodeLine>> dartCodeLines =
dartCodeLinesFromJsCodeLines(jsCodeLines);
- block.addColumnBlock(
- new DiffColumn('js', index),
+ block.addColumnBlock(new DiffColumn('js', index),
new CodeLinesColumnBlock(jsCodeLines, dartCodeLines));
collectCodeSources(codeSources, dartCodeLines);
if (codeSources.isNotEmpty) {
- block.addColumnBlock(
- const DiffColumn('dart'),
+ block.addColumnBlock(const DiffColumn('dart'),
codeLinesFromCodeSources(mainCodeSources, codeSources));
}
blocks.add(block);
@@ -347,9 +334,7 @@
/// Create a block containing the code lines in [ranges] from the
/// corresponding JavaScript inputs. If [codeSource] is provided, the block
/// will contain a corresponding Dart code column.
- void addLines(
- DiffKind kind,
- List<Interval> ranges,
+ void addLines(DiffKind kind, List<Interval> ranges,
[Iterable<CodeSource> mainCodeSources = const <CodeSource>[]]) {
if (ranges.every((range) => range.isEmpty)) return;
@@ -362,9 +347,8 @@
List<CodeLine> jsCodeLines =
inputLines[i].sublist(ranges[i].from, ranges[i].to);
Map<CodeLine, List<CodeLine>> dartCodeLines =
- dartCodeLinesFromJsCodeLines(jsCodeLines);
- block.addColumnBlock(
- new DiffColumn('js', i),
+ dartCodeLinesFromJsCodeLines(jsCodeLines);
+ block.addColumnBlock(new DiffColumn('js', i),
new CodeLinesColumnBlock(jsCodeLines, dartCodeLines));
collectCodeSources(codeSources, dartCodeLines);
}
@@ -402,37 +386,31 @@
if (current == null) {
return [
new Interval(indices[0], indices[0] + 1),
- new Interval(indices[1], indices[1] + 1)];
+ new Interval(indices[1], indices[1] + 1)
+ ];
} else {
- current[0] =
- new Interval(current[0].from, indices[0] + 1);
- current[1] =
- new Interval(current[1].from, indices[1] + 1);
+ current[0] = new Interval(current[0].from, indices[0] + 1);
+ current[1] = new Interval(current[1].from, indices[1] + 1);
return current;
}
}
- align(
- inputLines[0],
- inputLines[1],
+ align(inputLines[0], inputLines[1],
range1: range1,
range2: range2,
- match: match,
- handleSkew: (int listIndex, Interval range) {
- flushMatching();
- flushUnmatched();
- handleSkew(listIndex, range);
- },
- handleMatched: (List<int> indices) {
- flushUnmatched();
- currentMatchedIntervals =
- updateIntervals(currentMatchedIntervals, indices);
- },
- handleUnmatched: (List<int> indices) {
- flushMatching();
- currentUnmatchedIntervals =
- updateIntervals(currentUnmatchedIntervals, indices);
- });
+ match: match, handleSkew: (int listIndex, Interval range) {
+ flushMatching();
+ flushUnmatched();
+ handleSkew(listIndex, range);
+ }, handleMatched: (List<int> indices) {
+ flushUnmatched();
+ currentMatchedIntervals =
+ updateIntervals(currentMatchedIntervals, indices);
+ }, handleUnmatched: (List<int> indices) {
+ flushMatching();
+ currentUnmatchedIntervals =
+ updateIntervals(currentUnmatchedIntervals, indices);
+ });
flushMatching();
flushUnmatched();
@@ -449,8 +427,7 @@
void addSkewedEntity(int index, OutputEntity entity) {
if (entity.canHaveChildren) {
handleSkew(index, entity.header);
- addSkewedChildren(
- index, entity, new Interval(0, entity.children.length));
+ addSkewedChildren(index, entity, new Interval(0, entity.children.length));
handleSkew(index, entity.footer);
} else {
handleSkew(index, entity.interval, codeSourceFromEntities([entity]));
@@ -470,26 +447,25 @@
align(classes[0].children, classes[1].children,
match: (a, b) => a.name == b.name,
handleSkew: (int listIndex, Interval childRange) {
- addSkewedChildren(listIndex, classes[listIndex], childRange);
- },
- handleMatched: (List<int> indices) {
- List<BasicEntity> entities = [
- classes[0].getChild(indices[0]),
- classes[1].getChild(indices[1])];
- if (entities.every((e) => e is Statics)) {
- addMatchingContainers(entities);
- } else {
- addLines(DiffKind.MATCHING,
- entities.map((e) => e.interval).toList(),
- codeSourceFromEntities(entities));
- }
- },
- handleUnmatched: (List<int> indices) {
- List<Interval> intervals = [
- classes[0].getChild(indices[0]).interval,
- classes[1].getChild(indices[1]).interval];
- addLines(DiffKind.UNMATCHED, intervals);
- });
+ addSkewedChildren(listIndex, classes[listIndex], childRange);
+ }, handleMatched: (List<int> indices) {
+ List<BasicEntity> entities = [
+ classes[0].getChild(indices[0]),
+ classes[1].getChild(indices[1])
+ ];
+ if (entities.every((e) => e is Statics)) {
+ addMatchingContainers(entities);
+ } else {
+ addLines(DiffKind.MATCHING, entities.map((e) => e.interval).toList(),
+ codeSourceFromEntities(entities));
+ }
+ }, handleUnmatched: (List<int> indices) {
+ List<Interval> intervals = [
+ classes[0].getChild(indices[0]).interval,
+ classes[1].getChild(indices[1]).interval
+ ];
+ addLines(DiffKind.UNMATCHED, intervals);
+ });
addLines(DiffKind.MATCHING, classes.map((c) => c.footer).toList());
}
@@ -498,34 +474,32 @@
void addMatchingBlocks(List<int> indices) {
List<LibraryBlock> blocks = [
structures[0].getChild(indices[0]),
- structures[1].getChild(indices[1])];
+ structures[1].getChild(indices[1])
+ ];
addLines(DiffKind.MATCHING, blocks.map((b) => b.header).toList());
align(blocks[0].children, blocks[1].children,
match: (a, b) => a.name == b.name,
handleSkew: (int listIndex, Interval childRange) {
- addSkewedChildren(
- listIndex, blocks[listIndex], childRange);
- },
- handleMatched: (List<int> indices) {
- List<BasicEntity> entities = [
- blocks[0].getChild(indices[0]),
- blocks[1].getChild(indices[1])];
- if (entities.every((e) => e is LibraryClass)) {
- addMatchingContainers(entities);
- } else {
- addLines(
- DiffKind.MATCHING,
- entities.map((e) => e.interval).toList(),
- codeSourceFromEntities(entities));
- }
- },
- handleUnmatched: (List<int> indices) {
- List<Interval> intervals = [
- blocks[0].getChild(indices[0]).interval,
- blocks[1].getChild(indices[1]).interval];
- addLines(DiffKind.UNMATCHED, intervals);
- });
+ addSkewedChildren(listIndex, blocks[listIndex], childRange);
+ }, handleMatched: (List<int> indices) {
+ List<BasicEntity> entities = [
+ blocks[0].getChild(indices[0]),
+ blocks[1].getChild(indices[1])
+ ];
+ if (entities.every((e) => e is LibraryClass)) {
+ addMatchingContainers(entities);
+ } else {
+ addLines(DiffKind.MATCHING, entities.map((e) => e.interval).toList(),
+ codeSourceFromEntities(entities));
+ }
+ }, handleUnmatched: (List<int> indices) {
+ List<Interval> intervals = [
+ blocks[0].getChild(indices[0]).interval,
+ blocks[1].getChild(indices[1]).interval
+ ];
+ addLines(DiffKind.UNMATCHED, intervals);
+ });
addLines(DiffKind.MATCHING, blocks.map((b) => b.footer).toList());
}
@@ -533,8 +507,9 @@
/// [OutputStructure]s.
void addUnmatchedBlocks(List<int> indices) {
List<LibraryBlock> blocks = [
- structures[0].getChild(indices[0]),
- structures[1].getChild(indices[1])];
+ structures[0].getChild(indices[0]),
+ structures[1].getChild(indices[1])
+ ];
addLines(DiffKind.UNMATCHED, [blocks[0].interval, blocks[1].interval]);
}
@@ -542,12 +517,11 @@
List<DiffBlock> computeBlocks() {
addRaw(structures[0].header, structures[1].header);
- align(structures[0].children,
- structures[1].children,
- match: (a, b) => a.name == b.name,
- handleSkew: addBlock,
- handleMatched: addMatchingBlocks,
- handleUnmatched: addUnmatchedBlocks);
+ align(structures[0].children, structures[1].children,
+ match: (a, b) => a.name == b.name,
+ handleSkew: addBlock,
+ handleMatched: addMatchingBlocks,
+ handleUnmatched: addUnmatchedBlocks);
addRaw(structures[0].footer, structures[1].footer);
@@ -562,18 +536,15 @@
String elementName = codeSource.name;
HtmlLine line = new HtmlLine();
line.htmlParts.add(new ConstHtmlPart('<span class="comment">'));
- line.htmlParts.add(new HtmlText(
- '${elementName}: ${sourceFile.filename}'));
+ line.htmlParts.add(new HtmlText('${elementName}: ${sourceFile.filename}'));
line.htmlParts.add(new ConstHtmlPart('</span>'));
lines.add(line);
if (codeSource.begin != null) {
int startLine = sourceFile.getLine(codeSource.begin);
int endLine = sourceFile.getLine(codeSource.end) + 1;
for (CodeLine codeLine in convertAnnotatedCodeToCodeLines(
- sourceFile.slowText(),
- const <Annotation>[],
- startLine: startLine,
- endLine: endLine)) {
+ sourceFile.slowText(), const <Annotation>[],
+ startLine: startLine, endLine: endLine)) {
codeLine.lineAnnotation = codeSource;
lines.add(codeLine);
}
@@ -597,8 +568,9 @@
for (Annotation annotation in jsCodeLine.annotations) {
CodeLineAnnotation codeLineAnnotation = annotation.data;
for (CodeSource codeSource in codeLineAnnotation.codeSources) {
- codeSourceMap.putIfAbsent(codeSource.uri,
- () => new Set<CodeSource>()).add(codeSource);
+ codeSourceMap
+ .putIfAbsent(codeSource.uri, () => new Set<CodeSource>())
+ .add(codeSource);
}
}
}
@@ -608,13 +580,9 @@
Set<CodeSource> codeSources = codeSourceMap[currentUri];
SourceFile sourceFile = sourceFileManager.getSourceFile(currentUri);
- List<CodeLine> annotatedDartCodeLines =
- convertAnnotatedCodeToCodeLines(
- sourceFile.slowText(),
- annotations,
- startLine: interval.from,
- endLine: interval.to,
- uri: currentUri);
+ List<CodeLine> annotatedDartCodeLines = convertAnnotatedCodeToCodeLines(
+ sourceFile.slowText(), annotations,
+ startLine: interval.from, endLine: interval.to, uri: currentUri);
if (codeSources != null) {
CodeSource currentCodeSource;
Interval currentLineInterval;
@@ -648,8 +616,8 @@
}
}
while (index < annotatedDartCodeLines.length) {
- jsToDartMap[codeLineInterval.keys.last].add(
- annotatedDartCodeLines[index++]);
+ jsToDartMap[codeLineInterval.keys.last]
+ .add(annotatedDartCodeLines[index++]);
}
currentUri = null;
@@ -681,10 +649,8 @@
restart(jsCodeLine, location, line);
}
- annotations.add(new Annotation(
- codeLineAnnotation.annotationType,
- location.offset,
- 'id=${codeLineAnnotation.annotationId}',
+ annotations.add(new Annotation(codeLineAnnotation.annotationType,
+ location.offset, 'id=${codeLineAnnotation.annotationId}',
data: codeLineAnnotation));
}
}
@@ -756,7 +722,8 @@
WITH_SOURCE_INFO,
WITHOUT_SOURCE_INFO,
ADDITIONAL_SOURCE_INFO,
- UNUSED_SOURCE_INFO];
+ UNUSED_SOURCE_INFO
+ ];
}
class CodeLineAnnotation {
@@ -769,11 +736,11 @@
CodeLineAnnotation(
{this.annotationId,
- this.annotationType,
- this.codeLocations,
- this.codeSources,
- this.stepInfo,
- this.sourceMappingIndex});
+ this.annotationType,
+ this.codeLocations,
+ this.codeSources,
+ this.stepInfo,
+ this.sourceMappingIndex});
Map toJson(JsonStrategy strategy) {
return {
@@ -793,9 +760,8 @@
codeLocations: json['codeLocations']
.map((j) => CodeLocation.fromJson(j, strategy))
.toList(),
- codeSources: json['codeSources']
- .map((j) => CodeSource.fromJson(j))
- .toList(),
+ codeSources:
+ json['codeSources'].map((j) => CodeSource.fromJson(j)).toList(),
stepInfo: json['stepInfo'],
sourceMappingIndex: json['sourceMappingIndex']);
}
diff --git a/tests/compiler/dart2js/sourcemaps/diff_view.dart b/tests/compiler/dart2js/sourcemaps/diff_view.dart
index adeb641..bd29b49 100644
--- a/tests/compiler/dart2js/sourcemaps/diff_view.dart
+++ b/tests/compiler/dart2js/sourcemaps/diff_view.dart
@@ -90,15 +90,11 @@
output = AnnotatedOutput.loadOutput(loadFrom[i]);
} else {
print('Compiling ${options[i].join(' ')} $filename');
- CodeLinesResult result = await computeCodeLines(
- options[i], filename);
+ CodeLinesResult result = await computeCodeLines(options[i], filename);
OutputStructure structure = OutputStructure.parse(result.codeLines);
computeEntityCodeSources(result, structure);
output = new AnnotatedOutput(
- filename,
- options[i],
- structure,
- result.coverage.getCoverageReport());
+ filename, options[i], structure, result.coverage.getCoverageReport());
}
if (saveTo.containsKey(i)) {
AnnotatedOutput.saveOutput(output, saveTo[i]);
@@ -107,13 +103,10 @@
}
List<DiffBlock> blocks = createDiffBlocks(
- outputs.map((o) => o.structure).toList(),
- sourceFileManager);
+ outputs.map((o) => o.structure).toList(), sourceFileManager);
- outputDiffView(
- out, outputs, blocks,
- showMarkers: showAnnotations,
- showSourceMapped: showAnnotations);
+ outputDiffView(out, outputs, blocks,
+ showMarkers: showAnnotations, showSourceMapped: showAnnotations);
}
/// Attaches [CodeSource]s to the entities in [structure] using the
@@ -142,10 +135,7 @@
}
Annotation decodeAnnotation(Map json) {
- return new Annotation(
- json['id'],
- json['codeOffset'],
- json['title'],
+ return new Annotation(json['id'], json['codeOffset'], json['title'],
data: CodeLineAnnotation.fromJson(json['data'], this));
}
@@ -196,8 +186,8 @@
}
static AnnotatedOutput loadOutput(filename) {
- AnnotatedOutput output = AnnotatedOutput.fromJson(
- JSON.decode(new File(filename).readAsStringSync()));
+ AnnotatedOutput output = AnnotatedOutput
+ .fromJson(JSON.decode(new File(filename).readAsStringSync()));
print('Output loaded from $filename');
return output;
}
@@ -212,11 +202,8 @@
}
void outputDiffView(
- String out,
- List<AnnotatedOutput> outputs,
- List<DiffBlock> blocks,
- {bool showMarkers: true,
- bool showSourceMapped: true}) {
+ String out, List<AnnotatedOutput> outputs, List<DiffBlock> blocks,
+ {bool showMarkers: true, bool showSourceMapped: true}) {
assert(outputs[0].filename == outputs[1].filename);
bool usePre = true;
@@ -479,7 +466,6 @@
</span>
''');
-
/// Marker to alternate output colors.
bool alternating = false;
@@ -501,7 +487,8 @@
}
List<DiffColumn> columns = [column_js0, column_js1, column_dart]
- .where((c) => allColumns.contains(c)).toList();
+ .where((c) => allColumns.contains(c))
+ .toList();
sb.write('''
</div>
@@ -535,8 +522,7 @@
alternating = !alternating;
break;
case DiffKind.IDENTICAL:
- className =
- '${ClassNames.cell} ${ClassNames.identical(alternating)}';
+ className = '${ClassNames.cell} ${ClassNames.identical(alternating)}';
alternating = !alternating;
break;
}
@@ -548,7 +534,7 @@
includeAnnotation: (Annotation annotation) {
CodeLineAnnotation data = annotation.data;
return data.annotationType == AnnotationType.WITH_SOURCE_INFO ||
- data.annotationType == AnnotationType.ADDITIONAL_SOURCE_INFO;
+ data.annotationType == AnnotationType.ADDITIONAL_SOURCE_INFO;
},
getAnnotationData: getAnnotationData,
getLineData: getLineData);
@@ -623,12 +609,8 @@
final SourceFileManager sourceFileManager;
final CodeSources codeSources;
- CodeLinesResult(
- this.codeLines,
- this.coverage,
- this.elementMap,
- this.sourceFileManager,
- this.codeSources);
+ CodeLinesResult(this.codeLines, this.coverage, this.elementMap,
+ this.sourceFileManager, this.codeSources);
}
class CodeSources {
@@ -636,10 +618,7 @@
Map<Uri, Map<Interval, CodeSource>> uriCodeSourceMap =
<Uri, Map<Interval, CodeSource>>{};
- CodeSources(
- SourceMapProcessor processor,
- SourceMaps sourceMaps) {
-
+ CodeSources(SourceMapProcessor processor, SourceMaps sourceMaps) {
CodeSource computeCodeSource(Element element) {
return codeSourceMap.putIfAbsent(element, () {
CodeSource codeSource = codeSourceFromElement(element);
@@ -656,13 +635,13 @@
CodeSource existingCodeSource = intervals[existingInterval];
intervals.remove(existingInterval);
if (existingInterval.from < interval.from) {
- Interval preInterval = new Interval(
- existingInterval.from, interval.from);
+ Interval preInterval =
+ new Interval(existingInterval.from, interval.from);
intervals[preInterval] = existingCodeSource;
}
if (interval.to < existingInterval.to) {
- Interval postInterval = new Interval(
- interval.to, existingInterval.to);
+ Interval postInterval =
+ new Interval(interval.to, existingInterval.to);
intervals[postInterval] = existingCodeSource;
}
}
@@ -686,15 +665,15 @@
});
}
- for (LibraryElement library in
- sourceMaps.compiler.libraryLoader.libraries) {
+ for (LibraryElement library
+ in sourceMaps.compiler.libraryLoader.libraries) {
library.forEachLocalMember(computeCodeSource);
library.implementation.forEachLocalMember(computeCodeSource);
}
uriCodeSourceMap.forEach((Uri uri, Map<Interval, CodeSource> intervals) {
- List<Interval> sortedKeys = intervals.keys.toList()..sort(
- (i1, i2) => i1.from.compareTo(i2.from));
+ List<Interval> sortedKeys = intervals.keys.toList()
+ ..sort((i1, i2) => i1.from.compareTo(i2.from));
Map<Interval, CodeSource> sortedintervals = <Interval, CodeSource>{};
sortedKeys.forEach((Interval interval) {
sortedintervals[interval] = intervals[interval];
@@ -724,8 +703,7 @@
/// Compute [CodeLine]s and [Coverage] for [filename] using the given [options].
Future<CodeLinesResult> computeCodeLines(
- List<String> options,
- String filename) async {
+ List<String> options, String filename) async {
SourceMapProcessor processor = new SourceMapProcessor(filename);
SourceMaps sourceMaps =
await processor.process(options, perElement: true, forMain: true);
@@ -743,9 +721,9 @@
/// Create a [CodeLineAnnotation] for [codeOffset].
void addCodeLineAnnotation(
{AnnotationType annotationType,
- int codeOffset,
- List<SourceLocation> locations: const <SourceLocation>[],
- String stepInfo}) {
+ int codeOffset,
+ List<SourceLocation> locations: const <SourceLocation>[],
+ String stepInfo}) {
if (annotationType == AnnotationType.WITHOUT_SOURCE_INFO ||
annotationType == AnnotationType.UNUSED_SOURCE_INFO) {
locations = [];
@@ -763,8 +741,9 @@
codeLocations: codeLocations,
codeSources: codeSourceList,
stepInfo: stepInfo);
- codeLineAnnotationMap.putIfAbsent(
- codeOffset, () => <CodeLineAnnotation>[]).add(data);
+ codeLineAnnotationMap
+ .putIfAbsent(codeOffset, () => <CodeLineAnnotation>[])
+ .add(data);
}
String code = info.code;
@@ -775,9 +754,9 @@
/// Add an annotation for [codeOffset] pointing to [locations].
void addSourceLocations(
{AnnotationType annotationType,
- int codeOffset,
- List<SourceLocation> locations,
- String stepInfo}) {
+ int codeOffset,
+ List<SourceLocation> locations,
+ String stepInfo}) {
locations = locations.where((l) => l != null).toList();
addCodeLineAnnotation(
annotationType: annotationType,
@@ -788,9 +767,7 @@
/// Add annotations for all mappings created for [node].
bool addSourceLocationsForNode(
- {AnnotationType annotationType,
- js.Node node,
- String stepInfo}) {
+ {AnnotationType annotationType, js.Node node, String stepInfo}) {
Map<int, List<SourceLocation>> locations = info.nodeMap[node];
if (locations == null || locations.isEmpty) {
return false;
@@ -833,22 +810,21 @@
for (js.Node node in info.nodeMap.nodes) {
if (!mappedNodes.contains(node)) {
addSourceLocationsForNode(
- annotationType: AnnotationType.ADDITIONAL_SOURCE_INFO,
- node: node);
+ annotationType: AnnotationType.ADDITIONAL_SOURCE_INFO, node: node);
}
}
// Add annotations for unused source information associated with nodes.
SourceLocationCollector collector = new SourceLocationCollector();
info.node.accept(collector);
- collector.sourceLocations.forEach(
- (js.Node node, List<SourceLocation> locations) {
+ collector.sourceLocations
+ .forEach((js.Node node, List<SourceLocation> locations) {
if (!mappedNodes.contains(node)) {
int offset = info.jsCodePositions[node].startPosition;
addSourceLocations(
- annotationType: AnnotationType.UNUSED_SOURCE_INFO,
- codeOffset: offset,
- locations: locations);
+ annotationType: AnnotationType.UNUSED_SOURCE_INFO,
+ codeOffset: offset,
+ locations: locations);
}
});
@@ -863,9 +839,7 @@
hasSourceMappedLocation = true;
}
annotations.add(new Annotation(
- data.annotationType.index,
- codeOffset,
- 'id=${data.annotationId}',
+ data.annotationType.index, codeOffset, 'id=${data.annotationId}',
data: data));
}
if (hasSourceMappedLocation) {
@@ -876,17 +850,15 @@
// Associate JavaScript offsets with [Element]s.
StringSourceFile sourceFile = new StringSourceFile.fromName(filename, code);
Map<int, Element> elementMap = <int, Element>{};
- sourceMaps.elementSourceMapInfos.forEach(
- (Element element, SourceMapInfo info) {
+ sourceMaps.elementSourceMapInfos
+ .forEach((Element element, SourceMapInfo info) {
CodePosition position = info.jsCodePositions[info.node];
elementMap[sourceFile.getLine(position.startPosition)] = element;
});
codeLines = convertAnnotatedCodeToCodeLines(code, annotations);
- return new CodeLinesResult(
- codeLines, coverage, elementMap,
- sourceMaps.sourceFileManager,
- codeSources);
+ return new CodeLinesResult(codeLines, coverage, elementMap,
+ sourceMaps.sourceFileManager, codeSources);
}
/// Visitor that computes a map from [js.Node]s to all attached source
@@ -940,37 +912,31 @@
if (lineAnnotation != null) {
return new LineData(
lineClass: ClassNames.line,
- lineNumberClass:
- '${ClassNames.lineNumber} '
- '${ClassNames.colored(lineAnnotation.hashCode % 4)}');
+ lineNumberClass: '${ClassNames.lineNumber} '
+ '${ClassNames.colored(lineAnnotation.hashCode % 4)}');
}
return new LineData(
- lineClass: ClassNames.line,
- lineNumberClass: ClassNames.lineNumber);
+ lineClass: ClassNames.line, lineNumberClass: ClassNames.lineNumber);
}
AnnotationData getAnnotationData(Iterable<Annotation> annotations,
- {bool forSpan}) {
+ {bool forSpan}) {
for (Annotation annotation in annotations) {
CodeLineAnnotation data = annotation.data;
if (data.annotationType.isSourceMapped) {
if (forSpan) {
int index = data.sourceMappingIndex;
- return new AnnotationData(
- tag: 'span',
- properties: {
- 'class':
- '${ClassNames.sourceMapping} '
- '${ClassNames.sourceMappingIndex(index % HUE_COUNT)}',
- 'title': 'index=$index',
- });
+ return new AnnotationData(tag: 'span', properties: {
+ 'class': '${ClassNames.sourceMapping} '
+ '${ClassNames.sourceMappingIndex(index % HUE_COUNT)}',
+ 'title': 'index=$index',
+ });
} else {
- return new AnnotationData(
- tag: 'span',
- properties: {
- 'title': annotation.title,
- 'class': '${ClassNames.marker} '
- '${data.annotationType.className}'});
+ return new AnnotationData(tag: 'span', properties: {
+ 'title': annotation.title,
+ 'class': '${ClassNames.marker} '
+ '${data.annotationType.className}'
+ });
}
}
}
@@ -978,23 +944,21 @@
for (Annotation annotation in annotations) {
CodeLineAnnotation data = annotation.data;
if (data.annotationType == AnnotationType.UNUSED_SOURCE_INFO) {
- return new AnnotationData(
- tag: 'span',
- properties: {
- 'title': annotation.title,
- 'class': '${ClassNames.marker} '
- '${data.annotationType.className}'});
+ return new AnnotationData(tag: 'span', properties: {
+ 'title': annotation.title,
+ 'class': '${ClassNames.marker} '
+ '${data.annotationType.className}'
+ });
}
}
for (Annotation annotation in annotations) {
CodeLineAnnotation data = annotation.data;
if (data.annotationType == AnnotationType.WITHOUT_SOURCE_INFO) {
- return new AnnotationData(
- tag: 'span',
- properties: {
- 'title': annotation.title,
- 'class': '${ClassNames.marker} '
- '${data.annotationType.className}'});
+ return new AnnotationData(tag: 'span', properties: {
+ 'title': annotation.title,
+ 'class': '${ClassNames.marker} '
+ '${data.annotationType.className}'
+ });
}
}
return null;
diff --git a/tests/compiler/dart2js/sourcemaps/html_parts.dart b/tests/compiler/dart2js/sourcemaps/html_parts.dart
index 4d06f98..2691a09 100644
--- a/tests/compiler/dart2js/sourcemaps/html_parts.dart
+++ b/tests/compiler/dart2js/sourcemaps/html_parts.dart
@@ -16,8 +16,7 @@
}
typedef bool AnnotationFilter(Annotation annotation);
-typedef AnnotationData AnnotationDataFunction(
- Iterable<Annotation> annotations,
+typedef AnnotationData AnnotationDataFunction(Iterable<Annotation> annotations,
{bool forSpan});
typedef LineData LineDataFunction(lineAnnotation);
@@ -27,18 +26,15 @@
final String lineClass;
final String lineNumberClass;
- const LineData({
- this.lineClass: 'line',
- this.lineNumberClass: 'lineNumber'});
+ const LineData({this.lineClass: 'line', this.lineNumberClass: 'lineNumber'});
}
class AnnotationData {
final String tag;
final Map<String, String> properties;
- const AnnotationData({
- this.tag: 'a',
- this.properties: const <String, String>{}});
+ const AnnotationData(
+ {this.tag: 'a', this.properties: const <String, String>{}});
int get hashCode => tag.hashCode * 13 + properties.hashCode * 19;
@@ -46,17 +42,16 @@
if (identical(this, other)) return true;
if (other is! AnnotationData) return false;
return tag == other.tag &&
- properties.length == other.properties.length &&
- properties.keys.every((k) => properties[k] == other.properties[k]);
+ properties.length == other.properties.length &&
+ properties.keys.every((k) => properties[k] == other.properties[k]);
}
}
AnnotationDataFunction createAnnotationDataFunction(
{CssColorScheme colorScheme: const SingleColorScheme(),
- ElementScheme elementScheme: const ElementScheme()}) {
+ ElementScheme elementScheme: const ElementScheme()}) {
return (Iterable<Annotation> annotations, {bool forSpan}) {
- return getAnnotationDataFromSchemes(
- annotations,
+ return getAnnotationDataFromSchemes(annotations,
forSpan: forSpan,
colorScheme: colorScheme,
elementScheme: elementScheme);
@@ -65,11 +60,10 @@
LineData getDefaultLineData(data) => const LineData();
-AnnotationData getAnnotationDataFromSchemes(
- Iterable<Annotation> annotations,
+AnnotationData getAnnotationDataFromSchemes(Iterable<Annotation> annotations,
{bool forSpan,
- CssColorScheme colorScheme: const SingleColorScheme(),
- ElementScheme elementScheme: const ElementScheme()}) {
+ CssColorScheme colorScheme: const SingleColorScheme(),
+ ElementScheme elementScheme: const ElementScheme()}) {
if (colorScheme.showLocationAsSpan != forSpan) return null;
Map<String, String> data = <String, String>{};
var id;
@@ -97,8 +91,7 @@
data['onclick'] = elementScheme.onClick(id, ids);
data['onmouseover'] = elementScheme.onMouseOver(id, ids);
data['onmouseout'] = elementScheme.onMouseOut(id, ids);
- return new AnnotationData(
- properties: data);
+ return new AnnotationData(properties: data);
}
return null;
}
@@ -110,15 +103,15 @@
final AnnotationDataFunction getAnnotationData;
final LineDataFunction getLineData;
- HtmlPrintContext({
- this.lineNoWidth,
- this.usePre: true,
- this.includeAnnotation: includeAllAnnotation,
- this.getAnnotationData: getAnnotationDataFromSchemes,
- this.getLineData: getDefaultLineData});
+ HtmlPrintContext(
+ {this.lineNoWidth,
+ this.usePre: true,
+ this.includeAnnotation: includeAllAnnotation,
+ this.getAnnotationData: getAnnotationDataFromSchemes,
+ this.getLineData: getDefaultLineData});
- HtmlPrintContext from({
- int lineNoWidth,
+ HtmlPrintContext from(
+ {int lineNoWidth,
bool usePre,
AnnotationFilter includeAnnotation,
AnnotationDataFunction getAnnotationData,
@@ -238,10 +231,9 @@
final Map<String, String> properties;
final List<HtmlPart> content;
- TagPart(
- this.tag,
- {this.properties: const <String, String>{},
- this.content: const <HtmlPart>[]});
+ TagPart(this.tag,
+ {this.properties: const <String, String>{},
+ this.content: const <HtmlPart>[]});
HtmlPartKind get kind => HtmlPartKind.TAG;
@@ -265,12 +257,12 @@
'kind': kind.index,
'tag': tag,
'properties': properties,
- 'content': content.map((p) => p.toJson(strategy)).toList()};
+ 'content': content.map((p) => p.toJson(strategy)).toList()
+ };
}
static TagPart fromJson(Map json, JsonStrategy strategy) {
- return new TagPart(
- json['tag'],
+ return new TagPart(json['tag'],
properties: json['properties'],
content: json['content'].map(HtmlPart.fromJson).toList());
}
@@ -297,9 +289,8 @@
static HtmlLine fromJson(Map json, JsonStrategy strategy) {
HtmlLine line = new HtmlLine();
- json['html']
- .forEach((part) => line.htmlParts
- .add(HtmlPart.fromJson(part, strategy)));
+ json['html'].forEach(
+ (part) => line.htmlParts.add(HtmlPart.fromJson(part, strategy)));
return line;
}
}
@@ -329,31 +320,26 @@
}
void addForSpan(AnnotationData data) {
- htmlParts.add(new TagPart(
- data.tag,
+ htmlParts.add(new TagPart(data.tag,
properties: data.properties,
content: [new HtmlText(subsequentCode)]));
}
- if (annotationData != null &&
- annotationDataForSpan != null) {
- htmlParts.add(new TagPart(
- annotationDataForSpan.tag,
+ if (annotationData != null && annotationDataForSpan != null) {
+ htmlParts.add(new TagPart(annotationDataForSpan.tag,
properties: annotationDataForSpan.properties,
content: [
- new TagPart(
- annotationData.tag,
+ new TagPart(annotationData.tag,
properties: annotationData.properties,
content: [new HtmlText(head)]),
- new HtmlText(tail)]));
+ new HtmlText(tail)
+ ]));
} else if (annotationDataForSpan != null) {
- htmlParts.add(new TagPart(
- annotationDataForSpan.tag,
+ htmlParts.add(new TagPart(annotationDataForSpan.tag,
properties: annotationDataForSpan.properties,
content: [new HtmlText(subsequentCode)]));
} else if (annotationData != null) {
- htmlParts.add(new TagPart(
- annotationData.tag,
+ htmlParts.add(new TagPart(annotationData.tag,
properties: annotationData.properties,
content: [new HtmlText(head)]));
htmlParts.add(new HtmlText(tail));
@@ -372,7 +358,7 @@
Map toJson(JsonStrategy strategy) {
return {
'annotations':
- annotations.map((a) => strategy.encodeAnnotation(a)).toList(),
+ annotations.map((a) => strategy.encodeAnnotation(a)).toList(),
'subsequentCode': subsequentCode,
};
}
@@ -403,14 +389,12 @@
static LineNumber fromJson(Map json, JsonStrategy strategy) {
return new LineNumber(
- json['lineNo'],
- strategy.decodeLineAnnotation(json['lineAnnotation']));
+ json['lineNo'], strategy.decodeLineAnnotation(json['lineAnnotation']));
}
@override
void printHtmlOn(StringBuffer buffer, HtmlPrintContext context) {
- buffer.write(lineNumber(
- lineNo,
+ buffer.write(lineNumber(lineNo,
width: context.lineNoWidth,
useNbsp: !context.usePre,
className: context.getLineData(lineAnnotation).lineNumberClass));
@@ -462,26 +446,24 @@
'code': code,
'parts': codeParts.map((p) => p.toJson(strategy)).toList(),
'annotations':
- annotations.map((a) => strategy.encodeAnnotation(a)).toList(),
+ annotations.map((a) => strategy.encodeAnnotation(a)).toList(),
'lineAnnotation': lineAnnotation != null
- ? strategy.encodeLineAnnotation(lineAnnotation) : null,
+ ? strategy.encodeLineAnnotation(lineAnnotation)
+ : null,
};
}
static CodeLine fromJson(Map json, JsonStrategy strategy) {
- CodeLine line = new CodeLine(
- json['lineNo'],
- json['offset'],
+ CodeLine line = new CodeLine(json['lineNo'], json['offset'],
uri: json['uri'] != null ? Uri.parse(json['uri']) : null);
line.codeBuffer.write(json['code']);
- json['parts']
- .forEach((part) => line.codeParts
- .add(CodePart.fromJson(part, strategy)));
+ json['parts'].forEach(
+ (part) => line.codeParts.add(CodePart.fromJson(part, strategy)));
json['annotations']
- .forEach((a) => line.annotations
- .add(strategy.decodeAnnotation(a)));
+ .forEach((a) => line.annotations.add(strategy.decodeAnnotation(a)));
line.lineAnnotation = json['lineAnnotation'] != null
- ? strategy.decodeLineAnnotation(json['lineAnnotation']) : null;
+ ? strategy.decodeLineAnnotation(json['lineAnnotation'])
+ : null;
return line;
}
}
@@ -499,14 +481,10 @@
}
Annotation decodeAnnotation(Map json) {
- return new Annotation(
- json['id'],
- json['codeOffset'],
- json['title'],
+ return new Annotation(json['id'], json['codeOffset'], json['title'],
data: json['data']);
}
-
encodeLineAnnotation(lineAnnotation) => lineAnnotation;
decodeLineAnnotation(json) => json;
diff --git a/tests/compiler/dart2js/sourcemaps/js_tracer.dart b/tests/compiler/dart2js/sourcemaps/js_tracer.dart
index 56d6f12..6faf88e 100644
--- a/tests/compiler/dart2js/sourcemaps/js_tracer.dart
+++ b/tests/compiler/dart2js/sourcemaps/js_tracer.dart
@@ -82,43 +82,29 @@
js.Switch switchNode = node;
text = ['switch(', switchNode.key, ') ...'];
break;
-
}
- createTraceStep(
- kind,
- node,
+ createTraceStep(kind, node,
offset: offset,
- sourceLocation: getSourceLocation(
- sourceInformation, sourcePositionKind),
+ sourceLocation:
+ getSourceLocation(sourceInformation, sourcePositionKind),
text: text);
}
- void createTraceStep(
- StepKind kind,
- js.Node node,
- {Offset offset,
- List text,
- String note,
- SourceLocation sourceLocation}) {
+ void createTraceStep(StepKind kind, js.Node node,
+ {Offset offset, List text, String note, SourceLocation sourceLocation}) {
int id = steppableMap.length;
if (text == null) {
text = [node];
}
- TraceStep step = new TraceStep(
- kind,
- id,
- node,
- offset,
- text,
- sourceLocation);
+ TraceStep step =
+ new TraceStep(kind, id, node, offset, text, sourceLocation);
graph.addStep(step);
steppableMap[node] = step;
}
-
void pushBranch(BranchKind kind, [value]) {
var branch;
switch (kind) {
diff --git a/tests/compiler/dart2js/sourcemaps/output_structure.dart b/tests/compiler/dart2js/sourcemaps/output_structure.dart
index b9bb841..648973a 100644
--- a/tests/compiler/dart2js/sourcemaps/output_structure.dart
+++ b/tests/compiler/dart2js/sourcemaps/output_structure.dart
@@ -5,10 +5,7 @@
library sourcemap.output_structure;
import 'dart:math' as Math;
-import 'html_parts.dart' show
- Annotation,
- CodeLine,
- JsonStrategy;
+import 'html_parts.dart' show Annotation, CodeLine, JsonStrategy;
// Constants used to identify the subsection of the JavaScript output. These
// are specifically for the unminified full_emitter output.
@@ -43,10 +40,8 @@
CodeSource codeSource;
Interval getChildInterval(Interval childIndex) {
- return new Interval(
- children[childIndex.from].interval.from,
+ return new Interval(children[childIndex.from].interval.from,
children[childIndex.to - 1].interval.to);
-
}
OutputEntity getChild(int index) {
@@ -137,11 +132,7 @@
final int footerStart;
final List<LibraryBlock> children;
- OutputStructure(
- this.lines,
- this.headerEnd,
- this.footerStart,
- this.children);
+ OutputStructure(this.lines, this.headerEnd, this.footerStart, this.children);
@override
EntityKind get kind => EntityKind.STRUCTURE;
@@ -168,7 +159,6 @@
/// Compute the structure of the JavaScript [lines].
static OutputStructure parse(List<CodeLine> lines) {
-
int findHeaderStart(List<CodeLine> lines) {
int index = 0;
for (CodeLine line in lines) {
@@ -229,8 +219,7 @@
block.preprocess(lines);
}
- return new OutputStructure(
- lines, headerEnd, footerStart, libraryBlocks);
+ return new OutputStructure(lines, headerEnd, footerStart, libraryBlocks);
}
accept(OutputVisitor visitor, arg) => visitor.visitStructure(this, arg);
@@ -250,10 +239,9 @@
json['lines'].map((l) => CodeLine.fromJson(l, strategy)).toList();
int headerEnd = json['headerEnd'];
int footerStart = json['footerStart'];
- List<LibraryBlock> children =
- json['children']
- .map((j) => AbstractEntity.fromJson(j, strategy))
- .toList();
+ List<LibraryBlock> children = json['children']
+ .map((j) => AbstractEntity.fromJson(j, strategy))
+ .toList();
return new OutputStructure(lines, headerEnd, footerStart, children);
}
}
@@ -298,42 +286,42 @@
return lib;
case EntityKind.CLASS:
LibraryClass cls = new LibraryClass(name, from)
- ..to = to
- ..codeSource = codeSource;
+ ..to = to
+ ..codeSource = codeSource;
json['children']
.forEach((child) => cls.children.add(fromJson(child, strategy)));
return cls;
case EntityKind.TOP_LEVEL_FUNCTION:
return new TopLevelFunction(name, from)
- ..to = to
- ..codeSource = codeSource;
+ ..to = to
+ ..codeSource = codeSource;
case EntityKind.TOP_LEVEL_VALUE:
return new TopLevelValue(name, from)
- ..to = to
- ..codeSource = codeSource;
+ ..to = to
+ ..codeSource = codeSource;
case EntityKind.MEMBER_FUNCTION:
return new MemberFunction(name, from)
- ..to = to
- ..codeSource = codeSource;
+ ..to = to
+ ..codeSource = codeSource;
case EntityKind.MEMBER_OBJECT:
return new MemberObject(name, from)
- ..to = to
- ..codeSource = codeSource;
+ ..to = to
+ ..codeSource = codeSource;
case EntityKind.MEMBER_VALUE:
return new MemberValue(name, from)
- ..to = to
- ..codeSource = codeSource;
+ ..to = to
+ ..codeSource = codeSource;
case EntityKind.STATICS:
Statics statics = new Statics(from)
- ..to = to
- ..codeSource = codeSource;
+ ..to = to
+ ..codeSource = codeSource;
json['children'].forEach(
(child) => statics.children.add(fromJson(child, strategy)));
return statics;
case EntityKind.STATIC_FUNCTION:
return new StaticFunction(name, from)
- ..to = to
- ..codeSource = codeSource;
+ ..to = to
+ ..codeSource = codeSource;
}
}
}
@@ -342,7 +330,7 @@
class LibraryBlock extends AbstractEntity {
List<BasicEntity> children = <BasicEntity>[];
int get headerEnd => from + 2;
- int get footerStart => to/* - 1*/;
+ int get footerStart => to /* - 1*/;
LibraryBlock(String name, int from) : super(name, from);
@@ -675,9 +663,7 @@
static CodeLocation fromJson(Map json, JsonStrategy strategy) {
if (json == null) return null;
return new CodeLocation(
- Uri.parse(json['uri']),
- json['name'],
- json['offset']);
+ Uri.parse(json['uri']), json['name'], json['offset']);
}
}
@@ -694,8 +680,7 @@
CodeSource(this.kind, this.uri, this.name, this.begin, this.end);
int get hashCode {
- return
- kind.hashCode * 13 +
+ return kind.hashCode * 13 +
uri.hashCode * 17 +
name.hashCode * 19 +
begin.hashCode * 23;
@@ -704,12 +689,10 @@
bool operator ==(other) {
if (identical(this, other)) return true;
if (other is! CodeSource) return false;
- return
- kind == other.kind &&
+ return kind == other.kind &&
uri == other.uri &&
name == other.name &&
begin == other.begin;
-
}
String toString() => '${toJson()}';
@@ -727,13 +710,9 @@
static CodeSource fromJson(Map json) {
if (json == null) return null;
- CodeSource codeSource = new CodeSource(
- CodeKind.values[json['kind']],
- Uri.parse(json['uri']),
- json['name'],
- json['begin'],
- json['end']);
+ CodeSource codeSource = new CodeSource(CodeKind.values[json['kind']],
+ Uri.parse(json['uri']), json['name'], json['begin'], json['end']);
json['members'].forEach((m) => codeSource.members.add(fromJson(m)));
return codeSource;
}
-}
\ No newline at end of file
+}
diff --git a/tests/compiler/dart2js/sourcemaps/source_mapping_invokes_test.dart b/tests/compiler/dart2js/sourcemaps/source_mapping_invokes_test.dart
index 6ca3c0f..7120815 100644
--- a/tests/compiler/dart2js/sourcemaps/source_mapping_invokes_test.dart
+++ b/tests/compiler/dart2js/sourcemaps/source_mapping_invokes_test.dart
@@ -6,4 +6,4 @@
void main() {
test(['invokes']);
-}
\ No newline at end of file
+}
diff --git a/tests/compiler/dart2js/sourcemaps/source_mapping_operators_test.dart b/tests/compiler/dart2js/sourcemaps/source_mapping_operators_test.dart
index 34a826c..24c9284 100644
--- a/tests/compiler/dart2js/sourcemaps/source_mapping_operators_test.dart
+++ b/tests/compiler/dart2js/sourcemaps/source_mapping_operators_test.dart
@@ -14,4 +14,4 @@
return allowGtOptimization;
});
-}
\ No newline at end of file
+}
diff --git a/tests/compiler/dart2js/sourcemaps/source_mapping_test_viewer.dart b/tests/compiler/dart2js/sourcemaps/source_mapping_test_viewer.dart
index 215092a..0fee7e2 100644
--- a/tests/compiler/dart2js/sourcemaps/source_mapping_test_viewer.dart
+++ b/tests/compiler/dart2js/sourcemaps/source_mapping_test_viewer.dart
@@ -30,7 +30,6 @@
} else if (argument.startsWith('--out=')) {
/// Generate visualization for the first configuration.
outputPath = argument.substring('--out='.length);
-
} else if (argument.startsWith('-o')) {
/// Generate visualization for the first configuration.
outputPath = argument.substring('-o'.length);
@@ -69,11 +68,8 @@
}
generateMultiConfigs = true;
} else {
- outputConfigurations.registerPathUri(
- configurations.first,
- files.first,
- outputPath,
- Uri.base.resolve(nativeToUriPath(outputPath)));
+ outputConfigurations.registerPathUri(configurations.first, files.first,
+ outputPath, Uri.base.resolve(nativeToUriPath(outputPath)));
}
}
@@ -81,8 +77,7 @@
for (String config in configurations) {
List<String> options = TEST_CONFIGURATIONS[config];
for (String file in files) {
- Measurement measurement = await runTest(
- config, TEST_FILES[file], options,
+ Measurement measurement = await runTest(config, TEST_FILES[file], options,
outputUri: outputConfigurations.getUri(config, file),
verbose: !measure);
measurements.add(measurement);
@@ -92,9 +87,7 @@
print(measurement);
}
if (generateMultiConfigs) {
- outputMultiConfigs(
- Uri.base.resolve(outputPath),
- outputConfigurations);
+ outputMultiConfigs(Uri.base.resolve(outputPath), outputConfigurations);
}
}
@@ -125,11 +118,8 @@
}
Future<Measurement> runTest(
- String config,
- String filename,
- List<String> options,
- {Uri outputUri,
- bool verbose}) async {
+ String config, String filename, List<String> options,
+ {Uri outputUri, bool verbose}) async {
TestResult result =
await runTests(config, filename, options, verbose: verbose);
if (outputUri != null) {
@@ -144,7 +134,9 @@
}
createTraceSourceMapHtml(outputUri, result.processor, result.userInfoList);
}
- return new Measurement(config, filename,
+ return new Measurement(
+ config,
+ filename,
result.missingCodePointsMap.values.fold(0, (s, i) => s + i.length),
result.userInfoList.fold(0, (s, i) => s + i.codePoints.length));
}
@@ -161,6 +153,6 @@
String toString() {
double percentage = 100 * missing / count;
return "Config '${config}', file: '${filename}': "
- "$missing of $count ($percentage%) missing";
+ "$missing of $count ($percentage%) missing";
}
}
diff --git a/tests/compiler/dart2js/sourcemaps/source_mapping_tester.dart b/tests/compiler/dart2js/sourcemaps/source_mapping_tester.dart
index 713814a..a1561af 100644
--- a/tests/compiler/dart2js/sourcemaps/source_mapping_tester.dart
+++ b/tests/compiler/dart2js/sourcemaps/source_mapping_tester.dart
@@ -26,7 +26,7 @@
}
void test(List<String> arguments,
- {WhiteListFunction whiteListFunction: emptyWhiteListFunction}) {
+ {WhiteListFunction whiteListFunction: emptyWhiteListFunction}) {
Set<String> configurations = new Set<String>();
Set<String> files = new Set<String>();
for (String argument in arguments) {
@@ -49,11 +49,10 @@
List<String> options = TEST_CONFIGURATIONS[config];
for (String file in files) {
String filename = TEST_FILES[file];
- TestResult result = await runTests(
- config, filename, options);
+ TestResult result = await runTests(config, filename, options);
if (result.missingCodePointsMap.isNotEmpty) {
- errorsFound = result.printMissingCodePoints(
- whiteListFunction(config, file));
+ errorsFound =
+ result.printMissingCodePoints(whiteListFunction(config, file));
true;
}
if (result.multipleNodesMap.isNotEmpty) {
@@ -66,7 +65,8 @@
}
}
}
- Expect.isFalse(errorsFound,
+ Expect.isFalse(
+ errorsFound,
"Errors found. "
"Run the test with a URI option, "
"`source_mapping_test_viewer [--out=<uri>] [configs] [tests]`, to "
@@ -80,24 +80,25 @@
/// test-file name is added to [files], and `true` is returned.
/// On failure, a message is printed and `false` is returned.
///
-bool parseArgument(String argument,
- Set<String> configurations,
- Set<String> files) {
+bool parseArgument(
+ String argument, Set<String> configurations, Set<String> files) {
if (TEST_CONFIGURATIONS.containsKey(argument)) {
configurations.add(argument);
} else if (TEST_FILES.containsKey(argument)) {
files.add(argument);
} else {
print("Unknown configuration or file '$argument'. "
- "Must be one of '${TEST_CONFIGURATIONS.keys.join("', '")}' or "
- "'${TEST_FILES.keys.join("', '")}'.");
+ "Must be one of '${TEST_CONFIGURATIONS.keys.join("', '")}' or "
+ "'${TEST_FILES.keys.join("', '")}'.");
return false;
}
return true;
}
const Map<String, List<String>> TEST_CONFIGURATIONS = const {
- 'ssa': const ['--use-new-source-info', ],
+ 'ssa': const [
+ '--use-new-source-info',
+ ],
'old': const [],
};
@@ -107,14 +108,11 @@
};
Future<TestResult> runTests(
- String config,
- String filename,
- List<String> options,
+ String config, String filename, List<String> options,
{bool verbose: true}) async {
SourceMapProcessor processor = new SourceMapProcessor(filename);
SourceMaps sourceMaps = await processor.process(
- ['--csp', '--disable-inlining']
- ..addAll(options),
+ ['--csp', '--disable-inlining']..addAll(options),
verbose: verbose);
TestResult result = new TestResult(config, filename, processor);
for (SourceMapInfo info in sourceMaps.elementSourceMapInfos.values) {
@@ -128,12 +126,11 @@
Map<int, Set<SourceLocation>> offsetToLocationsMap =
<int, Set<SourceLocation>>{};
for (Node node in info.nodeMap.nodes) {
- info.nodeMap[node].forEach(
- (int targetOffset, List<SourceLocation> sourceLocations) {
+ info.nodeMap[node]
+ .forEach((int targetOffset, List<SourceLocation> sourceLocations) {
if (sourceLocations.length > 1) {
- Map<Node, List<SourceLocation>> multipleMap =
- result.multipleNodesMap.putIfAbsent(info,
- () => <Node, List<SourceLocation>>{});
+ Map<Node, List<SourceLocation>> multipleMap = result.multipleNodesMap
+ .putIfAbsent(info, () => <Node, List<SourceLocation>>{});
multipleMap[node] = sourceLocations;
} else {
offsetToLocationsMap
@@ -142,12 +139,11 @@
}
});
}
- offsetToLocationsMap.forEach(
- (int targetOffset, Set<SourceLocation> sourceLocations) {
+ offsetToLocationsMap
+ .forEach((int targetOffset, Set<SourceLocation> sourceLocations) {
if (sourceLocations.length > 1) {
- Map<int, Set<SourceLocation>> multipleMap =
- result.multipleOffsetsMap.putIfAbsent(info,
- () => <int, Set<SourceLocation>>{});
+ Map<int, Set<SourceLocation>> multipleMap = result.multipleOffsetsMap
+ .putIfAbsent(info, () => <int, Set<SourceLocation>>{});
multipleMap[targetOffset] = sourceLocations;
}
});
@@ -180,7 +176,7 @@
bool allWhiteListed = true;
missingCodePointsMap.forEach((info, missingCodePoints) {
print("Missing code points for ${info.element} in '$file' "
- "in config '$config':");
+ "in config '$config':");
for (CodePoint codePoint in missingCodePoints) {
if (codePointWhiteList(codePoint)) {
print(" $codePoint (white-listed)");
@@ -197,8 +193,8 @@
multipleNodesMap.forEach((info, multipleMap) {
multipleMap.forEach((node, sourceLocations) {
print('Multiple source locations:\n ${sourceLocations.join('\n ')}\n'
- 'for `${nodeToString(node)}` in ${info.element} in '
- '$file.');
+ 'for `${nodeToString(node)}` in ${info.element} in '
+ '$file.');
});
});
}
@@ -206,8 +202,7 @@
void printMultipleOffsets() {
multipleOffsetsMap.forEach((info, multipleMap) {
multipleMap.forEach((targetOffset, sourceLocations) {
- print(
- 'Multiple source locations:\n ${sourceLocations.join('\n ')}\n'
+ print('Multiple source locations:\n ${sourceLocations.join('\n ')}\n'
'for offset $targetOffset in ${info.element} in $file.');
});
});
diff --git a/tests/compiler/dart2js/sourcemaps/sourcemap_helper.dart b/tests/compiler/dart2js/sourcemaps/sourcemap_helper.dart
index 3a5befd..fa8ea09 100644
--- a/tests/compiler/dart2js/sourcemaps/sourcemap_helper.dart
+++ b/tests/compiler/dart2js/sourcemaps/sourcemap_helper.dart
@@ -77,7 +77,7 @@
RandomAccessFileOutputProvider outputProvider;
CloningOutputProvider(Uri jsUri, Uri jsMapUri)
- : outputProvider = new RandomAccessFileOutputProvider(jsUri, jsMapUri);
+ : outputProvider = new RandomAccessFileOutputProvider(jsUri, jsMapUri);
@override
EventSink<String> createEventSink(String name, String extension) {
@@ -114,14 +114,11 @@
RecordingPrintingContext(this.listener);
@override
- void exitNode(js.Node node,
- int startPosition,
- int endPosition,
- int closingPosition) {
+ void exitNode(
+ js.Node node, int startPosition, int endPosition, int closingPosition) {
codePositions[node] =
new CodePosition(startPosition, endPosition, closingPosition);
- listener.onPositions(
- node, startPosition, endPosition, closingPosition);
+ listener.onPositions(node, startPosition, endPosition, closingPosition);
}
}
@@ -148,17 +145,12 @@
final CodePositionRecorder codePositions;
final LocationMap nodeToSourceLocationsMap;
- RecordingSourceInformationProcessor(
- this.wrapper,
- this.processor,
- this.codePositions,
- this.nodeToSourceLocationsMap);
+ RecordingSourceInformationProcessor(this.wrapper, this.processor,
+ this.codePositions, this.nodeToSourceLocationsMap);
@override
- void onPositions(js.Node node,
- int startPosition,
- int endPosition,
- int closingPosition) {
+ void onPositions(
+ js.Node node, int startPosition, int endPosition, int closingPosition) {
codePositions.registerPositions(
node, startPosition, endPosition, closingPosition);
processor.onPositions(node, startPosition, endPosition, closingPosition);
@@ -180,13 +172,9 @@
final LocationMap nodeToSourceLocationsMap;
RecordedSourceInformationProcess(
- this.root,
- this.code,
- this.codePositions,
- this.nodeToSourceLocationsMap);
+ this.root, this.code, this.codePositions, this.nodeToSourceLocationsMap);
}
-
/// A wrapper of [JavaScriptSourceInformationStrategy] that records
/// [RecordedSourceInformationProcess].
class RecordingSourceInformationStrategy
@@ -206,20 +194,21 @@
@override
SourceInformationProcessor createProcessor(SourceMapper sourceMapper) {
- LocationMap nodeToSourceLocationsMap =
- new _LocationRecorder();
+ LocationMap nodeToSourceLocationsMap = new _LocationRecorder();
CodePositionRecorder codePositions = new CodePositionRecorder();
return new RecordingSourceInformationProcessor(
this,
- strategy.createProcessor(new RecordingSourceMapper(
- sourceMapper, nodeToSourceLocationsMap)),
- codePositions, nodeToSourceLocationsMap);
+ strategy.createProcessor(
+ new RecordingSourceMapper(sourceMapper, nodeToSourceLocationsMap)),
+ codePositions,
+ nodeToSourceLocationsMap);
}
- void registerProcess(js.Node root,
- BufferedCodeOutput code,
- CodePositionRecorder codePositions,
- LocationMap nodeToSourceLocationsMap) {
+ void registerProcess(
+ js.Node root,
+ BufferedCodeOutput code,
+ CodePositionRecorder codePositions,
+ LocationMap nodeToSourceLocationsMap) {
RecordedSourceInformationProcess subProcess =
new RecordedSourceInformationProcess(
root, code.getText(), codePositions, nodeToSourceLocationsMap);
@@ -302,11 +291,8 @@
}
/// Computes the [SourceMapInfo] for the compiled elements.
- Future<SourceMaps> process(
- List<String> options,
- {bool verbose: true,
- bool perElement: true,
- bool forMain: false}) async {
+ Future<SourceMaps> process(List<String> options,
+ {bool verbose: true, bool perElement: true, bool forMain: false}) async {
OutputProvider outputProvider = outputToFile
? new CloningOutputProvider(targetUri, sourceMapFileUri)
: new OutputProvider();
@@ -320,16 +306,16 @@
outputProvider: outputProvider,
// TODO(johnniwinther): Use [verbose] to avoid showing diagnostics.
options: ['--out=$targetUri', '--source-map=$sourceMapFileUri']
- ..addAll(options));
+ ..addAll(options));
JavaScriptBackend backend = compiler.backend;
var handler = compiler.handler;
SourceFileProvider sourceFileProvider = handler.provider;
- sourceFileManager = new ProviderSourceFileManager(
- sourceFileProvider,
- outputProvider);
+ sourceFileManager =
+ new ProviderSourceFileManager(sourceFileProvider, outputProvider);
RecordingSourceInformationStrategy strategy =
- new RecordingSourceInformationStrategy(backend.sourceInformationStrategy);
+ new RecordingSourceInformationStrategy(
+ backend.sourceInformationStrategy);
backend.sourceInformationStrategy = strategy;
await compiler.run(inputUri);
@@ -354,12 +340,7 @@
new JavaScriptTracer(codePositions, [visitor]).apply(node);
List<CodePoint> codePoints = visitor.codePoints;
elementSourceMapInfos[element] = new SourceMapInfo(
- element,
- code,
- node,
- codePoints,
- codePositions,
- nodeMap);
+ element, code, node, codePoints, codePositions, nodeMap);
});
}
if (forMain) {
@@ -377,17 +358,11 @@
new JavaScriptTracer(codePositions, [visitor]).apply(node);
List<CodePoint> codePoints = visitor.codePoints;
mainSourceMapInfo = new SourceMapInfo(
- null, code, node,
- codePoints,
- codePositions,
- nodeMap);
+ null, code, node, codePoints, codePositions, nodeMap);
}
return new SourceMaps(
- compiler,
- sourceFileManager,
- mainSourceMapInfo,
- elementSourceMapInfos);
+ compiler, sourceFileManager, mainSourceMapInfo, elementSourceMapInfos);
}
}
@@ -398,11 +373,8 @@
final SourceMapInfo mainSourceMapInfo;
final Map<Element, SourceMapInfo> elementSourceMapInfos;
- SourceMaps(
- this.compiler,
- this.sourceFileManager,
- this.mainSourceMapInfo,
- this.elementSourceMapInfos);
+ SourceMaps(this.compiler, this.sourceFileManager, this.mainSourceMapInfo,
+ this.elementSourceMapInfos);
}
/// Source mapping information for the JavaScript code of an [Element].
@@ -415,15 +387,10 @@
final CodePositionMap jsCodePositions;
final LocationMap nodeMap;
- SourceMapInfo(
- Element element,
- this.code,
- this.node,
- this.codePoints,
- this.jsCodePositions,
- this.nodeMap)
+ SourceMapInfo(Element element, this.code, this.node, this.codePoints,
+ this.jsCodePositions, this.nodeMap)
: this.name =
- element != null ? computeElementNameForSourceMaps(element) : '',
+ element != null ? computeElementNameForSourceMaps(element) : '',
this.element = element;
String toString() {
@@ -436,29 +403,28 @@
abstract class LocationMap {
Iterable<js.Node> get nodes;
- Map<int, List<SourceLocation>> operator[] (js.Node node);
+ Map<int, List<SourceLocation>> operator [](js.Node node);
factory LocationMap.recorder() = _LocationRecorder;
factory LocationMap.filter(Set<js.Node> nodes, LocationMap map) =
_FilteredLocationMap;
-
}
-class _LocationRecorder
- implements SourceMapper, LocationMap {
+class _LocationRecorder implements SourceMapper, LocationMap {
final Map<js.Node, Map<int, List<SourceLocation>>> _nodeMap = {};
@override
void register(js.Node node, int codeOffset, SourceLocation sourceLocation) {
- _nodeMap.putIfAbsent(node, () => {})
+ _nodeMap
+ .putIfAbsent(node, () => {})
.putIfAbsent(codeOffset, () => [])
.add(sourceLocation);
}
Iterable<js.Node> get nodes => _nodeMap.keys;
- Map<int, List<SourceLocation>> operator[] (js.Node node) {
+ Map<int, List<SourceLocation>> operator [](js.Node node) {
return _nodeMap[node];
}
}
@@ -471,12 +437,11 @@
Iterable<js.Node> get nodes => map.nodes.where((n) => _nodes.contains(n));
- Map<int, List<SourceLocation>> operator[] (js.Node node) {
+ Map<int, List<SourceLocation>> operator [](js.Node node) {
return map[node];
}
}
-
/// Visitor that computes the [CodePoint]s for source mapping locations.
class CodePointComputer extends TraceListener {
final SourceFileManager sourceFileManager;
@@ -511,15 +476,16 @@
}
void register(StepKind kind, js.Node node, {bool expectInfo: true}) {
-
String dartCodeFromSourceLocation(SourceLocation sourceLocation) {
SourceFile sourceFile =
- sourceFileManager.getSourceFile(sourceLocation.sourceUri);
+ sourceFileManager.getSourceFile(sourceLocation.sourceUri);
if (sourceFile == null) {
return sourceLocation.shortText;
}
- return sourceFile.getLineText(sourceLocation.line)
- .substring(sourceLocation.column).trim();
+ return sourceFile
+ .getLineText(sourceLocation.line)
+ .substring(sourceLocation.column)
+ .trim();
}
void addLocation(SourceLocation sourceLocation, String jsCode) {
@@ -532,12 +498,12 @@
sourceLocation = sourceInformation.sourceLocations.first;
dartCode = dartCodeFromSourceLocation(sourceLocation);
}
- codePoints.add(new CodePoint(
- kind, jsCode, sourceLocation, dartCode, isMissing: true));
+ codePoints.add(new CodePoint(kind, jsCode, sourceLocation, dartCode,
+ isMissing: true));
}
} else {
- codePoints.add(new CodePoint(kind, jsCode, sourceLocation,
- dartCodeFromSourceLocation(sourceLocation)));
+ codePoints.add(new CodePoint(kind, jsCode, sourceLocation,
+ dartCodeFromSourceLocation(sourceLocation)));
}
}
@@ -563,16 +529,12 @@
final String dartCode;
final bool isMissing;
- CodePoint(
- this.kind,
- this.jsCode,
- this.sourceLocation,
- this.dartCode,
+ CodePoint(this.kind, this.jsCode, this.sourceLocation, this.dartCode,
{this.isMissing: false});
String toString() {
return 'CodePoint[kind=$kind,js=$jsCode,dart=$dartCode,'
- 'location=$sourceLocation]';
+ 'location=$sourceLocation]';
}
}
diff --git a/tests/compiler/dart2js/sourcemaps/sourcemap_html_helper.dart b/tests/compiler/dart2js/sourcemaps/sourcemap_html_helper.dart
index a3b10a8..ddb6fdc 100644
--- a/tests/compiler/dart2js/sourcemaps/sourcemap_html_helper.dart
+++ b/tests/compiler/dart2js/sourcemaps/sourcemap_html_helper.dart
@@ -54,9 +54,7 @@
/// Return the html for the [index] line number. If [width] is provided, shorter
/// line numbers will be prefixed with spaces to match the width.
String lineNumber(int index,
- {int width,
- bool useNbsp: false,
- String className}) {
+ {int width, bool useNbsp: false, String className}) {
if (className == null) {
className = 'lineNumber';
}
@@ -79,9 +77,8 @@
final CodeProcessor codeProcessor;
final SourceLocationCollection sourceLocationCollection;
- SourceMapHtmlInfo(this.sourceMapInfo,
- this.codeProcessor,
- this.sourceLocationCollection);
+ SourceMapHtmlInfo(
+ this.sourceMapInfo, this.codeProcessor, this.sourceLocationCollection);
String toString() {
return sourceMapInfo.toString();
@@ -126,8 +123,8 @@
CustomColorScheme(
{this.showLocationAsSpan: false,
- String this.single(var id),
- String this.multi(List ids)});
+ String this.single(var id),
+ String this.multi(List ids)});
String singleLocationToCssColor(var id) => single != null ? single(id) : null;
@@ -144,7 +141,6 @@
}
String multiLocationToCssColor(List<int> indices) {
-
StringBuffer sb = new StringBuffer();
double delta = 100.0 / (indices.length);
double position = 0.0;
@@ -159,7 +155,7 @@
addColor('${toColorCss(index)}');
}
return 'background: linear-gradient(to right${sb}); '
- 'background-size: 10px 10px;';
+ 'background-size: 10px 10px;';
}
}
@@ -187,7 +183,7 @@
addColor('${toColorCss(index)}');
}
return 'background: linear-gradient(to bottom${sb}); '
- 'background-size: 10px 3px;';
+ 'background-size: 10px 3px;';
}
}
@@ -215,14 +211,12 @@
for (SourceLocation location in locations) {
if (location != null) {
annotations.add(new Annotation(
- collection.getIndex(location),
- codeOffset,
- location.shortText));
+ collection.getIndex(location), codeOffset, location.shortText));
}
}
});
- return convertAnnotatedCodeToHtml(
- text, annotations, colorScheme: colorScheme,
+ return convertAnnotatedCodeToHtml(text, annotations,
+ colorScheme: colorScheme,
elementScheme: new HighlightLinkScheme(name),
windowSize: 3);
}
@@ -270,15 +264,12 @@
}
}
-String convertAnnotatedCodeToHtml(
- String code,
- Iterable<Annotation> annotations,
+String convertAnnotatedCodeToHtml(String code, Iterable<Annotation> annotations,
{CssColorScheme colorScheme: const SingleColorScheme(),
- ElementScheme elementScheme: const ElementScheme(),
- int windowSize}) {
+ ElementScheme elementScheme: const ElementScheme(),
+ int windowSize}) {
StringBuffer htmlBuffer = new StringBuffer();
- List<CodeLine> lines = convertAnnotatedCodeToCodeLines(
- code, annotations,
+ List<CodeLine> lines = convertAnnotatedCodeToCodeLines(code, annotations,
windowSize: windowSize);
int lineNoWidth;
if (lines.isNotEmpty) {
@@ -287,8 +278,7 @@
HtmlPrintContext context = new HtmlPrintContext(
lineNoWidth: lineNoWidth,
getAnnotationData: createAnnotationDataFunction(
- colorScheme: colorScheme,
- elementScheme: elementScheme));
+ colorScheme: colorScheme, elementScheme: elementScheme));
for (CodeLine line in lines) {
line.printHtmlOn(htmlBuffer, context);
}
@@ -296,13 +286,8 @@
}
List<CodeLine> convertAnnotatedCodeToCodeLines(
- String code,
- Iterable<Annotation> annotations,
- {int startLine,
- int endLine,
- int windowSize,
- Uri uri}) {
-
+ String code, Iterable<Annotation> annotations,
+ {int startLine, int endLine, int windowSize, Uri uri}) {
List<CodeLine> lines = <CodeLine>[];
CodeLine currentLine;
final List<Annotation> currentAnnotations = <Annotation>[];
@@ -314,8 +299,8 @@
void addCode(String code) {
if (currentLine != null) {
currentLine.codeBuffer.write(code);
- currentLine.codeParts.add(
- new CodePart(currentAnnotations.toList(), code));
+ currentLine.codeParts
+ .add(new CodePart(currentAnnotations.toList(), code));
currentAnnotations.clear();
}
}
@@ -326,8 +311,8 @@
}
void beginLine(int currentOffset) {
- lines.add(currentLine =
- new CodeLine(lines.length, currentOffset, uri: uri));
+ lines
+ .add(currentLine = new CodeLine(lines.length, currentOffset, uri: uri));
}
void endCurrentLocation() {
@@ -376,8 +361,9 @@
Map<int, List<Annotation>> annotationMap = <int, List<Annotation>>{};
for (Annotation annotation in annotations) {
- annotationMap.putIfAbsent(annotation.codeOffset, () => <Annotation>[])
- .add(annotation);
+ annotationMap
+ .putIfAbsent(annotation.codeOffset, () => <Annotation>[])
+ .add(annotation);
}
bool first = true;
@@ -402,14 +388,13 @@
/// Computes the HTML representation for a collection of JavaScript code blocks.
String computeJsHtml(Iterable<SourceMapHtmlInfo> infoList) {
-
StringBuffer jsCodeBuffer = new StringBuffer();
for (SourceMapHtmlInfo info in infoList) {
String name = info.sourceMapInfo.name;
String html = info.codeProcessor.convertToHtml(info.sourceMapInfo.code);
String onclick = 'show(\'$name\');';
- jsCodeBuffer.write(
- '<h3 onclick="$onclick">JS code for: ${escape(name)}</h3>\n');
+ jsCodeBuffer
+ .write('<h3 onclick="$onclick">JS code for: ${escape(name)}</h3>\n');
jsCodeBuffer.write('''
<pre>
$html
@@ -438,8 +423,8 @@
}
/// Computes the HTML information for the [info].
-SourceMapHtmlInfo createHtmlInfo(SourceLocationCollection collection,
- SourceMapInfo info) {
+SourceMapHtmlInfo createHtmlInfo(
+ SourceLocationCollection collection, SourceMapInfo info) {
js.Node node = info.node;
String code = info.code;
String name = info.name;
@@ -447,8 +432,8 @@
new SourceLocationCollection(collection);
CodeProcessor codeProcessor = new CodeProcessor(name, subcollection);
for (js.Node node in info.nodeMap.nodes) {
- info.nodeMap[node].forEach(
- (int targetOffset, List<SourceLocation> sourceLocations) {
+ info.nodeMap[node]
+ .forEach((int targetOffset, List<SourceLocation> sourceLocations) {
for (SourceLocation sourceLocation in sourceLocations) {
codeProcessor.addSourceLocation(targetOffset, sourceLocation);
}
@@ -461,8 +446,7 @@
/// visualization of the source mapping information in [infoList] computed
/// with the [sourceMapProcessor].
void createTraceSourceMapHtml(Uri jsMapHtmlUri,
- SourceMapProcessor sourceMapProcessor,
- Iterable<SourceMapInfo> infoList) {
+ SourceMapProcessor sourceMapProcessor, Iterable<SourceMapInfo> infoList) {
SourceFileManager sourceFileManager = sourceMapProcessor.sourceFileManager;
SourceLocationCollection collection = new SourceLocationCollection();
List<SourceMapHtmlInfo> htmlInfoList = <SourceMapHtmlInfo>[];
@@ -481,23 +465,19 @@
/// Computes the HTML representation for the Dart code snippets referenced in
/// [infoList].
String computeDartHtml(
- SourceFileManager sourceFileManager,
- Iterable<SourceMapHtmlInfo> infoList) {
-
+ SourceFileManager sourceFileManager, Iterable<SourceMapHtmlInfo> infoList) {
StringBuffer dartCodeBuffer = new StringBuffer();
for (SourceMapHtmlInfo info in infoList) {
dartCodeBuffer.write(computeDartHtmlPart(info.sourceMapInfo.name,
- sourceFileManager, info.sourceLocationCollection));
+ sourceFileManager, info.sourceLocationCollection));
}
return dartCodeBuffer.toString();
-
}
/// Computes the HTML representation for the Dart code snippets in [collection].
-String computeDartHtmlPart(String name,
- SourceFileManager sourceFileManager,
- SourceLocationCollection collection,
- {bool showAsBlock: false}) {
+String computeDartHtmlPart(String name, SourceFileManager sourceFileManager,
+ SourceLocationCollection collection,
+ {bool showAsBlock: false}) {
const int windowSize = 3;
StringBuffer dartCodeBuffer = new StringBuffer();
Map<Uri, Map<int, List<SourceLocation>>> sourceLocationMap = {};
@@ -523,15 +503,14 @@
void flush() {
if (firstLineIndex != null && lastLineIndex != null) {
- dartCodeBuffer.write(
- '<h4>${uri.pathSegments.last}, '
+ dartCodeBuffer.write('<h4>${uri.pathSegments.last}, '
'${firstLineIndex - windowSize + 1}-'
'${lastLineIndex + windowSize + 1}'
'</h4>\n');
dartCodeBuffer.write('<pre>\n');
for (int line = firstLineIndex - windowSize;
- line < firstLineIndex;
- line++) {
+ line < firstLineIndex;
+ line++) {
if (line >= 0) {
dartCodeBuffer.write(lineNumber(line, width: lineNoWidth));
dartCodeBuffer.write(sourceFile.getLineText(line));
@@ -539,8 +518,8 @@
}
dartCodeBuffer.write(codeBuffer);
for (int line = lastLineIndex + 1;
- line <= lastLineIndex + windowSize;
- line++) {
+ line <= lastLineIndex + windowSize;
+ line++) {
if (line < sourceFile.lines) {
dartCodeBuffer.write(lineNumber(line, width: lineNoWidth));
dartCodeBuffer.write(sourceFile.getLineText(line));
@@ -555,8 +534,7 @@
lineIndices.forEach((int lineIndex) {
List<SourceLocation> locations = uriMap[lineIndex];
- if (lastLineIndex != null &&
- lastLineIndex + windowSize * 4 < lineIndex) {
+ if (lastLineIndex != null && lastLineIndex + windowSize * 4 < lineIndex) {
flush();
}
if (firstLineIndex == null) {
@@ -581,11 +559,11 @@
codeBuffer.write(lineNumber(lineIndex, width: lineNoWidth));
codeBuffer.write(line.substring(0, start));
}
- codeBuffer.write(
- '<a name="${index}" style="background:${toPattern(index)};" '
- 'title="[${lineIndex + 1},${start + 1}]" '
- 'onmouseover="highlight(\'$index\');" '
- 'onmouseout="highlight();">');
+ codeBuffer
+ .write('<a name="${index}" style="background:${toPattern(index)};" '
+ 'title="[${lineIndex + 1},${start + 1}]" '
+ 'onmouseover="highlight(\'$index\');" '
+ 'onmouseout="highlight();">');
codeBuffer.write(line.substring(start, end));
codeBuffer.write('</a>');
}
@@ -603,12 +581,11 @@
}
/// Computes a HTML visualization of the [codePoints].
-String computeJsTraceHtmlPart(List<CodePoint> codePoints,
- SourceLocationCollection collection) {
+String computeJsTraceHtmlPart(
+ List<CodePoint> codePoints, SourceLocationCollection collection) {
StringBuffer buffer = new StringBuffer();
buffer.write('<table style="width:100%;">');
- buffer.write(
- '<tr><th>Node kind</th><th>JS code @ offset</th>'
+ buffer.write('<tr><th>Node kind</th><th>JS code @ offset</th>'
'<th>Dart code @ mapped location</th><th>file:position:name</th></tr>');
codePoints.forEach((CodePoint codePoint) {
String jsCode = truncate(codePoint.jsCode, 50);
@@ -620,9 +597,9 @@
style = 'style="background:${toColorCss(index)};" ';
}
buffer.write('<tr $style'
- 'name="trace$index" '
- 'onmouseover="highlight([${index}]);"'
- 'onmouseout="highlight([]);">');
+ 'name="trace$index" '
+ 'onmouseover="highlight([${index}]);"'
+ 'onmouseout="highlight([]);">');
} else {
buffer.write('<tr>');
print('${codePoint.sourceLocation} not found in ');
diff --git a/tests/compiler/dart2js/sourcemaps/sourcemap_html_templates.dart b/tests/compiler/dart2js/sourcemaps/sourcemap_html_templates.dart
index 6d0bcb2..892b758 100644
--- a/tests/compiler/dart2js/sourcemaps/sourcemap_html_templates.dart
+++ b/tests/compiler/dart2js/sourcemaps/sourcemap_html_templates.dart
@@ -14,8 +14,7 @@
String getPath(String config, String file);
}
-void outputMultiConfigs(Uri uri,
- Configurations configurations) {
+void outputMultiConfigs(Uri uri, Configurations configurations) {
StringBuffer sb = new StringBuffer();
String defaultConfig = configurations.configs.first;
String defaultFile = configurations.files.first;
@@ -116,10 +115,7 @@
/// Outputs JavaScript/Dart source mapping traces into [uri].
void outputJsDartTrace(
- Uri uri,
- String jsCodeHtml,
- String dartCodeHtml,
- String jsTraceHtml) {
+ Uri uri, String jsCodeHtml, String dartCodeHtml, String jsTraceHtml) {
String html = '''
<div class="js-buffer">
${jsCodeHtml}
@@ -151,10 +147,10 @@
}
/// Outputs [html] with customized [css] in [uri].
-void outputInTemplate(Uri uri,
- String html,
- String css) {
- output(uri, '''
+void outputInTemplate(Uri uri, String html, String css) {
+ output(
+ uri,
+ '''
<html>
<head>
<style>
@@ -243,8 +239,7 @@
}
/// Outputs [html] in [uri].
-void output(Uri uri,
- String html) {
+void output(Uri uri, String html) {
File outputFile = new File.fromUri(uri);
outputFile.writeAsStringSync(html);
}
diff --git a/tests/compiler/dart2js/sourcemaps/trace_graph.dart b/tests/compiler/dart2js/sourcemaps/trace_graph.dart
index 75eec94..0db1e18 100644
--- a/tests/compiler/dart2js/sourcemaps/trace_graph.dart
+++ b/tests/compiler/dart2js/sourcemaps/trace_graph.dart
@@ -59,14 +59,8 @@
List stack;
- TraceStep(
- this.kind,
- this.id,
- this.node,
- this.offset,
- this.text,
+ TraceStep(this.kind, this.id, this.node, this.offset, this.text,
[this.sourceLocation]);
String toString() => '<span style="background:${toColorCss(id)}">$id</span>';
}
-
diff --git a/tests/compiler/dart2js/space_test.dart b/tests/compiler/dart2js/space_test.dart
index b721952..9146f27 100644
--- a/tests/compiler/dart2js/space_test.dart
+++ b/tests/compiler/dart2js/space_test.dart
@@ -3,8 +3,7 @@
// BSD-style license that can be found in the LICENSE file.
import 'dart:io';
-import 'package:compiler/src/dart2js.dart'
- as dart2js;
+import 'package:compiler/src/dart2js.dart' as dart2js;
import 'package:compiler/src/commandline_options.dart';
main() {
@@ -13,7 +12,9 @@
Uri libraryRoot = script.resolve('../../../sdk/');
Directory.current = script.resolve("path with spaces").toFilePath();
- return dart2js.main(["--library-root=${libraryRoot.toFilePath()}",
- Flags.analyzeOnly,
- "file with spaces.dart"]);
+ return dart2js.main([
+ "--library-root=${libraryRoot.toFilePath()}",
+ Flags.analyzeOnly,
+ "file with spaces.dart"
+ ]);
}
diff --git a/tests/compiler/dart2js/ssa_phi_codegen_test.dart b/tests/compiler/dart2js/ssa_phi_codegen_test.dart
index 2189e49..57ee1b0 100644
--- a/tests/compiler/dart2js/ssa_phi_codegen_test.dart
+++ b/tests/compiler/dart2js/ssa_phi_codegen_test.dart
@@ -71,21 +71,21 @@
main() {
asyncTest(() => Future.wait([
- compileAndMatchFuzzy(TEST_ONE, 'foo', "var x = x === true \\? 2 : 3;"),
- compileAndMatchFuzzy(TEST_ONE, 'foo', "print\\(x\\);"),
+ compileAndMatchFuzzy(TEST_ONE, 'foo', "var x = x === true \\? 2 : 3;"),
+ compileAndMatchFuzzy(TEST_ONE, 'foo', "print\\(x\\);"),
- compileAndMatchFuzzy(TEST_TWO, 'main', "x \\+= 10"),
- compileAndMatchFuzzy(TEST_TWO, 'main', "\\+\\+x"),
+ compileAndMatchFuzzy(TEST_TWO, 'main', "x \\+= 10"),
+ compileAndMatchFuzzy(TEST_TWO, 'main', "\\+\\+x"),
- // Check that we don't have 'd = d' (using regexp back references).
- compileAndDoNotMatchFuzzy(TEST_THREE, 'foo', '(x) = \1'),
- compileAndMatchFuzzy(TEST_THREE, 'foo', 'return x'),
- // Check that a store just after the declaration of the local
- // only generates one instruction.
- compileAndMatchFuzzy(TEST_THREE, 'foo', 'x = 42'),
+ // Check that we don't have 'd = d' (using regexp back references).
+ compileAndDoNotMatchFuzzy(TEST_THREE, 'foo', '(x) = \1'),
+ compileAndMatchFuzzy(TEST_THREE, 'foo', 'return x'),
+ // Check that a store just after the declaration of the local
+ // only generates one instruction.
+ compileAndMatchFuzzy(TEST_THREE, 'foo', 'x = 42'),
- compileAndDoNotMatchFuzzy(TEST_FOUR, 'foo', '(x) = \1;'),
+ compileAndDoNotMatchFuzzy(TEST_FOUR, 'foo', '(x) = \1;'),
- compileAndDoNotMatch(TEST_FIVE, 'main', new RegExp('hash0')),
- ]));
+ compileAndDoNotMatch(TEST_FIVE, 'main', new RegExp('hash0')),
+ ]));
}
diff --git a/tests/compiler/dart2js/static_closure_test.dart b/tests/compiler/dart2js/static_closure_test.dart
index 5bf9171..f242806 100644
--- a/tests/compiler/dart2js/static_closure_test.dart
+++ b/tests/compiler/dart2js/static_closure_test.dart
@@ -10,14 +10,16 @@
main() {
asyncTest(() => compileAll(r'''main() { print(main); }''').then((code) {
- // At some point, we will have to closurize global functions
- // differently, at which point this test will break. Then it is time
- // to implement a way to call a Dart closure from JS foreign
- // functions.
+ // At some point, we will have to closurize global functions
+ // differently, at which point this test will break. Then it is time
+ // to implement a way to call a Dart closure from JS foreign
+ // functions.
- // If this test fail, please take a look at the use of
- // toStringWrapper in captureStackTrace in js_helper.dart.
- Expect.isTrue(code.contains(
- new RegExp(r'print\([$A-Z]+\.lib___main\$closure\(\)\);')), code);
- }));
+ // If this test fail, please take a look at the use of
+ // toStringWrapper in captureStackTrace in js_helper.dart.
+ Expect.isTrue(
+ code.contains(
+ new RegExp(r'print\([$A-Z]+\.lib___main\$closure\(\)\);')),
+ code);
+ }));
}
diff --git a/tests/compiler/dart2js/stats_test.dart b/tests/compiler/dart2js/stats_test.dart
index 8aad173..2f30919 100644
--- a/tests/compiler/dart2js/stats_test.dart
+++ b/tests/compiler/dart2js/stats_test.dart
@@ -28,7 +28,8 @@
stats.recordElement('foo', 'b');
stats.recordElement('bar', 'a', data: 'third-a-data');
stats.recordElement('bar', 'c');
- }, r'''
+ },
+ r'''
foo: 2
value=a data=second-a-data
b
@@ -45,7 +46,8 @@
stats.recordFrequency('bar', 'b', 'first-b-data');
stats.recordFrequency('foo', 'c');
stats.recordFrequency('bar', 'b');
- }, r'''
+ },
+ r'''
foo:
a: 2
first-a-data
@@ -68,7 +70,8 @@
stats.recordCounter('bar', 'd');
stats.recordCounter('baz');
stats.recordCounter('baz');
- }, r'''
+ },
+ r'''
foo: 3
count=2 example=a
count=1 example=b
diff --git a/tests/compiler/dart2js/string_add_test.dart b/tests/compiler/dart2js/string_add_test.dart
index 55adbc6..0a045c7 100644
--- a/tests/compiler/dart2js/string_add_test.dart
+++ b/tests/compiler/dart2js/string_add_test.dart
@@ -7,8 +7,8 @@
import 'compiler_helper.dart';
main() {
- asyncTest(() => compileAll(
- r'''main() { return "foo" + "bar"; }''').then((code) {
- Expect.isTrue(!code.contains(r'$add'));
- }));
+ asyncTest(
+ () => compileAll(r'''main() { return "foo" + "bar"; }''').then((code) {
+ Expect.isTrue(!code.contains(r'$add'));
+ }));
}
diff --git a/tests/compiler/dart2js/string_escapes_test.dart b/tests/compiler/dart2js/string_escapes_test.dart
index 1c62a25..b792e7d 100644
--- a/tests/compiler/dart2js/string_escapes_test.dart
+++ b/tests/compiler/dart2js/string_escapes_test.dart
@@ -16,54 +16,57 @@
main() {
asyncTest(() => Future.wait([
- compileExpression("''' \n\r\u2028\u2029'''").then((String generated) {
- Expect.isTrue(generated.contains(r'"\r\u2028\u2029"') ||
- generated.contains(r"'\r\u2028\u2029'"));
- }),
- compileExpression("r''' \n\r\u2028\u2029'''").then((String generated) {
- Expect.isTrue(generated.contains(r'"\r\u2028\u2029"') ||
- generated.contains(r"'\r\u2028\u2029'"));
- }),
- compileExpression("r''' \r\n\u2028\u2029'''").then((String generated) {
- Expect.isTrue(generated.contains(r'"\u2028\u2029"') ||
- generated.contains(r"'\u2028\u2029'"));
- }),
- compileExpression("r''' \r\u2028\u2029'''").then((String generated) {
- Expect.isTrue(generated.contains(r'"\u2028\u2029"') ||
- generated.contains(r"'\u2028\u2029'"));
- }),
- compileExpression("r''' \n\u2028\u2029'''").then((String generated) {
- Expect.isTrue(generated.contains(r'"\u2028\u2029"') ||
- generated.contains(r"'\u2028\u2029'"));
- }),
- compileExpression("r'''\t\t \t\t \t\t \t \t \n\r\u2028\u2029'''")
- .then((String generated) {
- Expect.isTrue(generated.contains(r'"\r\u2028\u2029"') ||
- generated.contains(r"'\r\u2028\u2029'"));
- }),
- compileExpression("r'''\\\t\\\t \\ \\ \t\\\t \t \\\n\r\u2028\u2029'''")
- .then((String generated) {
- Expect.isTrue(generated.contains(r'"\r\u2028\u2029"') ||
- generated.contains(r"'\r\u2028\u2029'"));
- }),
- compileExpression("r'''\t\t \t\t \t\t \t \t \\\n\r\u2028\u2029'''")
- .then((String generated) {
- Expect.isTrue(generated.contains(r'"\r\u2028\u2029"') ||
- generated.contains(r"'\r\u2028\u2029'"));
- }),
- compileExpression("r'''\\\t\\\t \\ \\ \t\\\t \\\r\n\u2028\u2029'''")
- .then((String generated) {
- Expect.isTrue(generated.contains(r'"\u2028\u2029"') ||
- generated.contains(r"'\u2028\u2029'"));
- }),
- compileExpression("r'''\\\t\\\t \\ \\ \t\\\t \\\r\u2028\u2029'''")
- .then((String generated) {
- Expect.isTrue(generated.contains(r'"\u2028\u2029"') ||
- generated.contains(r"'\u2028\u2029'"));
- }),
- compileExpression("'\u2028\u2029'").then((String generated) {
- Expect.isTrue(generated.contains(r'"\u2028\u2029"') ||
- generated.contains(r"'\u2028\u2029'"));
- }),
- ]));
+ compileExpression("''' \n\r\u2028\u2029'''").then((String generated) {
+ Expect.isTrue(generated.contains(r'"\r\u2028\u2029"') ||
+ generated.contains(r"'\r\u2028\u2029'"));
+ }),
+ compileExpression("r''' \n\r\u2028\u2029'''").then((String generated) {
+ Expect.isTrue(generated.contains(r'"\r\u2028\u2029"') ||
+ generated.contains(r"'\r\u2028\u2029'"));
+ }),
+ compileExpression("r''' \r\n\u2028\u2029'''").then((String generated) {
+ Expect.isTrue(generated.contains(r'"\u2028\u2029"') ||
+ generated.contains(r"'\u2028\u2029'"));
+ }),
+ compileExpression("r''' \r\u2028\u2029'''").then((String generated) {
+ Expect.isTrue(generated.contains(r'"\u2028\u2029"') ||
+ generated.contains(r"'\u2028\u2029'"));
+ }),
+ compileExpression("r''' \n\u2028\u2029'''").then((String generated) {
+ Expect.isTrue(generated.contains(r'"\u2028\u2029"') ||
+ generated.contains(r"'\u2028\u2029'"));
+ }),
+ compileExpression("r'''\t\t \t\t \t\t \t \t \n\r\u2028\u2029'''")
+ .then((String generated) {
+ Expect.isTrue(generated.contains(r'"\r\u2028\u2029"') ||
+ generated.contains(r"'\r\u2028\u2029'"));
+ }),
+ compileExpression(
+ "r'''\\\t\\\t \\ \\ \t\\\t \t \\\n\r\u2028\u2029'''")
+ .then((String generated) {
+ Expect.isTrue(generated.contains(r'"\r\u2028\u2029"') ||
+ generated.contains(r"'\r\u2028\u2029'"));
+ }),
+ compileExpression(
+ "r'''\t\t \t\t \t\t \t \t \\\n\r\u2028\u2029'''")
+ .then((String generated) {
+ Expect.isTrue(generated.contains(r'"\r\u2028\u2029"') ||
+ generated.contains(r"'\r\u2028\u2029'"));
+ }),
+ compileExpression(
+ "r'''\\\t\\\t \\ \\ \t\\\t \\\r\n\u2028\u2029'''")
+ .then((String generated) {
+ Expect.isTrue(generated.contains(r'"\u2028\u2029"') ||
+ generated.contains(r"'\u2028\u2029'"));
+ }),
+ compileExpression("r'''\\\t\\\t \\ \\ \t\\\t \\\r\u2028\u2029'''")
+ .then((String generated) {
+ Expect.isTrue(generated.contains(r'"\u2028\u2029"') ||
+ generated.contains(r"'\u2028\u2029'"));
+ }),
+ compileExpression("'\u2028\u2029'").then((String generated) {
+ Expect.isTrue(generated.contains(r'"\u2028\u2029"') ||
+ generated.contains(r"'\u2028\u2029'"));
+ }),
+ ]));
}
diff --git a/tests/compiler/dart2js/string_interpolation_test.dart b/tests/compiler/dart2js/string_interpolation_test.dart
index 4cb5f60..ae49b85 100644
--- a/tests/compiler/dart2js/string_interpolation_test.dart
+++ b/tests/compiler/dart2js/string_interpolation_test.dart
@@ -7,13 +7,14 @@
import 'compiler_helper.dart';
main() {
- asyncTest(() => compileAll(
- r'''main() { return "${2}${true}${'a'}${3.14}"; }''').then((code) {
- Expect.isTrue(code.contains(r'2truea3.14'));
- }));
+ asyncTest(() =>
+ compileAll(r'''main() { return "${2}${true}${'a'}${3.14}"; }''')
+ .then((code) {
+ Expect.isTrue(code.contains(r'2truea3.14'));
+ }));
- asyncTest(() => compileAll(
- r'''main() { return "foo ${new Object()}"; }''').then((code) {
- Expect.isFalse(code.contains(r'$add'));
- }));
+ asyncTest(() =>
+ compileAll(r'''main() { return "foo ${new Object()}"; }''').then((code) {
+ Expect.isFalse(code.contains(r'$add'));
+ }));
}
diff --git a/tests/compiler/dart2js/subtype_test.dart b/tests/compiler/dart2js/subtype_test.dart
index b31e2d8..ad8fba5 100644
--- a/tests/compiler/dart2js/subtype_test.dart
+++ b/tests/compiler/dart2js/subtype_test.dart
@@ -8,8 +8,7 @@
import "package:async_helper/async_helper.dart";
import 'type_test_helper.dart';
import 'package:compiler/src/dart_types.dart';
-import "package:compiler/src/elements/elements.dart"
- show Element, ClassElement;
+import "package:compiler/src/elements/elements.dart" show Element, ClassElement;
void main() {
testInterfaceSubtype();
@@ -24,7 +23,7 @@
}
void testTypes(TypeEnvironment env, DartType subtype, DartType supertype,
- bool expectSubtype, bool expectMoreSpecific) {
+ bool expectSubtype, bool expectMoreSpecific) {
if (expectMoreSpecific == null) expectMoreSpecific = expectSubtype;
Expect.equals(expectSubtype, env.isSubtype(subtype, supertype),
'$subtype <: $supertype');
@@ -33,13 +32,12 @@
}
void testElementTypes(TypeEnvironment env, String subname, String supername,
- bool expectSubtype, bool expectMoreSpecific) {
+ bool expectSubtype, bool expectMoreSpecific) {
DartType subtype = env.getElementType(subname);
DartType supertype = env.getElementType(supername);
testTypes(env, subtype, supertype, expectSubtype, expectMoreSpecific);
}
-
void testInterfaceSubtype() {
asyncTest(() => TypeEnvironment.create(r"""
class A<T> {}
@@ -48,210 +46,212 @@
// currently not supported by the implementation.
class C<T1, T2> extends B<T2, T1> /*implements A<A<T1>>*/ {}
""").then((env) {
+ void expect(bool expectSubtype, DartType T, DartType S,
+ {bool expectMoreSpecific}) {
+ testTypes(env, T, S, expectSubtype, expectMoreSpecific);
+ }
- void expect(bool expectSubtype, DartType T, DartType S,
- {bool expectMoreSpecific}) {
- testTypes(env, T, S, expectSubtype, expectMoreSpecific);
- }
+ ClassElement A = env.getElement('A');
+ ClassElement B = env.getElement('B');
+ ClassElement C = env.getElement('C');
+ DartType Object_ = env['Object'];
+ DartType num_ = env['num'];
+ DartType int_ = env['int'];
+ DartType String_ = env['String'];
+ DartType dynamic_ = env['dynamic'];
+ DartType void_ = env['void'];
- ClassElement A = env.getElement('A');
- ClassElement B = env.getElement('B');
- ClassElement C = env.getElement('C');
- DartType Object_ = env['Object'];
- DartType num_ = env['num'];
- DartType int_ = env['int'];
- DartType String_ = env['String'];
- DartType dynamic_ = env['dynamic'];
- DartType void_ = env['void'];
+ expect(true, void_, void_);
+ expect(true, void_, dynamic_);
+ // Unsure about the next one, see dartbug.com/14933.
+ expect(true, dynamic_, void_, expectMoreSpecific: false);
+ expect(false, void_, Object_);
+ expect(false, Object_, void_);
- expect(true, void_, void_);
- expect(true, void_, dynamic_);
- // Unsure about the next one, see dartbug.com/14933.
- expect(true, dynamic_, void_, expectMoreSpecific: false);
- expect(false, void_, Object_);
- expect(false, Object_, void_);
+ expect(true, Object_, Object_);
+ expect(true, num_, Object_);
+ expect(true, int_, Object_);
+ expect(true, String_, Object_);
+ expect(true, dynamic_, Object_, expectMoreSpecific: false);
- expect(true, Object_, Object_);
- expect(true, num_, Object_);
- expect(true, int_, Object_);
- expect(true, String_, Object_);
- expect(true, dynamic_, Object_, expectMoreSpecific: false);
+ expect(false, Object_, num_);
+ expect(true, num_, num_);
+ expect(true, int_, num_);
+ expect(false, String_, num_);
+ expect(true, dynamic_, num_, expectMoreSpecific: false);
- expect(false, Object_, num_);
- expect(true, num_, num_);
- expect(true, int_, num_);
- expect(false, String_, num_);
- expect(true, dynamic_, num_, expectMoreSpecific: false);
+ expect(false, Object_, int_);
+ expect(false, num_, int_);
+ expect(true, int_, int_);
+ expect(false, String_, int_);
+ expect(true, dynamic_, int_, expectMoreSpecific: false);
- expect(false, Object_, int_);
- expect(false, num_, int_);
- expect(true, int_, int_);
- expect(false, String_, int_);
- expect(true, dynamic_, int_, expectMoreSpecific: false);
+ expect(false, Object_, String_);
+ expect(false, num_, String_);
+ expect(false, int_, String_);
+ expect(true, String_, String_);
+ expect(true, dynamic_, String_, expectMoreSpecific: false);
- expect(false, Object_, String_);
- expect(false, num_, String_);
- expect(false, int_, String_);
- expect(true, String_, String_);
- expect(true, dynamic_, String_, expectMoreSpecific: false);
+ expect(true, Object_, dynamic_);
+ expect(true, num_, dynamic_);
+ expect(true, int_, dynamic_);
+ expect(true, String_, dynamic_);
+ expect(true, dynamic_, dynamic_);
- expect(true, Object_, dynamic_);
- expect(true, num_, dynamic_);
- expect(true, int_, dynamic_);
- expect(true, String_, dynamic_);
- expect(true, dynamic_, dynamic_);
+ DartType A_Object = instantiate(A, [Object_]);
+ DartType A_num = instantiate(A, [num_]);
+ DartType A_int = instantiate(A, [int_]);
+ DartType A_String = instantiate(A, [String_]);
+ DartType A_dynamic = instantiate(A, [dynamic_]);
- DartType A_Object = instantiate(A, [Object_]);
- DartType A_num = instantiate(A, [num_]);
- DartType A_int = instantiate(A, [int_]);
- DartType A_String = instantiate(A, [String_]);
- DartType A_dynamic = instantiate(A, [dynamic_]);
+ expect(true, A_Object, Object_);
+ expect(false, A_Object, num_);
+ expect(false, A_Object, int_);
+ expect(false, A_Object, String_);
+ expect(true, A_Object, dynamic_);
- expect(true, A_Object, Object_);
- expect(false, A_Object, num_);
- expect(false, A_Object, int_);
- expect(false, A_Object, String_);
- expect(true, A_Object, dynamic_);
+ expect(true, A_Object, A_Object);
+ expect(true, A_num, A_Object);
+ expect(true, A_int, A_Object);
+ expect(true, A_String, A_Object);
+ expect(true, A_dynamic, A_Object, expectMoreSpecific: false);
- expect(true, A_Object, A_Object);
- expect(true, A_num, A_Object);
- expect(true, A_int, A_Object);
- expect(true, A_String, A_Object);
- expect(true, A_dynamic, A_Object, expectMoreSpecific: false);
+ expect(false, A_Object, A_num);
+ expect(true, A_num, A_num);
+ expect(true, A_int, A_num);
+ expect(false, A_String, A_num);
+ expect(true, A_dynamic, A_num, expectMoreSpecific: false);
- expect(false, A_Object, A_num);
- expect(true, A_num, A_num);
- expect(true, A_int, A_num);
- expect(false, A_String, A_num);
- expect(true, A_dynamic, A_num, expectMoreSpecific: false);
+ expect(false, A_Object, A_int);
+ expect(false, A_num, A_int);
+ expect(true, A_int, A_int);
+ expect(false, A_String, A_int);
+ expect(true, A_dynamic, A_int, expectMoreSpecific: false);
- expect(false, A_Object, A_int);
- expect(false, A_num, A_int);
- expect(true, A_int, A_int);
- expect(false, A_String, A_int);
- expect(true, A_dynamic, A_int, expectMoreSpecific: false);
+ expect(false, A_Object, A_String);
+ expect(false, A_num, A_String);
+ expect(false, A_int, A_String);
+ expect(true, A_String, A_String);
+ expect(true, A_dynamic, A_String, expectMoreSpecific: false);
- expect(false, A_Object, A_String);
- expect(false, A_num, A_String);
- expect(false, A_int, A_String);
- expect(true, A_String, A_String);
- expect(true, A_dynamic, A_String, expectMoreSpecific: false);
+ expect(true, A_Object, A_dynamic);
+ expect(true, A_num, A_dynamic);
+ expect(true, A_int, A_dynamic);
+ expect(true, A_String, A_dynamic);
+ expect(true, A_dynamic, A_dynamic);
- expect(true, A_Object, A_dynamic);
- expect(true, A_num, A_dynamic);
- expect(true, A_int, A_dynamic);
- expect(true, A_String, A_dynamic);
- expect(true, A_dynamic, A_dynamic);
+ DartType B_Object_Object = instantiate(B, [Object_, Object_]);
+ DartType B_num_num = instantiate(B, [num_, num_]);
+ DartType B_int_num = instantiate(B, [int_, num_]);
+ DartType B_dynamic_dynamic = instantiate(B, [dynamic_, dynamic_]);
+ DartType B_String_dynamic = instantiate(B, [String_, dynamic_]);
- DartType B_Object_Object = instantiate(B, [Object_, Object_]);
- DartType B_num_num = instantiate(B, [num_, num_]);
- DartType B_int_num = instantiate(B, [int_, num_]);
- DartType B_dynamic_dynamic = instantiate(B, [dynamic_, dynamic_]);
- DartType B_String_dynamic = instantiate(B, [String_, dynamic_]);
+ expect(true, B_Object_Object, Object_);
+ expect(true, B_Object_Object, A_Object);
+ expect(false, B_Object_Object, A_num);
+ expect(false, B_Object_Object, A_int);
+ expect(false, B_Object_Object, A_String);
+ expect(true, B_Object_Object, A_dynamic);
- expect(true, B_Object_Object, Object_);
- expect(true, B_Object_Object, A_Object);
- expect(false, B_Object_Object, A_num);
- expect(false, B_Object_Object, A_int);
- expect(false, B_Object_Object, A_String);
- expect(true, B_Object_Object, A_dynamic);
+ expect(true, B_num_num, Object_);
+ expect(true, B_num_num, A_Object);
+ expect(true, B_num_num, A_num);
+ expect(false, B_num_num, A_int);
+ expect(false, B_num_num, A_String);
+ expect(true, B_num_num, A_dynamic);
- expect(true, B_num_num, Object_);
- expect(true, B_num_num, A_Object);
- expect(true, B_num_num, A_num);
- expect(false, B_num_num, A_int);
- expect(false, B_num_num, A_String);
- expect(true, B_num_num, A_dynamic);
+ expect(true, B_int_num, Object_);
+ expect(true, B_int_num, A_Object);
+ expect(true, B_int_num, A_num);
+ expect(true, B_int_num, A_int);
+ expect(false, B_int_num, A_String);
+ expect(true, B_int_num, A_dynamic);
- expect(true, B_int_num, Object_);
- expect(true, B_int_num, A_Object);
- expect(true, B_int_num, A_num);
- expect(true, B_int_num, A_int);
- expect(false, B_int_num, A_String);
- expect(true, B_int_num, A_dynamic);
+ expect(true, B_dynamic_dynamic, Object_);
+ expect(true, B_dynamic_dynamic, A_Object, expectMoreSpecific: false);
+ expect(true, B_dynamic_dynamic, A_num, expectMoreSpecific: false);
+ expect(true, B_dynamic_dynamic, A_int, expectMoreSpecific: false);
+ expect(true, B_dynamic_dynamic, A_String, expectMoreSpecific: false);
+ expect(true, B_dynamic_dynamic, A_dynamic);
- expect(true, B_dynamic_dynamic, Object_);
- expect(true, B_dynamic_dynamic, A_Object, expectMoreSpecific: false);
- expect(true, B_dynamic_dynamic, A_num, expectMoreSpecific: false);
- expect(true, B_dynamic_dynamic, A_int, expectMoreSpecific: false);
- expect(true, B_dynamic_dynamic, A_String, expectMoreSpecific: false);
- expect(true, B_dynamic_dynamic, A_dynamic);
+ expect(true, B_String_dynamic, Object_);
+ expect(true, B_String_dynamic, A_Object);
+ expect(false, B_String_dynamic, A_num);
+ expect(false, B_String_dynamic, A_int);
+ expect(true, B_String_dynamic, A_String);
+ expect(true, B_String_dynamic, A_dynamic);
- expect(true, B_String_dynamic, Object_);
- expect(true, B_String_dynamic, A_Object);
- expect(false, B_String_dynamic, A_num);
- expect(false, B_String_dynamic, A_int);
- expect(true, B_String_dynamic, A_String);
- expect(true, B_String_dynamic, A_dynamic);
+ expect(true, B_Object_Object, B_Object_Object);
+ expect(true, B_num_num, B_Object_Object);
+ expect(true, B_int_num, B_Object_Object);
+ expect(true, B_dynamic_dynamic, B_Object_Object,
+ expectMoreSpecific: false);
+ expect(true, B_String_dynamic, B_Object_Object,
+ expectMoreSpecific: false);
- expect(true, B_Object_Object, B_Object_Object);
- expect(true, B_num_num, B_Object_Object);
- expect(true, B_int_num, B_Object_Object);
- expect(true, B_dynamic_dynamic, B_Object_Object, expectMoreSpecific: false);
- expect(true, B_String_dynamic, B_Object_Object, expectMoreSpecific: false);
+ expect(false, B_Object_Object, B_num_num);
+ expect(true, B_num_num, B_num_num);
+ expect(true, B_int_num, B_num_num);
+ expect(true, B_dynamic_dynamic, B_num_num, expectMoreSpecific: false);
+ expect(false, B_String_dynamic, B_num_num);
- expect(false, B_Object_Object, B_num_num);
- expect(true, B_num_num, B_num_num);
- expect(true, B_int_num, B_num_num);
- expect(true, B_dynamic_dynamic, B_num_num, expectMoreSpecific: false);
- expect(false, B_String_dynamic, B_num_num);
+ expect(false, B_Object_Object, B_int_num);
+ expect(false, B_num_num, B_int_num);
+ expect(true, B_int_num, B_int_num);
+ expect(true, B_dynamic_dynamic, B_int_num, expectMoreSpecific: false);
+ expect(false, B_String_dynamic, B_int_num);
- expect(false, B_Object_Object, B_int_num);
- expect(false, B_num_num, B_int_num);
- expect(true, B_int_num, B_int_num);
- expect(true, B_dynamic_dynamic, B_int_num, expectMoreSpecific: false);
- expect(false, B_String_dynamic, B_int_num);
+ expect(true, B_Object_Object, B_dynamic_dynamic);
+ expect(true, B_num_num, B_dynamic_dynamic);
+ expect(true, B_int_num, B_dynamic_dynamic);
+ expect(true, B_dynamic_dynamic, B_dynamic_dynamic);
+ expect(true, B_String_dynamic, B_dynamic_dynamic);
- expect(true, B_Object_Object, B_dynamic_dynamic);
- expect(true, B_num_num, B_dynamic_dynamic);
- expect(true, B_int_num, B_dynamic_dynamic);
- expect(true, B_dynamic_dynamic, B_dynamic_dynamic);
- expect(true, B_String_dynamic, B_dynamic_dynamic);
+ expect(false, B_Object_Object, B_String_dynamic);
+ expect(false, B_num_num, B_String_dynamic);
+ expect(false, B_int_num, B_String_dynamic);
+ expect(true, B_dynamic_dynamic, B_String_dynamic,
+ expectMoreSpecific: false);
+ expect(true, B_String_dynamic, B_String_dynamic);
- expect(false, B_Object_Object, B_String_dynamic);
- expect(false, B_num_num, B_String_dynamic);
- expect(false, B_int_num, B_String_dynamic);
- expect(true, B_dynamic_dynamic, B_String_dynamic,
- expectMoreSpecific: false);
- expect(true, B_String_dynamic, B_String_dynamic);
+ DartType C_Object_Object = instantiate(C, [Object_, Object_]);
+ DartType C_num_num = instantiate(C, [num_, num_]);
+ DartType C_int_String = instantiate(C, [int_, String_]);
+ DartType C_dynamic_dynamic = instantiate(C, [dynamic_, dynamic_]);
- DartType C_Object_Object = instantiate(C, [Object_, Object_]);
- DartType C_num_num = instantiate(C, [num_, num_]);
- DartType C_int_String = instantiate(C, [int_, String_]);
- DartType C_dynamic_dynamic = instantiate(C, [dynamic_, dynamic_]);
+ expect(true, C_Object_Object, B_Object_Object);
+ expect(false, C_Object_Object, B_num_num);
+ expect(false, C_Object_Object, B_int_num);
+ expect(true, C_Object_Object, B_dynamic_dynamic);
+ expect(false, C_Object_Object, B_String_dynamic);
- expect(true, C_Object_Object, B_Object_Object);
- expect(false, C_Object_Object, B_num_num);
- expect(false, C_Object_Object, B_int_num);
- expect(true, C_Object_Object, B_dynamic_dynamic);
- expect(false, C_Object_Object, B_String_dynamic);
+ expect(true, C_num_num, B_Object_Object);
+ expect(true, C_num_num, B_num_num);
+ expect(false, C_num_num, B_int_num);
+ expect(true, C_num_num, B_dynamic_dynamic);
+ expect(false, C_num_num, B_String_dynamic);
- expect(true, C_num_num, B_Object_Object);
- expect(true, C_num_num, B_num_num);
- expect(false, C_num_num, B_int_num);
- expect(true, C_num_num, B_dynamic_dynamic);
- expect(false, C_num_num, B_String_dynamic);
+ expect(true, C_int_String, B_Object_Object);
+ expect(false, C_int_String, B_num_num);
+ expect(false, C_int_String, B_int_num);
+ expect(true, C_int_String, B_dynamic_dynamic);
+ expect(true, C_int_String, B_String_dynamic);
- expect(true, C_int_String, B_Object_Object);
- expect(false, C_int_String, B_num_num);
- expect(false, C_int_String, B_int_num);
- expect(true, C_int_String, B_dynamic_dynamic);
- expect(true, C_int_String, B_String_dynamic);
+ expect(true, C_dynamic_dynamic, B_Object_Object,
+ expectMoreSpecific: false);
+ expect(true, C_dynamic_dynamic, B_num_num, expectMoreSpecific: false);
+ expect(true, C_dynamic_dynamic, B_int_num, expectMoreSpecific: false);
+ expect(true, C_dynamic_dynamic, B_dynamic_dynamic);
+ expect(true, C_dynamic_dynamic, B_String_dynamic,
+ expectMoreSpecific: false);
- expect(true, C_dynamic_dynamic, B_Object_Object, expectMoreSpecific: false);
- expect(true, C_dynamic_dynamic, B_num_num, expectMoreSpecific: false);
- expect(true, C_dynamic_dynamic, B_int_num, expectMoreSpecific: false);
- expect(true, C_dynamic_dynamic, B_dynamic_dynamic);
- expect(true, C_dynamic_dynamic, B_String_dynamic,
- expectMoreSpecific: false);
-
- expect(false, C_int_String, A_int);
- expect(true, C_int_String, A_String);
- // TODO(johnniwinther): Inheritance with different type arguments is
- // currently not supported by the implementation.
- //expect(true, C_int_String, instantiate(A, [A_int]));
- expect(false, C_int_String, instantiate(A, [A_String]));
- }));
+ expect(false, C_int_String, A_int);
+ expect(true, C_int_String, A_String);
+ // TODO(johnniwinther): Inheritance with different type arguments is
+ // currently not supported by the implementation.
+ //expect(true, C_int_String, instantiate(A, [A_int]));
+ expect(false, C_int_String, instantiate(A, [A_String]));
+ }));
}
void testCallableSubtype() {
@@ -269,30 +269,30 @@
void m5(V v, int i);
}
""").then((env) {
- void expect(bool expectSubtype, DartType T, DartType S,
- {bool expectMoreSpecific}) {
- testTypes(env, T, S, expectSubtype, expectMoreSpecific);
- }
+ void expect(bool expectSubtype, DartType T, DartType S,
+ {bool expectMoreSpecific}) {
+ testTypes(env, T, S, expectSubtype, expectMoreSpecific);
+ }
- ClassElement classA = env.getElement('A');
- DartType A = classA.rawType;
- DartType function = env['Function'];
- DartType call = env.getMemberType(classA, 'call');
- DartType m1 = env.getMemberType(classA, 'm1');
- DartType m2 = env.getMemberType(classA, 'm2');
- DartType m3 = env.getMemberType(classA, 'm3');
- DartType m4 = env.getMemberType(classA, 'm4');
- DartType m5 = env.getMemberType(classA, 'm5');
+ ClassElement classA = env.getElement('A');
+ DartType A = classA.rawType;
+ DartType function = env['Function'];
+ DartType call = env.getMemberType(classA, 'call');
+ DartType m1 = env.getMemberType(classA, 'm1');
+ DartType m2 = env.getMemberType(classA, 'm2');
+ DartType m3 = env.getMemberType(classA, 'm3');
+ DartType m4 = env.getMemberType(classA, 'm4');
+ DartType m5 = env.getMemberType(classA, 'm5');
- expect(true, A, function);
- expect(true, A, call);
- expect(true, call, m1);
- expect(true, A, m1);
- expect(true, A, m2, expectMoreSpecific: false);
- expect(false, A, m3);
- expect(false, A, m4);
- expect(true, A, m5);
- }));
+ expect(true, A, function);
+ expect(true, A, call);
+ expect(true, call, m1);
+ expect(true, A, m1);
+ expect(true, A, m2, expectMoreSpecific: false);
+ expect(false, A, m3);
+ expect(false, A, m4);
+ expect(true, A, m5);
+ }));
}
testFunctionSubtyping() {
@@ -339,7 +339,7 @@
functionSubtypingHelper(TypeEnvironment env) {
void expect(bool expectSubtype, String sub, String sup,
- {bool expectMoreSpecific}) {
+ {bool expectMoreSpecific}) {
testElementTypes(env, sub, sup, expectSubtype, expectMoreSpecific);
}
@@ -427,7 +427,7 @@
functionSubtypingOptionalHelper(TypeEnvironment env) {
void expect(bool expectSubtype, String sub, String sup,
- {bool expectMoreSpecific}) {
+ {bool expectMoreSpecific}) {
testElementTypes(env, sub, sup, expectSubtype, expectMoreSpecific);
}
@@ -507,7 +507,7 @@
functionSubtypingNamedHelper(TypeEnvironment env) {
expect(bool expectSubtype, String sub, String sup,
- {bool expectMoreSpecific}) {
+ {bool expectMoreSpecific}) {
testElementTypes(env, sub, sup, expectSubtype, expectMoreSpecific);
}
@@ -554,207 +554,207 @@
class I<T extends S, S extends U, U extends T> {}
class J<T extends S, S extends U, U extends S> {}
""").then((env) {
- void expect(bool expectSubtype, DartType T, DartType S,
- {bool expectMoreSpecific}) {
- testTypes(env, T, S, expectSubtype, expectMoreSpecific);
- }
+ void expect(bool expectSubtype, DartType T, DartType S,
+ {bool expectMoreSpecific}) {
+ testTypes(env, T, S, expectSubtype, expectMoreSpecific);
+ }
- ClassElement A = env.getElement('A');
- TypeVariableType A_T = A.thisType.typeArguments[0];
- ClassElement B = env.getElement('B');
- TypeVariableType B_T = B.thisType.typeArguments[0];
- ClassElement C = env.getElement('C');
- TypeVariableType C_T = C.thisType.typeArguments[0];
- ClassElement D = env.getElement('D');
- TypeVariableType D_T = D.thisType.typeArguments[0];
- ClassElement E = env.getElement('E');
- TypeVariableType E_T = E.thisType.typeArguments[0];
- TypeVariableType E_S = E.thisType.typeArguments[1];
- ClassElement F = env.getElement('F');
- TypeVariableType F_T = F.thisType.typeArguments[0];
- TypeVariableType F_S = F.thisType.typeArguments[1];
- ClassElement G = env.getElement('G');
- TypeVariableType G_T = G.thisType.typeArguments[0];
- ClassElement H = env.getElement('H');
- TypeVariableType H_T = H.thisType.typeArguments[0];
- TypeVariableType H_S = H.thisType.typeArguments[1];
- ClassElement I = env.getElement('I');
- TypeVariableType I_T = I.thisType.typeArguments[0];
- TypeVariableType I_S = I.thisType.typeArguments[1];
- TypeVariableType I_U = I.thisType.typeArguments[2];
- ClassElement J = env.getElement('J');
- TypeVariableType J_T = J.thisType.typeArguments[0];
- TypeVariableType J_S = J.thisType.typeArguments[1];
- TypeVariableType J_U = J.thisType.typeArguments[2];
+ ClassElement A = env.getElement('A');
+ TypeVariableType A_T = A.thisType.typeArguments[0];
+ ClassElement B = env.getElement('B');
+ TypeVariableType B_T = B.thisType.typeArguments[0];
+ ClassElement C = env.getElement('C');
+ TypeVariableType C_T = C.thisType.typeArguments[0];
+ ClassElement D = env.getElement('D');
+ TypeVariableType D_T = D.thisType.typeArguments[0];
+ ClassElement E = env.getElement('E');
+ TypeVariableType E_T = E.thisType.typeArguments[0];
+ TypeVariableType E_S = E.thisType.typeArguments[1];
+ ClassElement F = env.getElement('F');
+ TypeVariableType F_T = F.thisType.typeArguments[0];
+ TypeVariableType F_S = F.thisType.typeArguments[1];
+ ClassElement G = env.getElement('G');
+ TypeVariableType G_T = G.thisType.typeArguments[0];
+ ClassElement H = env.getElement('H');
+ TypeVariableType H_T = H.thisType.typeArguments[0];
+ TypeVariableType H_S = H.thisType.typeArguments[1];
+ ClassElement I = env.getElement('I');
+ TypeVariableType I_T = I.thisType.typeArguments[0];
+ TypeVariableType I_S = I.thisType.typeArguments[1];
+ TypeVariableType I_U = I.thisType.typeArguments[2];
+ ClassElement J = env.getElement('J');
+ TypeVariableType J_T = J.thisType.typeArguments[0];
+ TypeVariableType J_S = J.thisType.typeArguments[1];
+ TypeVariableType J_U = J.thisType.typeArguments[2];
- DartType Object_ = env['Object'];
- DartType num_ = env['num'];
- DartType int_ = env['int'];
- DartType String_ = env['String'];
- DartType dynamic_ = env['dynamic'];
+ DartType Object_ = env['Object'];
+ DartType num_ = env['num'];
+ DartType int_ = env['int'];
+ DartType String_ = env['String'];
+ DartType dynamic_ = env['dynamic'];
- // class A<T> {}
- expect(true, A_T, Object_);
- expect(false, A_T, num_);
- expect(false, A_T, int_);
- expect(false, A_T, String_);
- expect(true, A_T, dynamic_);
- expect(true, A_T, A_T);
- expect(false, A_T, B_T);
+ // class A<T> {}
+ expect(true, A_T, Object_);
+ expect(false, A_T, num_);
+ expect(false, A_T, int_);
+ expect(false, A_T, String_);
+ expect(true, A_T, dynamic_);
+ expect(true, A_T, A_T);
+ expect(false, A_T, B_T);
- // class B<T extends Object> {}
- expect(true, B_T, Object_);
- expect(false, B_T, num_);
- expect(false, B_T, int_);
- expect(false, B_T, String_);
- expect(true, B_T, dynamic_);
- expect(true, B_T, B_T);
- expect(false, B_T, A_T);
+ // class B<T extends Object> {}
+ expect(true, B_T, Object_);
+ expect(false, B_T, num_);
+ expect(false, B_T, int_);
+ expect(false, B_T, String_);
+ expect(true, B_T, dynamic_);
+ expect(true, B_T, B_T);
+ expect(false, B_T, A_T);
- // class C<T extends num> {}
- expect(true, C_T, Object_);
- expect(true, C_T, num_);
- expect(false, C_T, int_);
- expect(false, C_T, String_);
- expect(true, C_T, dynamic_);
- expect(true, C_T, C_T);
- expect(false, C_T, A_T);
+ // class C<T extends num> {}
+ expect(true, C_T, Object_);
+ expect(true, C_T, num_);
+ expect(false, C_T, int_);
+ expect(false, C_T, String_);
+ expect(true, C_T, dynamic_);
+ expect(true, C_T, C_T);
+ expect(false, C_T, A_T);
- // class D<T extends int> {}
- expect(true, D_T, Object_);
- expect(true, D_T, num_);
- expect(true, D_T, int_);
- expect(false, D_T, String_);
- expect(true, D_T, dynamic_);
- expect(true, D_T, D_T);
- expect(false, D_T, A_T);
+ // class D<T extends int> {}
+ expect(true, D_T, Object_);
+ expect(true, D_T, num_);
+ expect(true, D_T, int_);
+ expect(false, D_T, String_);
+ expect(true, D_T, dynamic_);
+ expect(true, D_T, D_T);
+ expect(false, D_T, A_T);
- // class E<T extends S, S extends num> {}
- expect(true, E_T, Object_);
- expect(true, E_T, num_);
- expect(false, E_T, int_);
- expect(false, E_T, String_);
- expect(true, E_T, dynamic_);
- expect(true, E_T, E_T);
- expect(true, E_T, E_S);
- expect(false, E_T, A_T);
+ // class E<T extends S, S extends num> {}
+ expect(true, E_T, Object_);
+ expect(true, E_T, num_);
+ expect(false, E_T, int_);
+ expect(false, E_T, String_);
+ expect(true, E_T, dynamic_);
+ expect(true, E_T, E_T);
+ expect(true, E_T, E_S);
+ expect(false, E_T, A_T);
- expect(true, E_S, Object_);
- expect(true, E_S, num_);
- expect(false, E_S, int_);
- expect(false, E_S, String_);
- expect(true, E_S, dynamic_);
- expect(false, E_S, E_T);
- expect(true, E_S, E_S);
- expect(false, E_S, A_T);
+ expect(true, E_S, Object_);
+ expect(true, E_S, num_);
+ expect(false, E_S, int_);
+ expect(false, E_S, String_);
+ expect(true, E_S, dynamic_);
+ expect(false, E_S, E_T);
+ expect(true, E_S, E_S);
+ expect(false, E_S, A_T);
- // class F<T extends num, S extends T> {}
- expect(true, F_T, Object_);
- expect(true, F_T, num_);
- expect(false, F_T, int_);
- expect(false, F_T, String_);
- expect(true, F_T, dynamic_);
- expect(false, F_T, F_S);
- expect(true, F_T, F_T);
- expect(false, F_T, A_T);
+ // class F<T extends num, S extends T> {}
+ expect(true, F_T, Object_);
+ expect(true, F_T, num_);
+ expect(false, F_T, int_);
+ expect(false, F_T, String_);
+ expect(true, F_T, dynamic_);
+ expect(false, F_T, F_S);
+ expect(true, F_T, F_T);
+ expect(false, F_T, A_T);
- expect(true, F_S, Object_);
- expect(true, F_S, num_);
- expect(false, F_S, int_);
- expect(false, F_S, String_);
- expect(true, F_S, dynamic_);
- expect(true, F_S, F_S);
- expect(true, F_S, F_T);
- expect(false, F_S, A_T);
+ expect(true, F_S, Object_);
+ expect(true, F_S, num_);
+ expect(false, F_S, int_);
+ expect(false, F_S, String_);
+ expect(true, F_S, dynamic_);
+ expect(true, F_S, F_S);
+ expect(true, F_S, F_T);
+ expect(false, F_S, A_T);
- // class G<T extends T> {}
- expect(true, G_T, Object_);
- expect(false, G_T, num_);
- expect(false, G_T, int_);
- expect(false, G_T, String_);
- expect(true, G_T, dynamic_);
- expect(true, G_T, G_T);
- expect(false, G_T, A_T);
+ // class G<T extends T> {}
+ expect(true, G_T, Object_);
+ expect(false, G_T, num_);
+ expect(false, G_T, int_);
+ expect(false, G_T, String_);
+ expect(true, G_T, dynamic_);
+ expect(true, G_T, G_T);
+ expect(false, G_T, A_T);
- // class H<T extends S, S extends T> {}
- expect(true, H_T, Object_);
- expect(false, H_T, num_);
- expect(false, H_T, int_);
- expect(false, H_T, String_);
- expect(true, H_T, dynamic_);
- expect(true, H_T, H_T);
- expect(true, H_T, H_S);
- expect(false, H_T, A_T);
+ // class H<T extends S, S extends T> {}
+ expect(true, H_T, Object_);
+ expect(false, H_T, num_);
+ expect(false, H_T, int_);
+ expect(false, H_T, String_);
+ expect(true, H_T, dynamic_);
+ expect(true, H_T, H_T);
+ expect(true, H_T, H_S);
+ expect(false, H_T, A_T);
- expect(true, H_S, Object_);
- expect(false, H_S, num_);
- expect(false, H_S, int_);
- expect(false, H_S, String_);
- expect(true, H_S, dynamic_);
- expect(true, H_S, H_T);
- expect(true, H_S, H_S);
- expect(false, H_S, A_T);
+ expect(true, H_S, Object_);
+ expect(false, H_S, num_);
+ expect(false, H_S, int_);
+ expect(false, H_S, String_);
+ expect(true, H_S, dynamic_);
+ expect(true, H_S, H_T);
+ expect(true, H_S, H_S);
+ expect(false, H_S, A_T);
- // class I<T extends S, S extends U, U extends T> {}
- expect(true, I_T, Object_);
- expect(false, I_T, num_);
- expect(false, I_T, int_);
- expect(false, I_T, String_);
- expect(true, I_T, dynamic_);
- expect(true, I_T, I_T);
- expect(true, I_T, I_S);
- expect(true, I_T, I_U);
- expect(false, I_T, A_T);
+ // class I<T extends S, S extends U, U extends T> {}
+ expect(true, I_T, Object_);
+ expect(false, I_T, num_);
+ expect(false, I_T, int_);
+ expect(false, I_T, String_);
+ expect(true, I_T, dynamic_);
+ expect(true, I_T, I_T);
+ expect(true, I_T, I_S);
+ expect(true, I_T, I_U);
+ expect(false, I_T, A_T);
- expect(true, I_S, Object_);
- expect(false, I_S, num_);
- expect(false, I_S, int_);
- expect(false, I_S, String_);
- expect(true, I_S, dynamic_);
- expect(true, I_S, I_T);
- expect(true, I_S, I_S);
- expect(true, I_S, I_U);
- expect(false, I_S, A_T);
+ expect(true, I_S, Object_);
+ expect(false, I_S, num_);
+ expect(false, I_S, int_);
+ expect(false, I_S, String_);
+ expect(true, I_S, dynamic_);
+ expect(true, I_S, I_T);
+ expect(true, I_S, I_S);
+ expect(true, I_S, I_U);
+ expect(false, I_S, A_T);
- expect(true, I_U, Object_);
- expect(false, I_U, num_);
- expect(false, I_U, int_);
- expect(false, I_U, String_);
- expect(true, I_U, dynamic_);
- expect(true, I_U, I_T);
- expect(true, I_U, I_S);
- expect(true, I_U, I_U);
- expect(false, I_U, A_T);
+ expect(true, I_U, Object_);
+ expect(false, I_U, num_);
+ expect(false, I_U, int_);
+ expect(false, I_U, String_);
+ expect(true, I_U, dynamic_);
+ expect(true, I_U, I_T);
+ expect(true, I_U, I_S);
+ expect(true, I_U, I_U);
+ expect(false, I_U, A_T);
- // class J<T extends S, S extends U, U extends S> {}
- expect(true, J_T, Object_);
- expect(false, J_T, num_);
- expect(false, J_T, int_);
- expect(false, J_T, String_);
- expect(true, J_T, dynamic_);
- expect(true, J_T, J_T);
- expect(true, J_T, J_S);
- expect(true, J_T, J_U);
- expect(false, J_T, A_T);
+ // class J<T extends S, S extends U, U extends S> {}
+ expect(true, J_T, Object_);
+ expect(false, J_T, num_);
+ expect(false, J_T, int_);
+ expect(false, J_T, String_);
+ expect(true, J_T, dynamic_);
+ expect(true, J_T, J_T);
+ expect(true, J_T, J_S);
+ expect(true, J_T, J_U);
+ expect(false, J_T, A_T);
- expect(true, J_S, Object_);
- expect(false, J_S, num_);
- expect(false, J_S, int_);
- expect(false, J_S, String_);
- expect(true, J_S, dynamic_);
- expect(false, J_S, J_T);
- expect(true, J_S, J_S);
- expect(true, J_S, J_U);
- expect(false, J_S, A_T);
+ expect(true, J_S, Object_);
+ expect(false, J_S, num_);
+ expect(false, J_S, int_);
+ expect(false, J_S, String_);
+ expect(true, J_S, dynamic_);
+ expect(false, J_S, J_T);
+ expect(true, J_S, J_S);
+ expect(true, J_S, J_U);
+ expect(false, J_S, A_T);
- expect(true, J_U, Object_);
- expect(false, J_U, num_);
- expect(false, J_U, int_);
- expect(false, J_U, String_);
- expect(true, J_U, dynamic_);
- expect(false, J_U, J_T);
- expect(true, J_U, J_S);
- expect(true, J_U, J_U);
- expect(false, J_U, A_T);
- }));
+ expect(true, J_U, Object_);
+ expect(false, J_U, num_);
+ expect(false, J_U, int_);
+ expect(false, J_U, String_);
+ expect(true, J_U, dynamic_);
+ expect(false, J_U, J_T);
+ expect(true, J_U, J_S);
+ expect(true, J_U, J_U);
+ expect(false, J_U, A_T);
+ }));
}
diff --git a/tests/compiler/dart2js/subtypeset_test.dart b/tests/compiler/dart2js/subtypeset_test.dart
index 1853a8b..38bac61 100644
--- a/tests/compiler/dart2js/subtypeset_test.dart
+++ b/tests/compiler/dart2js/subtypeset_test.dart
@@ -9,13 +9,14 @@
import 'package:expect/expect.dart';
import 'package:async_helper/async_helper.dart';
import 'type_test_helper.dart';
-import 'package:compiler/src/elements/elements.dart'
- show Element, ClassElement;
+import 'package:compiler/src/elements/elements.dart' show Element, ClassElement;
import 'package:compiler/src/universe/class_set.dart';
import 'package:compiler/src/world.dart';
void main() {
- asyncTest(() => TypeEnvironment.create(r"""
+ asyncTest(() => TypeEnvironment
+ .create(
+ r"""
/// A
/// / \
/// B C
@@ -34,7 +35,7 @@
class H implements C {}
class I implements H {}
""",
- mainSource: r"""
+ mainSource: r"""
main() {
new A();
new C();
@@ -44,38 +45,39 @@
new G();
}
""",
- useMockCompiler: false).then((env) {
- World world = env.compiler.world;
+ useMockCompiler: false)
+ .then((env) {
+ World world = env.compiler.world;
- ClassElement A = env.getElement("A");
- ClassElement B = env.getElement("B");
- ClassElement C = env.getElement("C");
- ClassElement D = env.getElement("D");
- ClassElement E = env.getElement("E");
- ClassElement F = env.getElement("F");
- ClassElement G = env.getElement("G");
- ClassElement H = env.getElement("H");
- ClassElement I = env.getElement("I");
+ ClassElement A = env.getElement("A");
+ ClassElement B = env.getElement("B");
+ ClassElement C = env.getElement("C");
+ ClassElement D = env.getElement("D");
+ ClassElement E = env.getElement("E");
+ ClassElement F = env.getElement("F");
+ ClassElement G = env.getElement("G");
+ ClassElement H = env.getElement("H");
+ ClassElement I = env.getElement("I");
- void checkClass(ClassElement cls,
- List<ClassElement> subtypes) {
- ClassSet node = world.getClassSet(cls);
- print('$cls:\n${node}');
- Expect.listEquals(subtypes,
- node.subtypes().toList(),
- "Unexpected subtypes of ${cls.name}:\n"
- "Expected: $subtypes\n"
- "Found : ${node.subtypes().toList()}");
- }
+ void checkClass(ClassElement cls, List<ClassElement> subtypes) {
+ ClassSet node = world.getClassSet(cls);
+ print('$cls:\n${node}');
+ Expect.listEquals(
+ subtypes,
+ node.subtypes().toList(),
+ "Unexpected subtypes of ${cls.name}:\n"
+ "Expected: $subtypes\n"
+ "Found : ${node.subtypes().toList()}");
+ }
- checkClass(A, [A, C, E, F, G, B, D, H, I]);
- checkClass(B, [B, D, E]);
- checkClass(C, [C, E, F, G, H, B, D, I]);
- checkClass(D, [D]);
- checkClass(E, [E]);
- checkClass(F, [F]);
- checkClass(G, [G]);
- checkClass(H, [H, I]);
- checkClass(I, [I]);
- }));
+ checkClass(A, [A, C, E, F, G, B, D, H, I]);
+ checkClass(B, [B, D, E]);
+ checkClass(C, [C, E, F, G, H, B, D, I]);
+ checkClass(D, [D]);
+ checkClass(E, [E]);
+ checkClass(F, [F]);
+ checkClass(G, [G]);
+ checkClass(H, [H, I]);
+ checkClass(I, [I]);
+ }));
}
diff --git a/tests/compiler/dart2js/switch_empty_default_test.dart b/tests/compiler/dart2js/switch_empty_default_test.dart
index d0d2f88..cbddf01 100644
--- a/tests/compiler/dart2js/switch_empty_default_test.dart
+++ b/tests/compiler/dart2js/switch_empty_default_test.dart
@@ -121,11 +121,11 @@
var case3 = new RegExp(r"case 3:");
asyncTest(() => Future.wait([
- compileAndDoNotMatch(SIMPLY_EMPTY, 'main', def),
- compileAndDoNotMatch(TOTAL, 'main', defOrCase3),
- compileAndDoNotMatch(OPTIMIZED, 'main', def),
- compileAndMatch(LABEL, 'main', case3),
- compileAndMatch(DEFLABEL, 'main', def),
- compileAndMatch(EMPTYDEFLABEL, 'main', def),
- ]));
+ compileAndDoNotMatch(SIMPLY_EMPTY, 'main', def),
+ compileAndDoNotMatch(TOTAL, 'main', defOrCase3),
+ compileAndDoNotMatch(OPTIMIZED, 'main', def),
+ compileAndMatch(LABEL, 'main', case3),
+ compileAndMatch(DEFLABEL, 'main', def),
+ compileAndMatch(EMPTYDEFLABEL, 'main', def),
+ ]));
}
diff --git a/tests/compiler/dart2js/tag_mapping_test.dart b/tests/compiler/dart2js/tag_mapping_test.dart
index ed781f3..8080942 100644
--- a/tests/compiler/dart2js/tag_mapping_test.dart
+++ b/tests/compiler/dart2js/tag_mapping_test.dart
@@ -26,18 +26,18 @@
};
asyncTest(() => compileSources(sources, (MockCompiler compiler) {
- LibraryElement mainApp =
- compiler.libraryLoader.lookupLibrary(Uri.parse('source:/main.dart'));
- LibraryElement lib =
- compiler.libraryLoader.lookupLibrary(Uri.parse('source:/library.dart'));
- Expect.isNotNull(mainApp, 'Could not find main.dart library');
- Expect.isNotNull(lib, 'Could not find library.dart library');
+ LibraryElement mainApp = compiler.libraryLoader
+ .lookupLibrary(Uri.parse('source:/main.dart'));
+ LibraryElement lib = compiler.libraryLoader
+ .lookupLibrary(Uri.parse('source:/library.dart'));
+ Expect.isNotNull(mainApp, 'Could not find main.dart library');
+ Expect.isNotNull(lib, 'Could not find library.dart library');
- ImportElement import = mainApp.imports.single;
- Expect.isNotNull(import, 'Could not find import tag in $mainApp');
+ ImportElement import = mainApp.imports.single;
+ Expect.isNotNull(import, 'Could not find import tag in $mainApp');
- // Test that we can get from the import tag in main.dart to the
- // library element representing library.dart.
- Expect.identical(lib, import.importedLibrary);
- }));
+ // Test that we can get from the import tag in main.dart to the
+ // library element representing library.dart.
+ Expect.identical(lib, import.importedLibrary);
+ }));
}
diff --git a/tests/compiler/dart2js/tdiv_test.dart b/tests/compiler/dart2js/tdiv_test.dart
index 86eb955..f6407d4 100644
--- a/tests/compiler/dart2js/tdiv_test.dart
+++ b/tests/compiler/dart2js/tdiv_test.dart
@@ -85,10 +85,10 @@
}
asyncTest(() => Future.wait([
- check(TEST1),
- check(TEST2),
- check(TEST3),
- check(TEST4),
- check(TEST5),
- ]));
+ check(TEST1),
+ check(TEST2),
+ check(TEST3),
+ check(TEST4),
+ check(TEST5),
+ ]));
}
diff --git a/tests/compiler/dart2js/token_naming_test.dart b/tests/compiler/dart2js/token_naming_test.dart
index 7f99d5e..3a3248e 100644
--- a/tests/compiler/dart2js/token_naming_test.dart
+++ b/tests/compiler/dart2js/token_naming_test.dart
@@ -39,7 +39,7 @@
Expect.equals("h_", forwardN(scope, 63 * 5));
// Likewise, ensure we skip s.
Expect.equals("t_", forwardN(scope, 63 * 11));
- // And wrap around another digit.
+ // And wrap around another digit.
Expect.equals("a__", forwardN(scope, 63 * 33));
// Test a filtered scope.
diff --git a/tests/compiler/dart2js/top_level_closure_tree_shake_test.dart b/tests/compiler/dart2js/top_level_closure_tree_shake_test.dart
index 6c3ae37..158a1bc 100644
--- a/tests/compiler/dart2js/top_level_closure_tree_shake_test.dart
+++ b/tests/compiler/dart2js/top_level_closure_tree_shake_test.dart
@@ -26,13 +26,12 @@
}
""";
-
main() {
asyncTest(() => Future.wait([
- compileAll(TEST_ONE).then((String generated) {
- Expect.isFalse(generated.contains('Tarantula!'),
- "failed to remove 'foo'");
- Expect.isTrue(generated.contains('Coelacanth!'));
- }),
- ]));
+ compileAll(TEST_ONE).then((String generated) {
+ Expect.isFalse(
+ generated.contains('Tarantula!'), "failed to remove 'foo'");
+ Expect.isTrue(generated.contains('Coelacanth!'));
+ }),
+ ]));
}
diff --git a/tests/compiler/dart2js/tree_shaking_test.dart b/tests/compiler/dart2js/tree_shaking_test.dart
index 541956f..ceec29c 100644
--- a/tests/compiler/dart2js/tree_shaking_test.dart
+++ b/tests/compiler/dart2js/tree_shaking_test.dart
@@ -27,8 +27,8 @@
void main() {
asyncTest(() => compileAll(TEST).then((generated) {
- Expect.isTrue(generated.contains('return 42'));
- Expect.isTrue(generated.contains('return 54'));
- Expect.isFalse(generated.contains('return 68'));
- }));
+ Expect.isTrue(generated.contains('return 42'));
+ Expect.isTrue(generated.contains('return 54'));
+ Expect.isFalse(generated.contains('return 68'));
+ }));
}
diff --git a/tests/compiler/dart2js/trust_type_annotations_test.dart b/tests/compiler/dart2js/trust_type_annotations_test.dart
index a90d7e5..6e86bc0 100644
--- a/tests/compiler/dart2js/trust_type_annotations_test.dart
+++ b/tests/compiler/dart2js/trust_type_annotations_test.dart
@@ -50,30 +50,31 @@
Uri uri = new Uri(scheme: 'source');
var compiler = compilerFor(TEST, uri, trustTypeAnnotations: true);
asyncTest(() => compiler.run(uri).then((_) {
- var typesInferrer = compiler.globalInference.typesInferrer;
+ var typesInferrer = compiler.globalInference.typesInferrer;
- ClassElement classA = findElement(compiler, "A");
+ ClassElement classA = findElement(compiler, "A");
- checkReturn(String name, TypeMask type) {
- var element = classA.lookupMember(name);
- var mask = typesInferrer.getReturnTypeOfElement(element);
- Expect.isTrue(type.containsMask(
- typesInferrer.getReturnTypeOfElement(element), compiler.world));
- }
- checkType(String name, type) {
- var element = classA.lookupMember(name);
- Expect.isTrue(type.containsMask(
- typesInferrer.getTypeOfElement(element), compiler.world));
- }
+ checkReturn(String name, TypeMask type) {
+ var element = classA.lookupMember(name);
+ var mask = typesInferrer.getReturnTypeOfElement(element);
+ Expect.isTrue(type.containsMask(
+ typesInferrer.getReturnTypeOfElement(element), compiler.world));
+ }
- var intMask = new TypeMask.subtype(
- compiler.coreClasses.intClass, compiler.world);
+ checkType(String name, type) {
+ var element = classA.lookupMember(name);
+ Expect.isTrue(type.containsMask(
+ typesInferrer.getTypeOfElement(element), compiler.world));
+ }
- checkReturn('foo', intMask);
- checkReturn('faa', intMask);
- checkType('aField', intMask);
- checkReturn('bar', intMask);
- checkReturn('baz', intMask);
- checkReturn('tear', intMask);
- }));
+ var intMask =
+ new TypeMask.subtype(compiler.coreClasses.intClass, compiler.world);
+
+ checkReturn('foo', intMask);
+ checkReturn('faa', intMask);
+ checkType('aField', intMask);
+ checkReturn('bar', intMask);
+ checkReturn('baz', intMask);
+ checkReturn('tear', intMask);
+ }));
}
diff --git a/tests/compiler/dart2js/type_checker_test.dart b/tests/compiler/dart2js/type_checker_test.dart
index d471cf1..0ac90d1 100644
--- a/tests/compiler/dart2js/type_checker_test.dart
+++ b/tests/compiler/dart2js/type_checker_test.dart
@@ -10,15 +10,11 @@
import 'package:compiler/src/dart_types.dart';
import 'package:compiler/src/diagnostics/messages.dart';
import 'package:compiler/src/elements/elements.dart';
-import 'package:compiler/src/elements/modelx.dart' show
- ClassElementX,
- CompilationUnitElementX,
- ElementX,
- FunctionElementX;
+import 'package:compiler/src/elements/modelx.dart'
+ show ClassElementX, CompilationUnitElementX, ElementX, FunctionElementX;
import 'package:compiler/src/io/source_file.dart';
-import 'package:compiler/src/resolution/tree_elements.dart' show
- TreeElements,
- TreeElementMapping;
+import 'package:compiler/src/resolution/tree_elements.dart'
+ show TreeElements, TreeElementMapping;
import 'package:compiler/src/parser/element_listener.dart';
import 'package:compiler/src/tree/tree.dart';
import 'package:compiler/src/typechecker.dart';
@@ -33,42 +29,44 @@
final MessageKind UNDEFINED_GETTER = MessageKind.UNDEFINED_GETTER;
main() {
- List tests = [testSimpleTypes,
- testReturn,
- testFor,
- testSyncForIn,
- testAsyncForIn,
- testWhile,
- testTry,
- testSwitch,
- testEnumSwitch,
- testOperators,
- testConstructorInvocationArgumentCount,
- testConstructorInvocationArgumentTypes,
- testMethodInvocationArgumentCount,
- testMethodInvocations,
- testMethodInvocationsInClass,
- testGetterSetterInvocation,
- // testNewExpression,
- testConditionalExpression,
- testIfStatement,
- testThis,
- testSuper,
- testOperatorsAssignability,
- testFieldInitializers,
- testTypeVariableExpressions,
- testTypeVariableLookup1,
- testTypeVariableLookup2,
- testTypeVariableLookup3,
- testFunctionTypeLookup,
- testTypedefLookup,
- testTypeLiteral,
- testInitializers,
- testTypePromotionHints,
- testFunctionCall,
- testCascade,
- testAwait,
- testAsyncReturn];
+ List tests = [
+ testSimpleTypes,
+ testReturn,
+ testFor,
+ testSyncForIn,
+ testAsyncForIn,
+ testWhile,
+ testTry,
+ testSwitch,
+ testEnumSwitch,
+ testOperators,
+ testConstructorInvocationArgumentCount,
+ testConstructorInvocationArgumentTypes,
+ testMethodInvocationArgumentCount,
+ testMethodInvocations,
+ testMethodInvocationsInClass,
+ testGetterSetterInvocation,
+ // testNewExpression,
+ testConditionalExpression,
+ testIfStatement,
+ testThis,
+ testSuper,
+ testOperatorsAssignability,
+ testFieldInitializers,
+ testTypeVariableExpressions,
+ testTypeVariableLookup1,
+ testTypeVariableLookup2,
+ testTypeVariableLookup3,
+ testFunctionTypeLookup,
+ testTypedefLookup,
+ testTypeLiteral,
+ testInitializers,
+ testTypePromotionHints,
+ testFunctionCall,
+ testCascade,
+ testAwait,
+ testAsyncReturn
+ ];
asyncTest(() => Future.forEach(tests, (test) => setup(test)));
}
@@ -130,7 +128,6 @@
// check("for (String s in true) {}", MessageKind.UNDEFINED_METHOD);
}
-
testSyncForIn(MockCompiler compiler) {
String script = """
class HasUntypedIterator {
@@ -180,111 +177,217 @@
foo.ensureResolved(compiler.resolution);
FunctionElement method = foo.lookupLocalMember('forIn');
- analyzeIn(compiler, method, """{
+ analyzeIn(
+ compiler,
+ method,
+ """{
for (var e in <String>[]) {}
}""");
- analyzeIn(compiler, method, """{
+ analyzeIn(
+ compiler,
+ method,
+ """{
for (String e in <String>[]) {}
}""");
- analyzeIn(compiler, method, """{
+ analyzeIn(
+ compiler,
+ method,
+ """{
for (int e in <String>[]) {}
- }""", hints: MessageKind.FORIN_NOT_ASSIGNABLE);
- analyzeIn(compiler, method, """{
+ }""",
+ hints: MessageKind.FORIN_NOT_ASSIGNABLE);
+ analyzeIn(
+ compiler,
+ method,
+ """{
for (int e in []) {}
}""");
- analyzeIn(compiler, method, """{
+ analyzeIn(
+ compiler,
+ method,
+ """{
for (var e in new HasUntypedIterator()) {}
}""");
- analyzeIn(compiler, method, """{
+ analyzeIn(
+ compiler,
+ method,
+ """{
for (String e in new HasUntypedIterator()) {}
}""");
- analyzeIn(compiler, method, """{
+ analyzeIn(
+ compiler,
+ method,
+ """{
for (int e in new HasUntypedIterator()) {}
}""");
- analyzeIn(compiler, method, """{
+ analyzeIn(
+ compiler,
+ method,
+ """{
for (var e in new HasIntIterator()) {}
}""");
- analyzeIn(compiler, method, """{
+ analyzeIn(
+ compiler,
+ method,
+ """{
for (String e in new HasIntIterator()) {}
- }""", hints: MessageKind.FORIN_NOT_ASSIGNABLE);
- analyzeIn(compiler, method, """{
+ }""",
+ hints: MessageKind.FORIN_NOT_ASSIGNABLE);
+ analyzeIn(
+ compiler,
+ method,
+ """{
for (int e in new HasIntIterator()) {}
}""");
- analyzeIn(compiler, method, """{
+ analyzeIn(
+ compiler,
+ method,
+ """{
for (var e in new HasNoIterator()) {}
- }""", warnings: MessageKind.UNDEFINED_GETTER);
- analyzeIn(compiler, method, """{
+ }""",
+ warnings: MessageKind.UNDEFINED_GETTER);
+ analyzeIn(
+ compiler,
+ method,
+ """{
for (String e in new HasNoIterator()) {}
- }""", warnings: MessageKind.UNDEFINED_GETTER);
- analyzeIn(compiler, method, """{
+ }""",
+ warnings: MessageKind.UNDEFINED_GETTER);
+ analyzeIn(
+ compiler,
+ method,
+ """{
for (int e in new HasNoIterator()) {}
- }""", warnings: MessageKind.UNDEFINED_GETTER);
+ }""",
+ warnings: MessageKind.UNDEFINED_GETTER);
- analyzeIn(compiler, method, """{
+ analyzeIn(
+ compiler,
+ method,
+ """{
for (var e in new HasCustomIntIterator()) {}
}""");
- analyzeIn(compiler, method, """{
+ analyzeIn(
+ compiler,
+ method,
+ """{
for (String e in new HasCustomIntIterator()) {}
- }""", hints: MessageKind.FORIN_NOT_ASSIGNABLE);
- analyzeIn(compiler, method, """{
+ }""",
+ hints: MessageKind.FORIN_NOT_ASSIGNABLE);
+ analyzeIn(
+ compiler,
+ method,
+ """{
for (int e in new HasCustomIntIterator()) {}
}""");
- analyzeIn(compiler, method, """{
+ analyzeIn(
+ compiler,
+ method,
+ """{
for (var e in new HasCustomNoCurrentIterator()) {}
- }""", hints: MessageKind.UNDEFINED_GETTER);
- analyzeIn(compiler, method, """{
+ }""",
+ hints: MessageKind.UNDEFINED_GETTER);
+ analyzeIn(
+ compiler,
+ method,
+ """{
for (String e in new HasCustomNoCurrentIterator()) {}
- }""", hints: MessageKind.UNDEFINED_GETTER);
- analyzeIn(compiler, method, """{
+ }""",
+ hints: MessageKind.UNDEFINED_GETTER);
+ analyzeIn(
+ compiler,
+ method,
+ """{
for (int e in new HasCustomNoCurrentIterator()) {}
- }""", hints: MessageKind.UNDEFINED_GETTER);
+ }""",
+ hints: MessageKind.UNDEFINED_GETTER);
- analyzeIn(compiler, method, """{
+ analyzeIn(
+ compiler,
+ method,
+ """{
var localDyn;
for (localDyn in <String>[]) {}
}""");
- analyzeIn(compiler, method, """{
+ analyzeIn(
+ compiler,
+ method,
+ """{
String localString;
for (localString in <String>[]) {}
}""");
- analyzeIn(compiler, method, """{
+ analyzeIn(
+ compiler,
+ method,
+ """{
int localInt;
for (localInt in <String>[]) {}
- }""", hints: MessageKind.FORIN_NOT_ASSIGNABLE);
+ }""",
+ hints: MessageKind.FORIN_NOT_ASSIGNABLE);
- analyzeIn(compiler, method, """{
+ analyzeIn(
+ compiler,
+ method,
+ """{
for (topLevelDyn in <String>[]) {}
}""");
- analyzeIn(compiler, method, """{
+ analyzeIn(
+ compiler,
+ method,
+ """{
for (topLevelString in <String>[]) {}
}""");
- analyzeIn(compiler, method, """{
+ analyzeIn(
+ compiler,
+ method,
+ """{
for (topLevelInt in <String>[]) {}
- }""", hints: MessageKind.FORIN_NOT_ASSIGNABLE);
+ }""",
+ hints: MessageKind.FORIN_NOT_ASSIGNABLE);
- analyzeIn(compiler, method, """{
+ analyzeIn(
+ compiler,
+ method,
+ """{
for (instanceDyn in <String>[]) {}
}""");
- analyzeIn(compiler, method, """{
+ analyzeIn(
+ compiler,
+ method,
+ """{
for (instanceString in <String>[]) {}
}""");
- analyzeIn(compiler, method, """{
+ analyzeIn(
+ compiler,
+ method,
+ """{
for (instanceInt in <String>[]) {}
- }""", hints: MessageKind.FORIN_NOT_ASSIGNABLE);
+ }""",
+ hints: MessageKind.FORIN_NOT_ASSIGNABLE);
- analyzeIn(compiler, method, """{
+ analyzeIn(
+ compiler,
+ method,
+ """{
for (staticDyn in <String>[]) {}
}""");
- analyzeIn(compiler, method, """{
+ analyzeIn(
+ compiler,
+ method,
+ """{
for (staticString in <String>[]) {}
}""");
- analyzeIn(compiler, method, """{
+ analyzeIn(
+ compiler,
+ method,
+ """{
for (staticInt in <String>[]) {}
- }""", hints: MessageKind.FORIN_NOT_ASSIGNABLE);
+ }""",
+ hints: MessageKind.FORIN_NOT_ASSIGNABLE);
}
testAsyncForIn(MockCompiler compiler) {
@@ -313,119 +416,201 @@
foo.ensureResolved(compiler.resolution);
FunctionElement method = foo.lookupLocalMember('forIn');
- analyzeIn(compiler, method, """{
+ analyzeIn(
+ compiler,
+ method,
+ """{
var stream;
await for (var e in stream) {}
}""");
- analyzeIn(compiler, method, """{
+ analyzeIn(
+ compiler,
+ method,
+ """{
var stream;
await for (String e in stream) {}
}""");
- analyzeIn(compiler, method, """{
+ analyzeIn(
+ compiler,
+ method,
+ """{
var stream;
await for (int e in stream) {}
}""");
- analyzeIn(compiler, method, """{
+ analyzeIn(
+ compiler,
+ method,
+ """{
await for (var e in []) {}
- }""", hints: MessageKind.NOT_ASSIGNABLE);
+ }""",
+ hints: MessageKind.NOT_ASSIGNABLE);
- analyzeIn(compiler, method, """{
+ analyzeIn(
+ compiler,
+ method,
+ """{
Stream<String> stream;
await for (var e in stream) {}
}""");
- analyzeIn(compiler, method, """{
+ analyzeIn(
+ compiler,
+ method,
+ """{
Stream<String> stream;
await for (String e in stream) {}
}""");
- analyzeIn(compiler, method, """{
+ analyzeIn(
+ compiler,
+ method,
+ """{
Stream<String> stream;
await for (int e in stream) {}
- }""", hints: MessageKind.FORIN_NOT_ASSIGNABLE);
+ }""",
+ hints: MessageKind.FORIN_NOT_ASSIGNABLE);
- analyzeIn(compiler, method, """{
+ analyzeIn(
+ compiler,
+ method,
+ """{
CustomStream<String> stream;
await for (var e in stream) {}
}""");
- analyzeIn(compiler, method, """{
+ analyzeIn(
+ compiler,
+ method,
+ """{
CustomStream<String> stream;
await for (String e in stream) {}
}""");
- analyzeIn(compiler, method, """{
+ analyzeIn(
+ compiler,
+ method,
+ """{
CustomStream<String> stream;
await for (int e in stream) {}
- }""", hints: MessageKind.FORIN_NOT_ASSIGNABLE);
+ }""",
+ hints: MessageKind.FORIN_NOT_ASSIGNABLE);
- analyzeIn(compiler, method, """{
+ analyzeIn(
+ compiler,
+ method,
+ """{
StringStream stream;
await for (var e in stream) {}
}""");
- analyzeIn(compiler, method, """{
+ analyzeIn(
+ compiler,
+ method,
+ """{
StringStream stream;
await for (String e in stream) {}
}""");
- analyzeIn(compiler, method, """{
+ analyzeIn(
+ compiler,
+ method,
+ """{
StringStream stream;
await for (int e in stream) {}
- }""", hints: MessageKind.FORIN_NOT_ASSIGNABLE);
+ }""",
+ hints: MessageKind.FORIN_NOT_ASSIGNABLE);
- analyzeIn(compiler, method, """{
+ analyzeIn(
+ compiler,
+ method,
+ """{
Stream<String> stream;
var localDyn;
await for (localDyn in stream) {}
}""");
- analyzeIn(compiler, method, """{
+ analyzeIn(
+ compiler,
+ method,
+ """{
Stream<String> stream;
String localString;
await for (localString in stream) {}
}""");
- analyzeIn(compiler, method, """{
+ analyzeIn(
+ compiler,
+ method,
+ """{
Stream<String> stream;
int localInt;
await for (localInt in stream) {}
- }""", hints: MessageKind.FORIN_NOT_ASSIGNABLE);
+ }""",
+ hints: MessageKind.FORIN_NOT_ASSIGNABLE);
- analyzeIn(compiler, method, """{
+ analyzeIn(
+ compiler,
+ method,
+ """{
Stream<String> stream;
await for (topLevelDyn in stream) {}
}""");
- analyzeIn(compiler, method, """{
+ analyzeIn(
+ compiler,
+ method,
+ """{
Stream<String> stream;
await for (topLevelString in stream) {}
}""");
- analyzeIn(compiler, method, """{
+ analyzeIn(
+ compiler,
+ method,
+ """{
Stream<String> stream;
await for (topLevelInt in stream) {}
- }""", hints: MessageKind.FORIN_NOT_ASSIGNABLE);
+ }""",
+ hints: MessageKind.FORIN_NOT_ASSIGNABLE);
- analyzeIn(compiler, method, """{
+ analyzeIn(
+ compiler,
+ method,
+ """{
Stream<String> stream;
await for (instanceDyn in stream) {}
}""");
- analyzeIn(compiler, method, """{
+ analyzeIn(
+ compiler,
+ method,
+ """{
Stream<String> stream;
await for (instanceString in stream) {}
}""");
- analyzeIn(compiler, method, """{
+ analyzeIn(
+ compiler,
+ method,
+ """{
Stream<String> stream;
await for (instanceInt in stream) {}
- }""", hints: MessageKind.FORIN_NOT_ASSIGNABLE);
+ }""",
+ hints: MessageKind.FORIN_NOT_ASSIGNABLE);
- analyzeIn(compiler, method, """{
+ analyzeIn(
+ compiler,
+ method,
+ """{
Stream<String> stream;
await for (staticDyn in stream) {}
}""");
- analyzeIn(compiler, method, """{
+ analyzeIn(
+ compiler,
+ method,
+ """{
Stream<String> stream;
await for (staticString in stream) {}
}""");
- analyzeIn(compiler, method, """{
+ analyzeIn(
+ compiler,
+ method,
+ """{
Stream<String> stream;
await for (staticInt in stream) {}
- }""", hints: MessageKind.FORIN_NOT_ASSIGNABLE);
+ }""",
+ hints: MessageKind.FORIN_NOT_ASSIGNABLE);
}
-
testWhile(MockCompiler compiler) {
check(String code, {warnings}) {
analyze(compiler, code, warnings: warnings);
@@ -456,14 +641,13 @@
check("try { int i = ''; } finally {}", warnings: NOT_ASSIGNABLE);
check("try {} finally { int i = ''; }", warnings: NOT_ASSIGNABLE);
check("try {} on String catch (e) { int i = e; } finally {}",
- warnings: NOT_ASSIGNABLE);
+ warnings: NOT_ASSIGNABLE);
check("try {} catch (e, s) { int i = e; int j = s; } finally {}",
- warnings: NOT_ASSIGNABLE);
+ warnings: NOT_ASSIGNABLE);
check("try {} on String catch (e, s) { int i = e; int j = s; } finally {}",
- warnings: [NOT_ASSIGNABLE, NOT_ASSIGNABLE]);
+ warnings: [NOT_ASSIGNABLE, NOT_ASSIGNABLE]);
}
-
testSwitch(MockCompiler compiler) {
check(String code, {warnings}) {
analyze(compiler, code, warnings: warnings);
@@ -471,13 +655,12 @@
check("switch (0) { case 1: break; case 2: break; }");
check("switch (0) { case 1: int i = ''; break; case 2: break; }",
- warnings: NOT_ASSIGNABLE);
- check("switch (0) { case '': break; }",
- warnings: NOT_ASSIGNABLE);
+ warnings: NOT_ASSIGNABLE);
+ check("switch (0) { case '': break; }", warnings: NOT_ASSIGNABLE);
check("switch ('') { case 1: break; case 2: break; }",
- warnings: [NOT_ASSIGNABLE, NOT_ASSIGNABLE]);
+ warnings: [NOT_ASSIGNABLE, NOT_ASSIGNABLE]);
check("switch (1.5) { case 1: break; case 2: break; }",
- warnings: [NOT_ASSIGNABLE, NOT_ASSIGNABLE]);
+ warnings: [NOT_ASSIGNABLE, NOT_ASSIGNABLE]);
}
testEnumSwitch(MockCompiler compiler) {
@@ -525,42 +708,56 @@
case Enum.C: break;
}""");
- check("""
+ check(
+ """
switch (Enum.A) {
case Enum.B: break;
case Enum.C: break;
-}""", warnings: MessageKind.MISSING_ENUM_CASES);
+}""",
+ warnings: MessageKind.MISSING_ENUM_CASES);
- check("""
+ check(
+ """
switch (Enum.A) {
case Enum.A: break;
case Enum.C: break;
-}""", warnings: MessageKind.MISSING_ENUM_CASES);
+}""",
+ warnings: MessageKind.MISSING_ENUM_CASES);
- check("""
+ check(
+ """
switch (Enum.A) {
case Enum.A: break;
case Enum.B: break;
-}""", warnings: MessageKind.MISSING_ENUM_CASES);
+}""",
+ warnings: MessageKind.MISSING_ENUM_CASES);
- check("""
+ check(
+ """
switch (Enum.A) {
case Enum.A: break;
-}""", warnings: MessageKind.MISSING_ENUM_CASES);
+}""",
+ warnings: MessageKind.MISSING_ENUM_CASES);
- check("""
+ check(
+ """
switch (Enum.A) {
case Enum.B: break;
-}""", warnings: MessageKind.MISSING_ENUM_CASES);
+}""",
+ warnings: MessageKind.MISSING_ENUM_CASES);
- check("""
+ check(
+ """
switch (Enum.A) {
case Enum.C: break;
-}""", warnings: MessageKind.MISSING_ENUM_CASES);
+}""",
+ warnings: MessageKind.MISSING_ENUM_CASES);
- check("""
+ check(
+ """
switch (Enum.A) {
-}""", warnings: MessageKind.MISSING_ENUM_CASES);
+}""",
+ warnings: MessageKind.MISSING_ENUM_CASES);
}
testOperators(MockCompiler compiler) {
@@ -574,22 +771,22 @@
check("{ var i = 1 ${op} 2; }");
check("{ var i = 1; i ${op}= 2; }");
check("{ int i; var j = (i = true) ${op} 2; }",
- warnings: [NOT_ASSIGNABLE, MessageKind.UNDEFINED_OPERATOR]);
+ warnings: [NOT_ASSIGNABLE, MessageKind.UNDEFINED_OPERATOR]);
check("{ int i; var j = 1 ${op} (i = true); }",
- warnings: [NOT_ASSIGNABLE, NOT_ASSIGNABLE]);
+ warnings: [NOT_ASSIGNABLE, NOT_ASSIGNABLE]);
}
for (final op in ['-', '~']) {
check("{ var i = ${op}1; }");
check("{ int i; var j = ${op}(i = true); }",
- warnings: [NOT_ASSIGNABLE, MessageKind.UNDEFINED_OPERATOR]);
+ warnings: [NOT_ASSIGNABLE, MessageKind.UNDEFINED_OPERATOR]);
}
for (final op in ['++', '--']) {
check("{ int i = 1; int j = i${op}; }");
check("{ int i = 1; bool j = i${op}; }", warnings: NOT_ASSIGNABLE);
check("{ bool b = true; bool j = b${op}; }",
- warnings: MessageKind.UNDEFINED_OPERATOR);
+ warnings: MessageKind.UNDEFINED_OPERATOR);
check("{ bool b = true; int j = ${op}b; }",
- warnings: MessageKind.UNDEFINED_OPERATOR);
+ warnings: MessageKind.UNDEFINED_OPERATOR);
}
for (final op in ['||', '&&']) {
check("{ bool b = (true ${op} false); }");
@@ -601,17 +798,15 @@
check("{ bool b = 1 ${op} 2; }");
check("{ int i = 1 ${op} 2; }", warnings: NOT_ASSIGNABLE);
check("{ int i; bool b = (i = true) ${op} 2; }",
- warnings: [NOT_ASSIGNABLE, MessageKind.UNDEFINED_OPERATOR]);
+ warnings: [NOT_ASSIGNABLE, MessageKind.UNDEFINED_OPERATOR]);
check("{ int i; bool b = 1 ${op} (i = true); }",
- warnings: [NOT_ASSIGNABLE, NOT_ASSIGNABLE]);
+ warnings: [NOT_ASSIGNABLE, NOT_ASSIGNABLE]);
}
for (final op in ['==', '!=']) {
check("{ bool b = 1 ${op} 2; }");
check("{ int i = 1 ${op} 2; }", warnings: NOT_ASSIGNABLE);
- check("{ int i; bool b = (i = true) ${op} 2; }",
- warnings: NOT_ASSIGNABLE);
- check("{ int i; bool b = 1 ${op} (i = true); }",
- warnings: NOT_ASSIGNABLE);
+ check("{ int i; bool b = (i = true) ${op} 2; }", warnings: NOT_ASSIGNABLE);
+ check("{ int i; bool b = 1 ${op} (i = true); }", warnings: NOT_ASSIGNABLE);
}
}
@@ -655,31 +850,27 @@
check("new C1(42);");
check("new C1('string');");
check("new C2(42);");
- check("new C2('string');",
- warnings: NOT_ASSIGNABLE);
+ check("new C2('string');", warnings: NOT_ASSIGNABLE);
check("new C3(42);");
- check("new C3('string');",
- warnings: NOT_ASSIGNABLE);
+ check("new C3('string');", warnings: NOT_ASSIGNABLE);
check("new C3.named(42);");
- check("new C3.named('string');",
- warnings: NOT_ASSIGNABLE);
+ check("new C3.named('string');", warnings: NOT_ASSIGNABLE);
}
void testMethodInvocationArgumentCount(MockCompiler compiler) {
compiler.parseScript(CLASS_WITH_METHODS);
check(String text, [expectedWarnings]) {
- analyze(compiler,
- "{ ClassWithMethods c; $text }",
- warnings: expectedWarnings);
+ analyze(compiler, "{ ClassWithMethods c; $text }",
+ warnings: expectedWarnings);
}
check("c.untypedNoArgumentMethod(1);", MessageKind.ADDITIONAL_ARGUMENT);
check("c.untypedOneArgumentMethod();", MessageKind.MISSING_ARGUMENT);
check("c.untypedOneArgumentMethod(1, 1);", MessageKind.ADDITIONAL_ARGUMENT);
check("c.untypedTwoArgumentMethod();", MessageKind.MISSING_ARGUMENT);
- check("c.untypedTwoArgumentMethod(1, 2, 3);",
- MessageKind.ADDITIONAL_ARGUMENT);
+ check(
+ "c.untypedTwoArgumentMethod(1, 2, 3);", MessageKind.ADDITIONAL_ARGUMENT);
check("c.intNoArgumentMethod(1);", MessageKind.ADDITIONAL_ARGUMENT);
check("c.intOneArgumentMethod();", MessageKind.MISSING_ARGUMENT);
check("c.intOneArgumentMethod(1, 1);", MessageKind.ADDITIONAL_ARGUMENT);
@@ -691,40 +882,39 @@
check("c.intOneArgumentOneOptionalMethod(0);");
check("c.intOneArgumentOneOptionalMethod(0, 1);");
check("c.intOneArgumentOneOptionalMethod(0, 1, 2);",
- [MessageKind.ADDITIONAL_ARGUMENT]);
+ [MessageKind.ADDITIONAL_ARGUMENT]);
check("c.intOneArgumentOneOptionalMethod(0, 1, c: 2);",
- [MessageKind.NAMED_ARGUMENT_NOT_FOUND]);
+ [MessageKind.NAMED_ARGUMENT_NOT_FOUND]);
check("c.intOneArgumentOneOptionalMethod(0, b: 1);",
- [MessageKind.NAMED_ARGUMENT_NOT_FOUND]);
- check("c.intOneArgumentOneOptionalMethod(a: 0, b: 1);",
- [MessageKind.NAMED_ARGUMENT_NOT_FOUND,
- MessageKind.NAMED_ARGUMENT_NOT_FOUND,
- MessageKind.MISSING_ARGUMENT]);
+ [MessageKind.NAMED_ARGUMENT_NOT_FOUND]);
+ check("c.intOneArgumentOneOptionalMethod(a: 0, b: 1);", [
+ MessageKind.NAMED_ARGUMENT_NOT_FOUND,
+ MessageKind.NAMED_ARGUMENT_NOT_FOUND,
+ MessageKind.MISSING_ARGUMENT
+ ]);
check("c.intTwoOptionalMethod();");
check("c.intTwoOptionalMethod(0);");
check("c.intTwoOptionalMethod(0, 1);");
check("c.intTwoOptionalMethod(0, 1, 2);", [MessageKind.ADDITIONAL_ARGUMENT]);
- check("c.intTwoOptionalMethod(a: 0);",
- [MessageKind.NAMED_ARGUMENT_NOT_FOUND]);
+ check(
+ "c.intTwoOptionalMethod(a: 0);", [MessageKind.NAMED_ARGUMENT_NOT_FOUND]);
check("c.intTwoOptionalMethod(0, b: 1);",
- [MessageKind.NAMED_ARGUMENT_NOT_FOUND]);
+ [MessageKind.NAMED_ARGUMENT_NOT_FOUND]);
check("c.intOneArgumentOneNamedMethod();", [MessageKind.MISSING_ARGUMENT]);
check("c.intOneArgumentOneNamedMethod(0);");
check("c.intOneArgumentOneNamedMethod(0, b: 1);");
- check("c.intOneArgumentOneNamedMethod(b: 1);",
- [MessageKind.MISSING_ARGUMENT]);
+ check(
+ "c.intOneArgumentOneNamedMethod(b: 1);", [MessageKind.MISSING_ARGUMENT]);
check("c.intOneArgumentOneNamedMethod(0, b: 1, c: 2);",
- [MessageKind.NAMED_ARGUMENT_NOT_FOUND]);
+ [MessageKind.NAMED_ARGUMENT_NOT_FOUND]);
check("c.intOneArgumentOneNamedMethod(0, 1);",
- [MessageKind.ADDITIONAL_ARGUMENT]);
+ [MessageKind.ADDITIONAL_ARGUMENT]);
check("c.intOneArgumentOneNamedMethod(0, 1, c: 2);",
- [MessageKind.ADDITIONAL_ARGUMENT,
- MessageKind.NAMED_ARGUMENT_NOT_FOUND]);
+ [MessageKind.ADDITIONAL_ARGUMENT, MessageKind.NAMED_ARGUMENT_NOT_FOUND]);
check("c.intOneArgumentOneNamedMethod(a: 1, b: 1);",
- [MessageKind.NAMED_ARGUMENT_NOT_FOUND,
- MessageKind.MISSING_ARGUMENT]);
+ [MessageKind.NAMED_ARGUMENT_NOT_FOUND, MessageKind.MISSING_ARGUMENT]);
check("c.intTwoNamedMethod();");
check("c.intTwoNamedMethod(a: 0);");
@@ -734,26 +924,25 @@
check("c.intTwoNamedMethod(0);", [MessageKind.ADDITIONAL_ARGUMENT]);
check("c.intTwoNamedMethod(c: 2);", [MessageKind.NAMED_ARGUMENT_NOT_FOUND]);
check("c.intTwoNamedMethod(a: 0, c: 2);",
- [MessageKind.NAMED_ARGUMENT_NOT_FOUND]);
+ [MessageKind.NAMED_ARGUMENT_NOT_FOUND]);
check("c.intTwoNamedMethod(a: 0, b: 1, c: 2);",
- [MessageKind.NAMED_ARGUMENT_NOT_FOUND]);
+ [MessageKind.NAMED_ARGUMENT_NOT_FOUND]);
check("c.intTwoNamedMethod(c: 2, b: 1, a: 0);",
- [MessageKind.NAMED_ARGUMENT_NOT_FOUND]);
+ [MessageKind.NAMED_ARGUMENT_NOT_FOUND]);
check("c.intTwoNamedMethod(0, b: 1);", [MessageKind.ADDITIONAL_ARGUMENT]);
check("c.intTwoNamedMethod(0, 1);",
- [MessageKind.ADDITIONAL_ARGUMENT,
- MessageKind.ADDITIONAL_ARGUMENT]);
+ [MessageKind.ADDITIONAL_ARGUMENT, MessageKind.ADDITIONAL_ARGUMENT]);
check("c.intTwoNamedMethod(0, c: 2);",
- [MessageKind.ADDITIONAL_ARGUMENT,
- MessageKind.NAMED_ARGUMENT_NOT_FOUND]);
+ [MessageKind.ADDITIONAL_ARGUMENT, MessageKind.NAMED_ARGUMENT_NOT_FOUND]);
}
void testMethodInvocations(MockCompiler compiler) {
compiler.parseScript(CLASS_WITH_METHODS);
- check(String text, [expectedWarnings]){
- analyze(compiler,
- """{
+ check(String text, [expectedWarnings]) {
+ analyze(
+ compiler,
+ """{
ClassWithMethods c;
SubClass d;
var e;
@@ -762,7 +951,8 @@
int localMethod(String str) { return 0; }
$text
}
- """, warnings: expectedWarnings);
+ """,
+ warnings: expectedWarnings);
}
check("int k = c.untypedNoArgumentMethod();");
@@ -786,21 +976,16 @@
check("ClassWithMethods x = d.untypedTwoArgumentMethod(i, d);");
check("int k = c.intNoArgumentMethod();");
- check("ClassWithMethods x = c.intNoArgumentMethod();",
- NOT_ASSIGNABLE);
+ check("ClassWithMethods x = c.intNoArgumentMethod();", NOT_ASSIGNABLE);
check("int k = c.intOneArgumentMethod(c);", NOT_ASSIGNABLE);
- check("ClassWithMethods x = c.intOneArgumentMethod(1);",
- NOT_ASSIGNABLE);
- check("int k = c.intOneArgumentMethod('string');",
- NOT_ASSIGNABLE);
+ check("ClassWithMethods x = c.intOneArgumentMethod(1);", NOT_ASSIGNABLE);
+ check("int k = c.intOneArgumentMethod('string');", NOT_ASSIGNABLE);
check("int k = c.intOneArgumentMethod(i);");
- check("int k = c.intTwoArgumentMethod(1, 'string');",
- NOT_ASSIGNABLE);
+ check("int k = c.intTwoArgumentMethod(1, 'string');", NOT_ASSIGNABLE);
check("int k = c.intTwoArgumentMethod(i, j);");
- check("ClassWithMethods x = c.intTwoArgumentMethod(i, j);",
- NOT_ASSIGNABLE);
+ check("ClassWithMethods x = c.intTwoArgumentMethod(i, j);", NOT_ASSIGNABLE);
check("c.functionField();");
check("d.functionField();");
@@ -815,27 +1000,21 @@
check("c.untypedField(1);");
check("d.untypedField('string');");
-
- check("c.intOneArgumentOneOptionalMethod('');",
- NOT_ASSIGNABLE);
+ check("c.intOneArgumentOneOptionalMethod('');", NOT_ASSIGNABLE);
check("c.intOneArgumentOneOptionalMethod('', '');",
- [NOT_ASSIGNABLE, NOT_ASSIGNABLE]);
+ [NOT_ASSIGNABLE, NOT_ASSIGNABLE]);
check("c.intTwoOptionalMethod('');", NOT_ASSIGNABLE);
- check("c.intTwoOptionalMethod('', '');",
- [NOT_ASSIGNABLE, NOT_ASSIGNABLE]);
+ check("c.intTwoOptionalMethod('', '');", [NOT_ASSIGNABLE, NOT_ASSIGNABLE]);
- check("c.intOneArgumentOneNamedMethod('');",
- NOT_ASSIGNABLE);
+ check("c.intOneArgumentOneNamedMethod('');", NOT_ASSIGNABLE);
check("c.intOneArgumentOneNamedMethod('', b: '');",
- [NOT_ASSIGNABLE, NOT_ASSIGNABLE]);
+ [NOT_ASSIGNABLE, NOT_ASSIGNABLE]);
check("c.intTwoNamedMethod(a: '');", NOT_ASSIGNABLE);
check("c.intTwoNamedMethod(b: '');", NOT_ASSIGNABLE);
- check("c.intTwoNamedMethod(a: '', b: '');",
- [NOT_ASSIGNABLE, NOT_ASSIGNABLE]);
- check("c.intTwoNamedMethod(b: '', a: '');",
- [NOT_ASSIGNABLE, NOT_ASSIGNABLE]);
+ check("c.intTwoNamedMethod(a: '', b: '');", [NOT_ASSIGNABLE, NOT_ASSIGNABLE]);
+ check("c.intTwoNamedMethod(b: '', a: '');", [NOT_ASSIGNABLE, NOT_ASSIGNABLE]);
// Invocation of dynamic variable.
check("e();");
@@ -865,17 +1044,14 @@
check("(String foo){}('string');");
check("int k = int bar(String foo){ return 0; }('string');");
check("int k = String bar(String foo){ return foo; }('string');",
- NOT_ASSIGNABLE);
+ NOT_ASSIGNABLE);
// Static invocations.
- check("ClassWithMethods.staticMethod();",
- MessageKind.MISSING_ARGUMENT);
- check("ClassWithMethods.staticMethod(1);",
- NOT_ASSIGNABLE);
+ check("ClassWithMethods.staticMethod();", MessageKind.MISSING_ARGUMENT);
+ check("ClassWithMethods.staticMethod(1);", NOT_ASSIGNABLE);
check("ClassWithMethods.staticMethod('string');");
check("int k = ClassWithMethods.staticMethod('string');");
- check("String k = ClassWithMethods.staticMethod('string');",
- NOT_ASSIGNABLE);
+ check("String k = ClassWithMethods.staticMethod('string');", NOT_ASSIGNABLE);
// Invocation on dynamic variable.
check("e.foo();");
@@ -904,20 +1080,20 @@
Element d = SubClass.lookupLocalMember('method');
assert(d != null);
- check(Element element, String text, [expectedWarnings]){
- analyzeIn(compiler,
- element,
- """{
+ check(Element element, String text, [expectedWarnings]) {
+ analyzeIn(
+ compiler,
+ element,
+ """{
var e;
int i;
int j;
int localMethod(String str) { return 0; }
$text
}""",
- warnings: expectedWarnings);
+ warnings: expectedWarnings);
}
-
check(c, "int k = untypedNoArgumentMethod();");
check(c, "ClassWithMethods x = untypedNoArgumentMethod();");
check(d, "ClassWithMethods x = untypedNoArgumentMethod();");
@@ -939,21 +1115,17 @@
check(d, "ClassWithMethods x = untypedTwoArgumentMethod(i, this);");
check(c, "int k = intNoArgumentMethod();");
- check(c, "ClassWithMethods x = intNoArgumentMethod();",
- NOT_ASSIGNABLE);
+ check(c, "ClassWithMethods x = intNoArgumentMethod();", NOT_ASSIGNABLE);
check(c, "int k = intOneArgumentMethod('');", NOT_ASSIGNABLE);
- check(c, "ClassWithMethods x = intOneArgumentMethod(1);",
- NOT_ASSIGNABLE);
- check(c, "int k = intOneArgumentMethod('string');",
- NOT_ASSIGNABLE);
+ check(c, "ClassWithMethods x = intOneArgumentMethod(1);", NOT_ASSIGNABLE);
+ check(c, "int k = intOneArgumentMethod('string');", NOT_ASSIGNABLE);
check(c, "int k = intOneArgumentMethod(i);");
- check(c, "int k = intTwoArgumentMethod(1, 'string');",
- NOT_ASSIGNABLE);
+ check(c, "int k = intTwoArgumentMethod(1, 'string');", NOT_ASSIGNABLE);
check(c, "int k = intTwoArgumentMethod(i, j);");
- check(c, "ClassWithMethods x = intTwoArgumentMethod(i, j);",
- NOT_ASSIGNABLE);
+ check(
+ c, "ClassWithMethods x = intTwoArgumentMethod(i, j);", NOT_ASSIGNABLE);
check(c, "functionField();");
check(d, "functionField();");
@@ -968,27 +1140,23 @@
check(c, "untypedField(1);");
check(d, "untypedField('string');");
-
- check(c, "intOneArgumentOneOptionalMethod('');",
- NOT_ASSIGNABLE);
+ check(c, "intOneArgumentOneOptionalMethod('');", NOT_ASSIGNABLE);
check(c, "intOneArgumentOneOptionalMethod('', '');",
- [NOT_ASSIGNABLE, NOT_ASSIGNABLE]);
+ [NOT_ASSIGNABLE, NOT_ASSIGNABLE]);
check(c, "intTwoOptionalMethod('');", NOT_ASSIGNABLE);
- check(c, "intTwoOptionalMethod('', '');",
- [NOT_ASSIGNABLE, NOT_ASSIGNABLE]);
+ check(c, "intTwoOptionalMethod('', '');", [NOT_ASSIGNABLE, NOT_ASSIGNABLE]);
- check(c, "intOneArgumentOneNamedMethod('');",
- NOT_ASSIGNABLE);
+ check(c, "intOneArgumentOneNamedMethod('');", NOT_ASSIGNABLE);
check(c, "intOneArgumentOneNamedMethod('', b: '');",
- [NOT_ASSIGNABLE, NOT_ASSIGNABLE]);
+ [NOT_ASSIGNABLE, NOT_ASSIGNABLE]);
check(c, "intTwoNamedMethod(a: '');", NOT_ASSIGNABLE);
check(c, "intTwoNamedMethod(b: '');", NOT_ASSIGNABLE);
check(c, "intTwoNamedMethod(a: '', b: '');",
- [NOT_ASSIGNABLE, NOT_ASSIGNABLE]);
+ [NOT_ASSIGNABLE, NOT_ASSIGNABLE]);
check(c, "intTwoNamedMethod(b: '', a: '');",
- [NOT_ASSIGNABLE, NOT_ASSIGNABLE]);
+ [NOT_ASSIGNABLE, NOT_ASSIGNABLE]);
// Invocation of dynamic variable.
check(c, "e();");
@@ -1018,22 +1186,20 @@
check(c, "(String foo){}('string');");
check(c, "int k = int bar(String foo){ return 0; }('string');");
check(c, "int k = String bar(String foo){ return foo; }('string');",
- NOT_ASSIGNABLE);
+ NOT_ASSIGNABLE);
// Static invocations.
- check(c, "staticMethod();",
- MessageKind.MISSING_ARGUMENT);
- check(c, "staticMethod(1);",
- NOT_ASSIGNABLE);
+ check(c, "staticMethod();", MessageKind.MISSING_ARGUMENT);
+ check(c, "staticMethod(1);", NOT_ASSIGNABLE);
check(c, "staticMethod('string');");
check(c, "int k = staticMethod('string');");
- check(c, "String k = staticMethod('string');",
- NOT_ASSIGNABLE);
+ check(c, "String k = staticMethod('string');", NOT_ASSIGNABLE);
check(d, "staticMethod();", MessageKind.UNDEFINED_METHOD);
check(d, "staticMethod(1);", MessageKind.UNDEFINED_METHOD);
check(d, "staticMethod('string');", MessageKind.UNDEFINED_METHOD);
check(d, "int k = staticMethod('string');", MessageKind.UNDEFINED_METHOD);
- check(d, "String k = staticMethod('string');", MessageKind.UNDEFINED_METHOD);
+ check(
+ d, "String k = staticMethod('string');", MessageKind.UNDEFINED_METHOD);
// Invocation on dynamic variable.
check(c, "e.foo();");
@@ -1046,16 +1212,17 @@
check(c, "foo('string');", MessageKind.UNDEFINED_METHOD);
check(c, "foo(a: 'string');", MessageKind.UNDEFINED_METHOD);
check(c, "foo(a: localMethod(1));",
- [MessageKind.UNDEFINED_METHOD, NOT_ASSIGNABLE]);
+ [MessageKind.UNDEFINED_METHOD, NOT_ASSIGNABLE]);
});
}
void testFunctionCall(MockCompiler compiler) {
compiler.parseScript(CLASS_WITH_METHODS);
- check(String text, [expectedWarnings]){
- analyze(compiler,
- """{
+ check(String text, [expectedWarnings]) {
+ analyze(
+ compiler,
+ """{
ClassWithMethods x;
int localMethod(String str) { return 0; }
String2Int string2int;
@@ -1063,7 +1230,8 @@
SubFunction subFunction;
$text
}
- """, warnings: expectedWarnings);
+ """,
+ warnings: expectedWarnings);
}
check("int k = localMethod.call('');");
@@ -1156,10 +1324,8 @@
check("null ? 1 : 2;");
check("0 ? 1 : 2;", warnings: NOT_ASSIGNABLE);
check("'' ? 1 : 2;", warnings: NOT_ASSIGNABLE);
- check("{ int i; true ? i = 2.7 : 2; }",
- warnings: NOT_ASSIGNABLE);
- check("{ int i; true ? 2 : i = 2.7; }",
- warnings: NOT_ASSIGNABLE);
+ check("{ int i; true ? i = 2.7 : 2; }", warnings: NOT_ASSIGNABLE);
+ check("{ int i; true ? 2 : i = 2.7; }", warnings: NOT_ASSIGNABLE);
check("{ int i; i = true ? 2.7 : 2; }");
compiler.parseScript("""
@@ -1176,14 +1342,12 @@
check("if (true) {}");
check("if (null) {}");
- check("if (0) {}",
- warnings: NOT_ASSIGNABLE);
- check("if ('') {}",
- warnings: NOT_ASSIGNABLE);
+ check("if (0) {}", warnings: NOT_ASSIGNABLE);
+ check("if ('') {}", warnings: NOT_ASSIGNABLE);
check("{ int i = 27; if (true) { i = 2.7; } else {} }",
- warnings: NOT_ASSIGNABLE);
+ warnings: NOT_ASSIGNABLE);
check("{ int i = 27; if (true) {} else { i = 2.7; } }",
- warnings: NOT_ASSIGNABLE);
+ warnings: NOT_ASSIGNABLE);
}
testThis(MockCompiler compiler) {
@@ -1387,19 +1551,14 @@
check('z = z $o z;');
check('z = a $o z;', NOT_ASSIGNABLE);
check('z = z $o b;', NOT_ASSIGNABLE);
- check('z = a $o b;',
- [NOT_ASSIGNABLE, NOT_ASSIGNABLE]);
- check('a = a $o b;',
- [NOT_ASSIGNABLE, NOT_ASSIGNABLE,
- NOT_ASSIGNABLE]);
+ check('z = a $o b;', [NOT_ASSIGNABLE, NOT_ASSIGNABLE]);
+ check('a = a $o b;', [NOT_ASSIGNABLE, NOT_ASSIGNABLE, NOT_ASSIGNABLE]);
}
check('z = !z;');
check('z = !a;', NOT_ASSIGNABLE);
check('a = !z;', NOT_ASSIGNABLE);
- check('a = !a;',
- [NOT_ASSIGNABLE, NOT_ASSIGNABLE]);
-
+ check('a = !a;', [NOT_ASSIGNABLE, NOT_ASSIGNABLE]);
// Tests against MismatchA.
@@ -1422,15 +1581,13 @@
check('b = a++;', NOT_ASSIGNABLE);
// 1 is not applicable to operator +.
// `++a` of type int is not assignable to `b`.
- check('b = ++a;',
- [NOT_ASSIGNABLE, NOT_ASSIGNABLE]);
+ check('b = ++a;', [NOT_ASSIGNABLE, NOT_ASSIGNABLE]);
// 1 is not applicable to operator +.
check('b = a[0]++;', NOT_ASSIGNABLE);
// 1 is not applicable to operator +.
// `++a[0]` of type int is not assignable to `b`.
- check('b = ++a[0];',
- [NOT_ASSIGNABLE, NOT_ASSIGNABLE]);
+ check('b = ++a[0];', [NOT_ASSIGNABLE, NOT_ASSIGNABLE]);
// Tests against: MismatchA operator -(int other) => this;
@@ -1468,9 +1625,7 @@
check('a[""] += b;', NOT_ASSIGNABLE);
// `c` is not applicable to operator [] on `a`.
// `c` is not applicable to operator []= on `a`.
- check('a[c] += b;',
- [NOT_ASSIGNABLE, NOT_ASSIGNABLE]);
-
+ check('a[c] += b;', [NOT_ASSIGNABLE, NOT_ASSIGNABLE]);
// Tests against MismatchB.
@@ -1487,12 +1642,10 @@
// `b` is not assignable to `a[0]`.
check('a[0] += b;', NOT_ASSIGNABLE);
// `0` is not applicable to operator + on `a[0]`.
- check('a[0] += "";',
- [NOT_ASSIGNABLE, NOT_ASSIGNABLE]);
+ check('a[0] += "";', [NOT_ASSIGNABLE, NOT_ASSIGNABLE]);
// `true` is not applicable to operator + on `a[0]`.
// `true` is not assignable to `a[0]`.
- check('a[0] += true;',
- [NOT_ASSIGNABLE, NOT_ASSIGNABLE]);
+ check('a[0] += true;', [NOT_ASSIGNABLE, NOT_ASSIGNABLE]);
}
Future testFieldInitializers(MockCompiler compiler) {
@@ -1503,13 +1656,14 @@
return Future.wait([
check("""int i = 0;"""),
check("""int i = '';""", NOT_ASSIGNABLE),
-
check("""class Class {
int i = 0;
}"""),
- check("""class Class {
+ check(
+ """class Class {
int i = '';
- }""", NOT_ASSIGNABLE),
+ }""",
+ NOT_ASSIGNABLE),
]);
}
@@ -1717,21 +1871,25 @@
Class(int this.a);
}
'''),
- check(r'''class Class {
+ check(
+ r'''class Class {
String a;
Class(int this.a);
}
- ''', NOT_ASSIGNABLE),
+ ''',
+ NOT_ASSIGNABLE),
check(r'''class Class {
var a;
Class(int a) : this.a = a;
}
'''),
- check(r'''class Class {
+ check(
+ r'''class Class {
String a;
Class(int a) : this.a = a;
}
- ''', NOT_ASSIGNABLE),
+ ''',
+ NOT_ASSIGNABLE),
// Check this-calls.
check(r'''class Class {
@@ -1740,24 +1898,28 @@
Class.named(int a) : this(a);
}
'''),
- check(r'''class Class {
+ check(
+ r'''class Class {
String a;
Class(this.a);
Class.named(int a) : this(a);
}
- ''', NOT_ASSIGNABLE),
+ ''',
+ NOT_ASSIGNABLE),
check(r'''class Class {
String a;
Class(var a) : this.a = a;
Class.named(int a) : this(a);
}
'''),
- check(r'''class Class {
+ check(
+ r'''class Class {
String a;
Class(String a) : this.a = a;
Class.named(int a) : this(a);
}
- ''', NOT_ASSIGNABLE),
+ ''',
+ NOT_ASSIGNABLE),
// Check super-calls.
check(r'''class Super {
@@ -1768,14 +1930,16 @@
Class.named(int a) : super(a);
}
'''),
- check(r'''class Super {
+ check(
+ r'''class Super {
String a;
Super(this.a);
}
class Class extends Super {
Class.named(int a) : super(a);
}
- ''', NOT_ASSIGNABLE),
+ ''',
+ NOT_ASSIGNABLE),
check(r'''class Super {
String a;
Super(var a) : this.a = a;
@@ -1784,14 +1948,16 @@
Class.named(int a) : super(a);
}
'''),
- check(r'''class Super {
+ check(
+ r'''class Super {
String a;
Super(String a) : this.a = a;
}
class Class extends Super {
Class.named(int a) : super(a);
}
- ''', NOT_ASSIGNABLE),
+ ''',
+ NOT_ASSIGNABLE),
// Check super-calls involving generics.
check(r'''class Super<T> {
@@ -1802,14 +1968,16 @@
Class.named(int a) : super(a);
}
'''),
- check(r'''class Super<T> {
+ check(
+ r'''class Super<T> {
T a;
Super(this.a);
}
class Class extends Super<String> {
Class.named(int a) : super(a);
}
- ''', NOT_ASSIGNABLE),
+ ''',
+ NOT_ASSIGNABLE),
check(r'''class Super<T> {
T a;
Super(var a) : this.a = a;
@@ -1818,14 +1986,16 @@
Class.named(int a) : super(a);
}
'''),
- check(r'''class Super<T> {
+ check(
+ r'''class Super<T> {
T a;
Super(T a) : this.a = a;
}
class Class extends Super<String> {
Class.named(int a) : super(a);
}
- ''', NOT_ASSIGNABLE),
+ ''',
+ NOT_ASSIGNABLE),
// Check instance creations.
check(r'''class Class {
@@ -1834,24 +2004,28 @@
}
method(int a) => new Class(a);
'''),
- check(r'''class Class {
+ check(
+ r'''class Class {
String a;
Class(this.a);
}
method(int a) => new Class(a);
- ''', NOT_ASSIGNABLE),
+ ''',
+ NOT_ASSIGNABLE),
check(r'''class Class {
String a;
Class(var a) : this.a = a;
}
method(int a) => new Class(a);
'''),
- check(r'''class Class {
+ check(
+ r'''class Class {
String a;
Class(String a) : this.a = a;
}
method(int a) => new Class(a);
- ''', NOT_ASSIGNABLE),
+ ''',
+ NOT_ASSIGNABLE),
// Check instance creations involving generics.
check(r'''class Class<T> {
@@ -1860,24 +2034,28 @@
}
method(int a) => new Class<String>(a);
'''),
- check(r'''class Class<T> {
+ check(
+ r'''class Class<T> {
T a;
Class(this.a);
}
method(int a) => new Class<String>(a);
- ''', NOT_ASSIGNABLE),
+ ''',
+ NOT_ASSIGNABLE),
check(r'''class Class<T> {
T a;
Class(var a) : this.a = a;
}
method(int a) => new Class<String>(a);
'''),
- check(r'''class Class<T> {
+ check(
+ r'''class Class<T> {
T a;
Class(String a) : this.a = a;
}
method(int a) => new Class<String>(a);
- ''', NOT_ASSIGNABLE),
+ ''',
+ NOT_ASSIGNABLE),
]);
}
@@ -1925,8 +2103,7 @@
// String is not assignable to int (the argument type of the operator + on the
// getter) and num (the result type of the operation) is not assignable to
// String (the type of the setter).
- check("variable += '';",
- [NOT_ASSIGNABLE, NOT_ASSIGNABLE]);
+ check("variable += '';", [NOT_ASSIGNABLE, NOT_ASSIGNABLE]);
check("c.instanceField = '';");
check("int v = c.instanceField;");
@@ -1938,8 +2115,7 @@
// String is not assignable to int (the argument type of the operator + on the
// getter) and num (the result type of the operation) is not assignable to
// String (the type of the setter).
- check("c.instanceField += '';",
- [NOT_ASSIGNABLE, NOT_ASSIGNABLE]);
+ check("c.instanceField += '';", [NOT_ASSIGNABLE, NOT_ASSIGNABLE]);
check("Class.staticField = '';");
check("int v = Class.staticField;");
@@ -1951,8 +2127,7 @@
// String is not assignable to int (the argument type of the operator + on the
// getter) and num (the result type of the operation) is not assignable to
// String (the type of the setter).
- check("Class.staticField += '';",
- [NOT_ASSIGNABLE, NOT_ASSIGNABLE]);
+ check("Class.staticField += '';", [NOT_ASSIGNABLE, NOT_ASSIGNABLE]);
check("int v = c.overriddenField;");
check("c.overriddenField = 0;");
@@ -2003,143 +2178,170 @@
''');
check(String text, {warnings, hints, infos}) {
- analyze(compiler,
- '{ $text }',
- warnings: warnings,
- hints: hints,
- infos: infos);
+ analyze(compiler, '{ $text }',
+ warnings: warnings, hints: hints, infos: infos);
}
- check(r'''
+ check(
+ r'''
A a = new B();
if (a is C) {
var x = a.c;
}''',
- warnings: [MessageKind.UNDEFINED_GETTER],
- hints: [MessageKind.NOT_MORE_SPECIFIC_SUBTYPE],
- infos: []);
+ warnings: [MessageKind.UNDEFINED_GETTER],
+ hints: [MessageKind.NOT_MORE_SPECIFIC_SUBTYPE],
+ infos: []);
- check(r'''
+ check(
+ r'''
A a = new B();
if (a is C) {
var x = '${a.c}${a.c}';
}''',
- warnings: [MessageKind.UNDEFINED_GETTER,
- MessageKind.UNDEFINED_GETTER],
- hints: [MessageKind.NOT_MORE_SPECIFIC_SUBTYPE],
- infos: []);
+ warnings: [MessageKind.UNDEFINED_GETTER, MessageKind.UNDEFINED_GETTER],
+ hints: [MessageKind.NOT_MORE_SPECIFIC_SUBTYPE],
+ infos: []);
- check(r'''
+ check(
+ r'''
A a = new B();
if (a is C) {
var x = '${a.d}${a.d}'; // Type promotion wouldn't help.
}''',
- warnings: [MessageKind.UNDEFINED_GETTER,
- MessageKind.UNDEFINED_GETTER],
- hints: [],
- infos: []);
+ warnings: [MessageKind.UNDEFINED_GETTER, MessageKind.UNDEFINED_GETTER],
+ hints: [],
+ infos: []);
- check('''
+ check(
+ '''
D<int> d = new E();
if (d is E) { // Suggest E<int>.
var x = d.e;
}''',
- warnings: [MessageKind.UNDEFINED_GETTER],
- hints: [checkMessage(MessageKind.NOT_MORE_SPECIFIC_SUGGESTION,
- {'shownTypeSuggestion': 'E<int>'})],
- infos: []);
+ warnings: [
+ MessageKind.UNDEFINED_GETTER
+ ],
+ hints: [
+ checkMessage(MessageKind.NOT_MORE_SPECIFIC_SUGGESTION,
+ {'shownTypeSuggestion': 'E<int>'})
+ ],
+ infos: []);
- check('''
+ check(
+ '''
D<int> d = new F();
if (d is F) { // Suggest F<int, dynamic>.
var x = d.f;
}''',
- warnings: [MessageKind.UNDEFINED_GETTER],
- hints: [checkMessage(MessageKind.NOT_MORE_SPECIFIC_SUGGESTION,
- {'shownTypeSuggestion': 'F<int, dynamic>'})],
- infos: []);
+ warnings: [
+ MessageKind.UNDEFINED_GETTER
+ ],
+ hints: [
+ checkMessage(MessageKind.NOT_MORE_SPECIFIC_SUGGESTION,
+ {'shownTypeSuggestion': 'F<int, dynamic>'})
+ ],
+ infos: []);
- check('''
+ check(
+ '''
D<int> d = new G();
if (d is G) { // Suggest G<int>.
var x = d.f;
}''',
- warnings: [MessageKind.UNDEFINED_GETTER],
- hints: [checkMessage(MessageKind.NOT_MORE_SPECIFIC_SUGGESTION,
- {'shownTypeSuggestion': 'G<int>'})],
- infos: []);
+ warnings: [
+ MessageKind.UNDEFINED_GETTER
+ ],
+ hints: [
+ checkMessage(MessageKind.NOT_MORE_SPECIFIC_SUGGESTION,
+ {'shownTypeSuggestion': 'G<int>'})
+ ],
+ infos: []);
- check('''
+ check(
+ '''
F<double, int> f = new G();
if (f is G) { // Cannot suggest a more specific type.
var x = f.g;
}''',
- warnings: [MessageKind.UNDEFINED_GETTER],
- hints: [MessageKind.NOT_MORE_SPECIFIC],
- infos: []);
+ warnings: [MessageKind.UNDEFINED_GETTER],
+ hints: [MessageKind.NOT_MORE_SPECIFIC],
+ infos: []);
- check('''
+ check(
+ '''
D<int> d = new E();
if (d is E) {
var x = d.f; // Type promotion wouldn't help.
}''',
- warnings: [MessageKind.UNDEFINED_GETTER],
- hints: [],
- infos: []);
+ warnings: [MessageKind.UNDEFINED_GETTER],
+ hints: [],
+ infos: []);
- check('''
+ check(
+ '''
A a = new B();
if (a is B) {
a = null;
var x = a.b;
}''',
- warnings: [MessageKind.UNDEFINED_GETTER],
- hints: [MessageKind.POTENTIAL_MUTATION],
- infos: [MessageKind.POTENTIAL_MUTATION_HERE]);
+ warnings: [MessageKind.UNDEFINED_GETTER],
+ hints: [MessageKind.POTENTIAL_MUTATION],
+ infos: [MessageKind.POTENTIAL_MUTATION_HERE]);
- check('''
+ check(
+ '''
A a = new B();
if (a is B) {
a = null;
var x = a.c; // Type promotion wouldn't help.
}''',
- warnings: [MessageKind.UNDEFINED_GETTER],
- hints: [],
- infos: []);
+ warnings: [MessageKind.UNDEFINED_GETTER],
+ hints: [],
+ infos: []);
- check('''
+ check(
+ '''
A a = new B();
local() { a = new A(); }
if (a is B) {
var x = a.b;
}''',
- warnings: [MessageKind.UNDEFINED_GETTER],
- hints: [MessageKind.POTENTIAL_MUTATION_IN_CLOSURE],
- infos: [MessageKind.POTENTIAL_MUTATION_IN_CLOSURE_HERE]);
+ warnings: [MessageKind.UNDEFINED_GETTER],
+ hints: [MessageKind.POTENTIAL_MUTATION_IN_CLOSURE],
+ infos: [MessageKind.POTENTIAL_MUTATION_IN_CLOSURE_HERE]);
- check('''
+ check(
+ '''
A a = new B();
local() { a = new A(); }
if (a is B) {
var x = a.c; // Type promotion wouldn't help.
}''',
- warnings: [MessageKind.UNDEFINED_GETTER],
- hints: [],
- infos: []);
+ warnings: [MessageKind.UNDEFINED_GETTER],
+ hints: [],
+ infos: []);
- check('''
+ check(
+ '''
A a = new B();
if (a is B) {
var x = () => a;
var y = a.b;
}
a = new A();''',
- warnings: [MessageKind.UNDEFINED_GETTER],
- hints: [MessageKind.ACCESSED_IN_CLOSURE],
- infos: [MessageKind.ACCESSED_IN_CLOSURE_HERE,
- MessageKind.POTENTIAL_MUTATION_HERE]);
+ warnings: [
+ MessageKind.UNDEFINED_GETTER
+ ],
+ hints: [
+ MessageKind.ACCESSED_IN_CLOSURE
+ ],
+ infos: [
+ MessageKind.ACCESSED_IN_CLOSURE_HERE,
+ MessageKind.POTENTIAL_MUTATION_HERE
+ ]);
- check('''
+ check(
+ '''
A a = new B();
if (a is B) {
var x = () => a;
@@ -2174,11 +2376,8 @@
''');
check(String text, {warnings, hints, infos}) {
- analyze(compiler,
- '{ $text }',
- warnings: warnings,
- hints: hints,
- infos: infos);
+ analyze(compiler, '{ $text }',
+ warnings: warnings, hints: hints, infos: infos);
}
check('A a = new A()..a;');
@@ -2189,134 +2388,106 @@
check('A a = new A()..b..c..a;');
- check('B b = new A()..a;',
- warnings: NOT_ASSIGNABLE);
+ check('B b = new A()..a;', warnings: NOT_ASSIGNABLE);
- check('B b = new A()..b;',
- warnings: NOT_ASSIGNABLE);
+ check('B b = new A()..b;', warnings: NOT_ASSIGNABLE);
check('B b = new A().b;');
check('new A().b..b;');
- check('new A().b..a;',
- warnings: UNDEFINED_GETTER);
+ check('new A().b..a;', warnings: UNDEFINED_GETTER);
check('B b = new A().b..c;');
- check('C c = new A().b..c;',
- warnings: NOT_ASSIGNABLE);
+ check('C c = new A().b..c;', warnings: NOT_ASSIGNABLE);
check('A a = new A()..a = new A();');
check('A a = new A()..b = new B();');
- check('B b = new A()..b = new B();',
- warnings: NOT_ASSIGNABLE);
+ check('B b = new A()..b = new B();', warnings: NOT_ASSIGNABLE);
- check('A a = new A()..b = new A();',
- warnings: NOT_ASSIGNABLE);
+ check('A a = new A()..b = new A();', warnings: NOT_ASSIGNABLE);
check('AFunc a = new C().afunc();');
- check('AFunc a = new C()..afunc();',
- warnings: NOT_ASSIGNABLE);
+ check('AFunc a = new C()..afunc();', warnings: NOT_ASSIGNABLE);
check('C c = new C()..afunc();');
check('A a = new C().afunc()();');
- check('A a = new C()..afunc()();',
- warnings: NOT_ASSIGNABLE);
+ check('A a = new C()..afunc()();', warnings: NOT_ASSIGNABLE);
- check('AFunc a = new C()..afunc()();',
- warnings: NOT_ASSIGNABLE);
-
+ check('AFunc a = new C()..afunc()();', warnings: NOT_ASSIGNABLE);
check('FuncFunc f = new A().funcfunc();');
- check('A a = new A().funcfunc();',
- warnings: NOT_ASSIGNABLE);
+ check('A a = new A().funcfunc();', warnings: NOT_ASSIGNABLE);
- check('FuncFunc f = new A()..funcfunc();',
- warnings: NOT_ASSIGNABLE);
+ check('FuncFunc f = new A()..funcfunc();', warnings: NOT_ASSIGNABLE);
check('A a = new A()..funcfunc();');
- check('FuncFunc f = new A()..funcfunc()();',
- warnings: NOT_ASSIGNABLE);
+ check('FuncFunc f = new A()..funcfunc()();', warnings: NOT_ASSIGNABLE);
check('A a = new A()..funcfunc()();');
- check('FuncFunc f = new A()..funcfunc()()();',
- warnings: NOT_ASSIGNABLE);
+ check('FuncFunc f = new A()..funcfunc()()();', warnings: NOT_ASSIGNABLE);
check('A a = new A()..funcfunc()()();');
-
check('''A a;
a = new A()..a = a = new A()..c.afunc();''');
check('''A a = new A()..b = new B()..c.afunc();''');
- check('''A a = new A()..b = new A()..c.afunc();''',
- warnings: NOT_ASSIGNABLE);
+ check('''A a = new A()..b = new A()..c.afunc();''', warnings: NOT_ASSIGNABLE);
check('''A a = new A()..b = new A()..c.afunc()();''',
- warnings: NOT_ASSIGNABLE);
+ warnings: NOT_ASSIGNABLE);
check('''A a = new A()..b = new A()..c.afunc()().b;''',
- warnings: NOT_ASSIGNABLE);
+ warnings: NOT_ASSIGNABLE);
- check('A a = new A().afunc()()[0].afunc();',
- warnings: NOT_ASSIGNABLE);
+ check('A a = new A().afunc()()[0].afunc();', warnings: NOT_ASSIGNABLE);
- check('C c = new A().afunc()()[0].afunc();',
- warnings: NOT_ASSIGNABLE);
+ check('C c = new A().afunc()()[0].afunc();', warnings: NOT_ASSIGNABLE);
check('AFunc a = new A().afunc()()[0].afunc();');
check('A a = new A()..afunc()()[0].afunc();');
- check('C c = new A()..afunc()()[0].afunc();',
- warnings: NOT_ASSIGNABLE);
+ check('C c = new A()..afunc()()[0].afunc();', warnings: NOT_ASSIGNABLE);
- check('AFunc a = new A()..afunc()()[0].afunc();',
- warnings: NOT_ASSIGNABLE);
+ check('AFunc a = new A()..afunc()()[0].afunc();', warnings: NOT_ASSIGNABLE);
- check('A a = new A().afunc()()[0]..afunc();',
- warnings: NOT_ASSIGNABLE);
+ check('A a = new A().afunc()()[0]..afunc();', warnings: NOT_ASSIGNABLE);
check('C c = new A().afunc()()[0]..afunc();');
- check('AFunc a = new A().afunc()()[0]..afunc();',
- warnings: NOT_ASSIGNABLE);
+ check('AFunc a = new A().afunc()()[0]..afunc();', warnings: NOT_ASSIGNABLE);
check('A a = new A()..afunc()()[0]..afunc();');
- check('C c = new A()..afunc()()[0]..afunc();',
- warnings: NOT_ASSIGNABLE);
+ check('C c = new A()..afunc()()[0]..afunc();', warnings: NOT_ASSIGNABLE);
- check('AFunc a = new A()..afunc()()[0]..afunc();',
- warnings: NOT_ASSIGNABLE);
+ check('AFunc a = new A()..afunc()()[0]..afunc();', warnings: NOT_ASSIGNABLE);
- check('new A()[0] = new A();',
- warnings: NOT_ASSIGNABLE);
+ check('new A()[0] = new A();', warnings: NOT_ASSIGNABLE);
check('new A()[0] = new C();');
- check('new A().a[0] = new A();',
- warnings: NOT_ASSIGNABLE);
+ check('new A().a[0] = new A();', warnings: NOT_ASSIGNABLE);
check('new A().a[0] = new C();');
- check('new A()..a[0] = new A();',
- warnings: NOT_ASSIGNABLE);
+ check('new A()..a[0] = new A();', warnings: NOT_ASSIGNABLE);
check('new A()..a[0] = new C();');
- check('new A()..afunc()()[0] = new A();',
- warnings: NOT_ASSIGNABLE);
+ check('new A()..afunc()()[0] = new A();', warnings: NOT_ASSIGNABLE);
check('new A()..afunc()()[0] = new C();');
}
@@ -2352,6 +2523,7 @@
Future check(String code, [expectedWarnings]) {
return analyzeTopLevel(code, expectedWarnings);
}
+
return Future.wait([
check("Future<int> foo() async { return; }"),
check("Future<int> foo() async { return null; }"),
@@ -2360,35 +2532,33 @@
check("Future<int> foo() async { return new Future.value(); }"),
check("Future<int> foo() async { return new Future<int>.value(); }"),
check("Future<int> foo() async { return new Future<String>.value(); }",
- NOT_ASSIGNABLE),
+ NOT_ASSIGNABLE),
check("""
Future<int> foo() async { return new Future<Future<int>>.value(); }
"""),
check("void foo() async { return; }"),
check("void foo() async { return 0; }", MessageKind.RETURN_VALUE_IN_VOID),
check("void foo() async { return new Future.value(); }",
- MessageKind.RETURN_VALUE_IN_VOID),
+ MessageKind.RETURN_VALUE_IN_VOID),
check("int foo() async { return; }"),
check("int foo() async { return 0; }", NOT_ASSIGNABLE),
- check("int foo() async { return new Future<int>.value(); }",
- NOT_ASSIGNABLE),
-
+ check(
+ "int foo() async { return new Future<int>.value(); }", NOT_ASSIGNABLE),
check("Future<int> foo() async => null;"),
check("Future<int> foo() async => 0;"),
check("Future<int> foo() async => '';", NOT_ASSIGNABLE),
check("Future<int> foo() async => new Future.value();"),
check("Future<int> foo() async => new Future<int>.value();"),
check("Future<int> foo() async => new Future<String>.value();",
- NOT_ASSIGNABLE),
+ NOT_ASSIGNABLE),
check("""
Future<int> foo() async => new Future<Future<int>>.value();
"""),
check("void foo() async => 0;", MessageKind.RETURN_VALUE_IN_VOID),
check("void foo() async => new Future.value();",
- MessageKind.RETURN_VALUE_IN_VOID),
+ MessageKind.RETURN_VALUE_IN_VOID),
check("int foo() async => 0;", NOT_ASSIGNABLE),
- check("int foo() async => new Future<int>.value();",
- NOT_ASSIGNABLE),
+ check("int foo() async => new Future<int>.value();", NOT_ASSIGNABLE),
check("Iterable<int> foo() sync* { return; }"),
check("Stream<int> foo() async* { return; }"),
]);
@@ -2437,7 +2607,7 @@
}
Node parseExpression(String text) =>
- parseBodyCode(text, (parser, token) => parser.parseExpression(token));
+ parseBodyCode(text, (parser, token) => parser.parseExpression(token));
const Map<String, String> ALT_SOURCE = const <String, String>{
'num': r'''
@@ -2474,8 +2644,8 @@
};
Future setup(test(MockCompiler compiler)) {
- MockCompiler compiler = new MockCompiler.internal(
- coreSource: ALT_SOURCE, enableAsyncAwait: true);
+ MockCompiler compiler =
+ new MockCompiler.internal(coreSource: ALT_SOURCE, enableAsyncAwait: true);
return compiler.init("import 'dart:async';").then((_) => test(compiler));
}
@@ -2488,7 +2658,7 @@
analyzeTopLevel(String text, [expectedWarnings]) {
if (expectedWarnings == null) expectedWarnings = [];
- if (expectedWarnings is !List) expectedWarnings = [expectedWarnings];
+ if (expectedWarnings is! List) expectedWarnings = [expectedWarnings];
MockCompiler compiler = new MockCompiler.internal(enableAsyncAwait: true);
compiler.diagnosticHandler = createHandler(compiler, text);
@@ -2504,8 +2674,8 @@
TreeElements mapping;
// Resolve all declarations and members.
for (Link<Element> elements = topLevelElements;
- !elements.isEmpty;
- elements = elements.tail) {
+ !elements.isEmpty;
+ elements = elements.tail) {
element = elements.head;
if (element.isClass) {
ClassElementX classElement = element;
@@ -2542,30 +2712,28 @@
* a list of [MessageKind]s. If [hints] and [infos] are [:null:] the
* corresponding message kinds are ignored.
*/
-analyze(MockCompiler compiler,
- String text,
- {errors, warnings, List hints, List infos,
- bool flushDeferred: false}) {
+analyze(MockCompiler compiler, String text,
+ {errors, warnings, List hints, List infos, bool flushDeferred: false}) {
if (warnings == null) warnings = [];
- if (warnings is !List) warnings = [warnings];
+ if (warnings is! List) warnings = [warnings];
if (errors == null) errors = [];
- if (errors is !List) errors = [errors];
+ if (errors is! List) errors = [errors];
compiler.diagnosticHandler = createHandler(compiler, text);
Token tokens = scan(text);
- NodeListener listener = new NodeListener(
- const ScannerOptions(), compiler.reporter, null);
+ NodeListener listener =
+ new NodeListener(const ScannerOptions(), compiler.reporter, null);
Parser parser = new Parser(listener, new MockParserOptions());
parser.parseStatement(tokens);
Node node = listener.popNode();
- Element compilationUnit =
- new CompilationUnitElementX(new Script(null, null, null), compiler.mainApp);
+ Element compilationUnit = new CompilationUnitElementX(
+ new Script(null, null, null), compiler.mainApp);
Element function = new MockElement(compilationUnit);
TreeElements elements = compiler.resolveNodeStatement(node, function);
compiler.enqueuer.resolution.emptyDeferredQueueForTesting();
- TypeCheckerVisitor checker = new TypeCheckerVisitor(
- compiler, elements, compiler.types);
+ TypeCheckerVisitor checker =
+ new TypeCheckerVisitor(compiler, elements, compiler.types);
DiagnosticCollector collector = compiler.diagnosticCollector;
collector.clear();
checker.analyze(node);
@@ -2584,31 +2752,29 @@
int begin = message.begin;
int end = message.end;
SourceFile sourceFile = new StringSourceFile.fromName('analysis', text);
- print(sourceFile.getLocationMessage(message.message.toString(),
- begin, end));
+ print(
+ sourceFile.getLocationMessage(message.message.toString(), begin, end));
}
}
-analyzeIn(MockCompiler compiler,
- FunctionElement element,
- String text,
- {warnings, hints}) {
+analyzeIn(MockCompiler compiler, FunctionElement element, String text,
+ {warnings, hints}) {
if (warnings == null) warnings = [];
- if (warnings is !List) warnings = [warnings];
+ if (warnings is! List) warnings = [warnings];
if (hints == null) hints = [];
- if (hints is !List) hints = [hints];
+ if (hints is! List) hints = [hints];
compiler.resolver.resolve(element);
Token tokens = scan(text);
- NodeListener listener = new NodeListener(
- const ScannerOptions(), compiler.reporter, null);
+ NodeListener listener =
+ new NodeListener(const ScannerOptions(), compiler.reporter, null);
Parser parser = new Parser(listener, new MockParserOptions(),
asyncAwaitKeywordsEnabled: element.asyncMarker != AsyncMarker.SYNC);
parser.parseStatement(tokens);
Node node = listener.popNode();
TreeElements elements = compiler.resolveNodeStatement(node, element);
- TypeCheckerVisitor checker = new TypeCheckerVisitor(
- compiler, elements, compiler.types);
+ TypeCheckerVisitor checker =
+ new TypeCheckerVisitor(compiler, elements, compiler.types);
DiagnosticCollector collector = compiler.diagnosticCollector;
collector.clear();
checker.analyze(node);
diff --git a/tests/compiler/dart2js/type_combination_test.dart b/tests/compiler/dart2js/type_combination_test.dart
index 5c72f356..5a32503 100644
--- a/tests/compiler/dart2js/type_combination_test.dart
+++ b/tests/compiler/dart2js/type_combination_test.dart
@@ -47,13 +47,12 @@
TypeMask jsIndexableOrNull;
TypeMask jsInterceptorOrNull;
-
class Pair {
final first;
final second;
Pair(this.first, this.second);
int get hashCode => first.hashCode * 47 + second.hashCode;
- bool operator==(Pair other) =>
+ bool operator ==(Pair other) =>
identical(first, other.first) && identical(second, other.second);
}
@@ -76,8 +75,7 @@
var r1 = operate(type1, type2);
var r2 = operate(type2, type1);
- Expect.equals(result, r1,
- "Unexpected result of $name($type1,$type2)");
+ Expect.equals(result, r1, "Unexpected result of $name($type1,$type2)");
Expect.equals(r1, r2, 'Symmetry violation of $name($type1,$type2)');
}
@@ -102,8 +100,8 @@
}
void testUnion(MockCompiler compiler) {
- RuleSet ruleSet = new RuleSet('union',
- (t1, t2) => simplify(t1.union(t2, compiler.world), compiler));
+ RuleSet ruleSet = new RuleSet(
+ 'union', (t1, t2) => simplify(t1.union(t2, compiler.world), compiler));
rule(type1, type2, result) => ruleSet.rule(type1, type2, result);
check(type1, type2, predicate) => ruleSet.check(type1, type2, predicate);
@@ -415,8 +413,8 @@
void testIntersection(MockCompiler compiler) {
JavaScriptBackend backend = compiler.backend;
BackendHelpers helpers = backend.helpers;
- RuleSet ruleSet = new RuleSet('intersection',
- (t1, t2) => t1.intersection(t2, compiler.world));
+ RuleSet ruleSet = new RuleSet(
+ 'intersection', (t1, t2) => t1.intersection(t2, compiler.world));
rule(type1, type2, result) => ruleSet.rule(type1, type2, result);
rule(emptyType, emptyType, emptyType);
@@ -556,10 +554,10 @@
rule(jsIndexable, jsUnmodifiableArray, jsUnmodifiableArray);
rule(jsIndexable, nonPrimitive1, emptyType);
rule(jsIndexable, nonPrimitive2, emptyType);
- rule(jsIndexable, potentialArray, new TypeMask.nonNullSubtype(
- helpers.jsArrayClass, compiler.world));
- rule(jsIndexable, potentialString, new TypeMask.nonNullSubtype(
- helpers.jsStringClass, compiler.world));
+ rule(jsIndexable, potentialArray,
+ new TypeMask.nonNullSubtype(helpers.jsArrayClass, compiler.world));
+ rule(jsIndexable, potentialString,
+ new TypeMask.nonNullSubtype(helpers.jsStringClass, compiler.world));
rule(jsIndexable, jsBooleanOrNull, emptyType);
rule(jsIndexable, jsNumberOrNull, emptyType);
rule(jsIndexable, jsIntegerOrNull, emptyType);
@@ -724,11 +722,10 @@
}
void testRegressions(MockCompiler compiler) {
- TypeMask nonNullPotentialString = new TypeMask.nonNullSubtype(
- patternClass, compiler.world);
- Expect.equals(
- potentialString, jsStringOrNull.union(
- nonNullPotentialString, compiler.world));
+ TypeMask nonNullPotentialString =
+ new TypeMask.nonNullSubtype(patternClass, compiler.world);
+ Expect.equals(potentialString,
+ jsStringOrNull.union(nonNullPotentialString, compiler.world));
}
void main() {
@@ -743,63 +740,54 @@
helpers.interceptorsLibrary.forEachLocalMember((element) {
if (element.isClass) {
element.ensureResolved(compiler.resolution);
- backend.registerInstantiatedType(
- element.rawType,
- compiler.enqueuer.resolution,
- compiler.globalDependencies);
+ backend.registerInstantiatedType(element.rawType,
+ compiler.enqueuer.resolution, compiler.globalDependencies);
}
});
ClassElement patternImplClass = compiler.mainApp.find('PatternImpl');
patternImplClass.ensureResolved(compiler.resolution);
- backend.registerInstantiatedType(
- compiler.coreTypes.mapType(),
- compiler.enqueuer.resolution,
- compiler.globalDependencies);
- backend.registerInstantiatedType(
- compiler.coreTypes.functionType,
- compiler.enqueuer.resolution,
- compiler.globalDependencies);
- backend.registerInstantiatedType(
- patternImplClass.rawType,
- compiler.enqueuer.resolution,
- compiler.globalDependencies);
+ backend.registerInstantiatedType(compiler.coreTypes.mapType(),
+ compiler.enqueuer.resolution, compiler.globalDependencies);
+ backend.registerInstantiatedType(compiler.coreTypes.functionType,
+ compiler.enqueuer.resolution, compiler.globalDependencies);
+ backend.registerInstantiatedType(patternImplClass.rawType,
+ compiler.enqueuer.resolution, compiler.globalDependencies);
compiler.world.populate();
// Grab hold of a supertype for String so we can produce potential
// string types.
patternClass = compiler.commonElements.coreLibrary.find('Pattern');
- nonPrimitive1 = new TypeMask.nonNullSubtype(
- compiler.coreClasses.mapClass, world);
- nonPrimitive2 = new TypeMask.nonNullSubtype(
- compiler.coreClasses.functionClass, world);
- potentialArray = new TypeMask.subtype(
- compiler.coreClasses.listClass, world);
+ nonPrimitive1 =
+ new TypeMask.nonNullSubtype(compiler.coreClasses.mapClass, world);
+ nonPrimitive2 =
+ new TypeMask.nonNullSubtype(compiler.coreClasses.functionClass, world);
+ potentialArray =
+ new TypeMask.subtype(compiler.coreClasses.listClass, world);
potentialString = new TypeMask.subtype(patternClass, world);
- jsInterceptor = new TypeMask.nonNullSubclass(helpers.jsInterceptorClass,
- world);
+ jsInterceptor =
+ new TypeMask.nonNullSubclass(helpers.jsInterceptorClass, world);
jsArrayOrNull = new TypeMask.subclass(helpers.jsArrayClass, world);
- jsReadableArray = new TypeMask.nonNullSubclass(helpers.jsArrayClass,
- world);
- jsMutableArrayOrNull = new TypeMask.subclass(helpers.jsMutableArrayClass,
- world);
- jsMutableArray = new TypeMask.nonNullSubclass(helpers.jsMutableArrayClass,
- world);
+ jsReadableArray = new TypeMask.nonNullSubclass(helpers.jsArrayClass, world);
+ jsMutableArrayOrNull =
+ new TypeMask.subclass(helpers.jsMutableArrayClass, world);
+ jsMutableArray =
+ new TypeMask.nonNullSubclass(helpers.jsMutableArrayClass, world);
jsFixedArrayOrNull = new TypeMask.exact(helpers.jsFixedArrayClass, world);
jsFixedArray = new TypeMask.nonNullExact(helpers.jsFixedArrayClass, world);
- jsExtendableArrayOrNull = new TypeMask.exact(helpers.jsExtendableArrayClass,
- world);
- jsExtendableArray = new TypeMask.nonNullExact(
- helpers.jsExtendableArrayClass, world);
+ jsExtendableArrayOrNull =
+ new TypeMask.exact(helpers.jsExtendableArrayClass, world);
+ jsExtendableArray =
+ new TypeMask.nonNullExact(helpers.jsExtendableArrayClass, world);
jsUnmodifiableArrayOrNull =
new TypeMask.exact(helpers.jsUnmodifiableArrayClass, world);
jsUnmodifiableArray =
new TypeMask.nonNullExact(helpers.jsUnmodifiableArrayClass, world);
jsIndexableOrNull = new TypeMask.subtype(helpers.jsIndexableClass, world);
jsIndexable = new TypeMask.nonNullSubtype(helpers.jsIndexableClass, world);
- jsInterceptorOrNull = new TypeMask.subclass(helpers.jsInterceptorClass,
- world);
+ jsInterceptorOrNull =
+ new TypeMask.subclass(helpers.jsInterceptorClass, world);
jsStringOrNull = new TypeMask.exact(helpers.jsStringClass, world);
jsString = new TypeMask.nonNullExact(helpers.jsStringClass, world);
jsBoolean = new TypeMask.nonNullExact(helpers.jsBoolClass, world);
@@ -811,14 +799,14 @@
jsIntegerOrNull = new TypeMask.exact(helpers.jsIntClass, world);
jsDoubleOrNull = new TypeMask.exact(helpers.jsDoubleClass, world);
nullType = const TypeMask.empty();
- objectType = new TypeMask.nonNullSubclass(
- compiler.coreClasses.objectClass, world);
+ objectType =
+ new TypeMask.nonNullSubclass(compiler.coreClasses.objectClass, world);
emptyType = const TypeMask.nonNullEmpty();
- dynamicType = new TypeMask.subclass(
- compiler.coreClasses.objectClass, world);
+ dynamicType =
+ new TypeMask.subclass(compiler.coreClasses.objectClass, world);
- Expect.notEquals(emptyType, nonPrimitive1,
- "nonPrimitive1 expected to be non-empty.");
+ Expect.notEquals(
+ emptyType, nonPrimitive1, "nonPrimitive1 expected to be non-empty.");
Expect.notEquals(jsStringOrNull, potentialString,
"potentialString expected not to be exact JSString");
Expect.notEquals(jsArrayOrNull, potentialArray,
diff --git a/tests/compiler/dart2js/type_equals_test.dart b/tests/compiler/dart2js/type_equals_test.dart
index edeacdc..3da5afe 100644
--- a/tests/compiler/dart2js/type_equals_test.dart
+++ b/tests/compiler/dart2js/type_equals_test.dart
@@ -88,31 +88,32 @@
void main() {}
""",
uri,
- analyzeAll: true, analyzeOnly: true);
+ analyzeAll: true,
+ analyzeOnly: true);
asyncTest(() => compiler.run(uri).then((_) {
- test(compiler, "void1", "void2", expect: true);
- test(compiler, "int1", "int2", expect: true);
- test(compiler, "String1", "String2", expect: true);
- test(compiler, "ListInt1", "ListInt2", expect: true);
- test(compiler, "ListString1", "ListString2", expect: true);
- test(compiler, "MapIntString1", "MapIntString2", expect: true);
- test(compiler, "TypeVar1", "TypeVar2", expect: true);
- test(compiler, "Function1a", "Function2a", expect: true);
- test(compiler, "Function1b", "Function2b", expect: true);
- test(compiler, "Typedef1a", "Typedef2a", expect: true);
- test(compiler, "Typedef1b", "Typedef2b", expect: true);
- test(compiler, "Typedef1c", "Typedef2c", expect: true);
+ test(compiler, "void1", "void2", expect: true);
+ test(compiler, "int1", "int2", expect: true);
+ test(compiler, "String1", "String2", expect: true);
+ test(compiler, "ListInt1", "ListInt2", expect: true);
+ test(compiler, "ListString1", "ListString2", expect: true);
+ test(compiler, "MapIntString1", "MapIntString2", expect: true);
+ test(compiler, "TypeVar1", "TypeVar2", expect: true);
+ test(compiler, "Function1a", "Function2a", expect: true);
+ test(compiler, "Function1b", "Function2b", expect: true);
+ test(compiler, "Typedef1a", "Typedef2a", expect: true);
+ test(compiler, "Typedef1b", "Typedef2b", expect: true);
+ test(compiler, "Typedef1c", "Typedef2c", expect: true);
- test(compiler, "void1", "int1", expect: false);
- test(compiler, "int1", "String1", expect: false);
- test(compiler, "String1", "ListInt1", expect: false);
- test(compiler, "ListInt1", "ListString1", expect: false);
- test(compiler, "ListString1", "MapIntString1", expect: false);
- test(compiler, "MapIntString1", "TypeVar1", expect: false);
- test(compiler, "TypeVar1", "Function1a", expect: false);
- test(compiler, "Function1a", "Function1b", expect: false);
- test(compiler, "Function1b", "Typedef1a", expect: false);
- test(compiler, "Typedef1a", "Typedef1b", expect: false);
- test(compiler, "Typedef1b", "Typedef1c", expect: false);
- }));
+ test(compiler, "void1", "int1", expect: false);
+ test(compiler, "int1", "String1", expect: false);
+ test(compiler, "String1", "ListInt1", expect: false);
+ test(compiler, "ListInt1", "ListString1", expect: false);
+ test(compiler, "ListString1", "MapIntString1", expect: false);
+ test(compiler, "MapIntString1", "TypeVar1", expect: false);
+ test(compiler, "TypeVar1", "Function1a", expect: false);
+ test(compiler, "Function1a", "Function1b", expect: false);
+ test(compiler, "Function1b", "Typedef1a", expect: false);
+ test(compiler, "Typedef1a", "Typedef1b", expect: false);
+ test(compiler, "Typedef1b", "Typedef1c", expect: false);
+ }));
}
diff --git a/tests/compiler/dart2js/type_guard_unuser_test.dart b/tests/compiler/dart2js/type_guard_unuser_test.dart
index a6703b9..e2e100e 100644
--- a/tests/compiler/dart2js/type_guard_unuser_test.dart
+++ b/tests/compiler/dart2js/type_guard_unuser_test.dart
@@ -15,7 +15,6 @@
}
""";
-
const String TEST_TWO = r"""
bar(a) {}
foo(d) {
@@ -44,30 +43,30 @@
main() {
asyncTest(() => Future.wait([
- compile(TEST_ONE, entry: 'foo', check: (String generated) {
- RegExp regexp = new RegExp(getIntTypeCheck(anyIdentifier));
- Iterator<Match> matches = regexp.allMatches(generated).iterator;
- checkNumberOfMatches(matches, 0);
- Expect.isTrue(
- generated.contains(
+ compile(TEST_ONE, entry: 'foo', check: (String generated) {
+ RegExp regexp = new RegExp(getIntTypeCheck(anyIdentifier));
+ Iterator<Match> matches = regexp.allMatches(generated).iterator;
+ checkNumberOfMatches(matches, 0);
+ Expect.isTrue(generated.contains(
new RegExp(r'return a === true \? [$A-Z]+\.foo\(2\) : b;')));
- }),
- compile(TEST_TWO, entry: 'foo', check: (String generated) {
- RegExp regexp = new RegExp("foo\\(1\\)");
- Iterator<Match> matches = regexp.allMatches(generated).iterator;
- checkNumberOfMatches(matches, 1);
- }),
- compile(TEST_THREE, entry: 'foo', check: (String generated) {
- RegExp regexp = new RegExp(getNumberTypeCheck('a'));
- Expect.isTrue(regexp.hasMatch(generated));
- regexp = new RegExp(getNumberTypeCheck('b'));
- Expect.isTrue(regexp.hasMatch(generated));
- }),
- compile(TEST_THREE_WITH_BAILOUT, entry: 'foo', check: (String generated) {
- RegExp regexp = new RegExp(getNumberTypeCheck('a'));
- Expect.isTrue(regexp.hasMatch(generated));
- regexp = new RegExp(getNumberTypeCheck('b'));
- Expect.isTrue(regexp.hasMatch(generated));
- })
- ]));
+ }),
+ compile(TEST_TWO, entry: 'foo', check: (String generated) {
+ RegExp regexp = new RegExp("foo\\(1\\)");
+ Iterator<Match> matches = regexp.allMatches(generated).iterator;
+ checkNumberOfMatches(matches, 1);
+ }),
+ compile(TEST_THREE, entry: 'foo', check: (String generated) {
+ RegExp regexp = new RegExp(getNumberTypeCheck('a'));
+ Expect.isTrue(regexp.hasMatch(generated));
+ regexp = new RegExp(getNumberTypeCheck('b'));
+ Expect.isTrue(regexp.hasMatch(generated));
+ }),
+ compile(TEST_THREE_WITH_BAILOUT, entry: 'foo',
+ check: (String generated) {
+ RegExp regexp = new RegExp(getNumberTypeCheck('a'));
+ Expect.isTrue(regexp.hasMatch(generated));
+ regexp = new RegExp(getNumberTypeCheck('b'));
+ Expect.isTrue(regexp.hasMatch(generated));
+ })
+ ]));
}
diff --git a/tests/compiler/dart2js/type_inference3_test.dart b/tests/compiler/dart2js/type_inference3_test.dart
index baefe2c..87b1585 100644
--- a/tests/compiler/dart2js/type_inference3_test.dart
+++ b/tests/compiler/dart2js/type_inference3_test.dart
@@ -16,7 +16,7 @@
main() {
asyncTest(() => compile(TEST_ONE, entry: 'sum', check: (String generated) {
- RegExp regexp = new RegExp(getNumberTypeCheck('(param1|b)'));
- Expect.isTrue(regexp.hasMatch(generated));
- }));
+ RegExp regexp = new RegExp(getNumberTypeCheck('(param1|b)'));
+ Expect.isTrue(regexp.hasMatch(generated));
+ }));
}
diff --git a/tests/compiler/dart2js/type_inference4_test.dart b/tests/compiler/dart2js/type_inference4_test.dart
index e8c4180..48cb603 100644
--- a/tests/compiler/dart2js/type_inference4_test.dart
+++ b/tests/compiler/dart2js/type_inference4_test.dart
@@ -18,13 +18,12 @@
main() {
asyncTest(() => compile(TEST_ONE, entry: 'foo', check: (String generated) {
-
- // Test for absence of an illegal argument exception. This means that the
- // arguments are known to be integers.
- Expect.isFalse(generated.contains('iae'));
- // Also make sure that we are not just in bailout mode without speculative
- // types by grepping for the integer-bailout check on argument j.
- RegExp regexp = new RegExp(getIntTypeCheck('[aji]'));
- Expect.isTrue(regexp.hasMatch(generated));
- }));
+ // Test for absence of an illegal argument exception. This means that the
+ // arguments are known to be integers.
+ Expect.isFalse(generated.contains('iae'));
+ // Also make sure that we are not just in bailout mode without speculative
+ // types by grepping for the integer-bailout check on argument j.
+ RegExp regexp = new RegExp(getIntTypeCheck('[aji]'));
+ Expect.isTrue(regexp.hasMatch(generated));
+ }));
}
diff --git a/tests/compiler/dart2js/type_inference5_test.dart b/tests/compiler/dart2js/type_inference5_test.dart
index 4bf5caa..7d6ef4c 100644
--- a/tests/compiler/dart2js/type_inference5_test.dart
+++ b/tests/compiler/dart2js/type_inference5_test.dart
@@ -17,17 +17,15 @@
main() {
asyncTest(() => compile(TEST_ONE, entry: 'foo', check: (String generated) {
-
- // Test for absence of an illegal argument exception. This means that the
- // arguments are known to be integers.
- Expect.isFalse(generated.contains('iae'));
- // Also make sure that we are not just in bailout mode without speculative
- // types by grepping for the integer-bailout check on argument j.
- var argname =
- new RegExp(r'function(?: [a-z]+)?\(([a-zA-Z0-9_]+)\)')
+ // Test for absence of an illegal argument exception. This means that the
+ // arguments are known to be integers.
+ Expect.isFalse(generated.contains('iae'));
+ // Also make sure that we are not just in bailout mode without speculative
+ // types by grepping for the integer-bailout check on argument j.
+ var argname = new RegExp(r'function(?: [a-z]+)?\(([a-zA-Z0-9_]+)\)')
.firstMatch(generated)[1];
- print(argname);
- RegExp regexp = new RegExp(getIntTypeCheck("(i|$argname)"));
- Expect.isTrue(regexp.hasMatch(generated));
- }));
+ print(argname);
+ RegExp regexp = new RegExp(getIntTypeCheck("(i|$argname)"));
+ Expect.isTrue(regexp.hasMatch(generated));
+ }));
}
diff --git a/tests/compiler/dart2js/type_inference7_test.dart b/tests/compiler/dart2js/type_inference7_test.dart
index af867cc..42b19b0 100644
--- a/tests/compiler/dart2js/type_inference7_test.dart
+++ b/tests/compiler/dart2js/type_inference7_test.dart
@@ -33,9 +33,8 @@
// First parameter is uint31|String|bool.
var mask1 = typesInferrer.getTypeOfElement(foo.parameters[0]);
Expect.isTrue(mask1.isUnion);
- var expectedTypes = new Set.from([commonMasks.uint31Type,
- commonMasks.stringType,
- commonMasks.boolType]);
+ var expectedTypes = new Set.from(
+ [commonMasks.uint31Type, commonMasks.stringType, commonMasks.boolType]);
for (var typeMask in mask1.disjointMasks) {
Expect.isFalse(typeMask.isNullable);
var simpleType = simplify(typeMask, compiler);
diff --git a/tests/compiler/dart2js/type_mask2_test.dart b/tests/compiler/dart2js/type_mask2_test.dart
index 03db580..648cf76 100644
--- a/tests/compiler/dart2js/type_mask2_test.dart
+++ b/tests/compiler/dart2js/type_mask2_test.dart
@@ -8,11 +8,9 @@
import 'package:expect/expect.dart';
import 'package:async_helper/async_helper.dart';
import 'type_test_helper.dart';
-import 'package:compiler/src/elements/elements.dart'
- show Element, ClassElement;
+import 'package:compiler/src/elements/elements.dart' show Element, ClassElement;
import 'package:compiler/src/types/types.dart';
-import 'package:compiler/src/world.dart' show
- ClassWorld;
+import 'package:compiler/src/world.dart' show ClassWorld;
isCheckedMode() {
try {
@@ -31,13 +29,12 @@
});
}
-checkMasks(ClassWorld classWorld,
- List<ClassElement> allClasses,
- List<FlatTypeMask> masks,
- {FlatTypeMask result,
- List<FlatTypeMask> disjointMasks,
- FlatTypeMask flattened,
- List<ClassElement> containedClasses}) {
+checkMasks(ClassWorld classWorld, List<ClassElement> allClasses,
+ List<FlatTypeMask> masks,
+ {FlatTypeMask result,
+ List<FlatTypeMask> disjointMasks,
+ FlatTypeMask flattened,
+ List<ClassElement> containedClasses}) {
List<FlatTypeMask> disjoint = <FlatTypeMask>[];
UnionTypeMask.unionOfHelper(masks, disjoint, classWorld);
Expect.listEquals(disjointMasks, disjoint,
@@ -47,14 +44,16 @@
// behaviour in unchecked mode is not defined and thus cannot be
// reliably tested.
if (isCheckedMode()) {
- Expect.throws(() => UnionTypeMask.flatten(disjoint, classWorld),
- (e) => e is AssertionError,
- 'Expect assertion failure on flattening of $disjoint.');
+ Expect.throws(
+ () => UnionTypeMask.flatten(disjoint, classWorld),
+ (e) => e is AssertionError,
+ 'Expect assertion failure on flattening of $disjoint.');
}
} else {
- TypeMask flattenResult =
- UnionTypeMask.flatten(disjoint, classWorld);
- Expect.equals(flattened, flattenResult,
+ TypeMask flattenResult = UnionTypeMask.flatten(disjoint, classWorld);
+ Expect.equals(
+ flattened,
+ flattenResult,
'Unexpected flattening of $disjoint: '
'$flattenResult, expected $flattened.');
}
@@ -62,12 +61,14 @@
if (result == null) {
Expect.isTrue(union is UnionTypeMask,
'Expected union of $masks to be a union-type: $union.');
- Expect.listEquals(disjointMasks, union.disjointMasks,
+ Expect.listEquals(
+ disjointMasks,
+ union.disjointMasks,
'Unexpected union masks: '
'${union.disjointMasks}, expected $disjointMasks.');
} else {
- Expect.equals(result, union,
- 'Unexpected union of $masks: $union, expected $result.');
+ Expect.equals(
+ result, union, 'Unexpected union of $masks: $union, expected $result.');
}
if (containedClasses != null) {
for (ClassElement cls in allClasses) {
@@ -79,13 +80,13 @@
'$union not expected to contain $cls.');
}
}
-
}
return union;
}
-Future testUnionTypeMaskFlatten() async {
- TypeEnvironment env = await TypeEnvironment.create(r"""
+Future testUnionTypeMaskFlatten() async {
+ TypeEnvironment env = await TypeEnvironment.create(
+ r"""
class A {}
class B {}
class C extends A {}
@@ -115,14 +116,11 @@
List<ClassElement> allClasses = <ClassElement>[Object_, A, B, C, D, E];
check(List<FlatTypeMask> masks,
- {FlatTypeMask result,
- List<FlatTypeMask> disjointMasks,
- FlatTypeMask flattened,
- List<ClassElement> containedClasses}) {
- return checkMasks(
- classWorld,
- allClasses,
- masks,
+ {FlatTypeMask result,
+ List<FlatTypeMask> disjointMasks,
+ FlatTypeMask flattened,
+ List<ClassElement> containedClasses}) {
+ return checkMasks(classWorld, allClasses, masks,
result: result,
disjointMasks: disjointMasks,
flattened: flattened,
@@ -140,80 +138,71 @@
TypeMask exactD = new TypeMask.nonNullExact(D, classWorld);
TypeMask exactE = new TypeMask.nonNullExact(E, classWorld);
- check([],
- result: empty,
- disjointMasks: [],
- containedClasses: []);
+ check([], result: empty, disjointMasks: [], containedClasses: []);
check([exactA],
- result: exactA,
- disjointMasks: [exactA],
- containedClasses: [A]);
+ result: exactA, disjointMasks: [exactA], containedClasses: [A]);
check([exactA, exactA],
- result: exactA,
- disjointMasks: [exactA],
- containedClasses: [A]);
+ result: exactA, disjointMasks: [exactA], containedClasses: [A]);
check([exactA, exactB],
- disjointMasks: [exactA, exactB],
- flattened: subclassObject,
- containedClasses: [A, B]);
+ disjointMasks: [exactA, exactB],
+ flattened: subclassObject,
+ containedClasses: [A, B]);
check([subclassObject],
- result: subclassObject,
- disjointMasks: [subclassObject],
- containedClasses: [Object_, A, B, C, D, E]);
+ result: subclassObject,
+ disjointMasks: [subclassObject],
+ containedClasses: [Object_, A, B, C, D, E]);
check([subclassObject, exactA],
- disjointMasks: [subclassObject],
- result: subclassObject,
- containedClasses: [Object_, A, B, C, D, E]);
+ disjointMasks: [subclassObject],
+ result: subclassObject,
+ containedClasses: [Object_, A, B, C, D, E]);
check([exactA, exactC],
- disjointMasks: [subclassA],
- result: subclassA,
- containedClasses: [A, C]);
+ disjointMasks: [subclassA], result: subclassA, containedClasses: [A, C]);
check([exactA, exactB, exactC],
- disjointMasks: [subclassA, exactB],
- flattened: subclassObject,
- containedClasses: [A, B, C]);
+ disjointMasks: [subclassA, exactB],
+ flattened: subclassObject,
+ containedClasses: [A, B, C]);
check([exactA, exactD],
- disjointMasks: [subtypeA],
- result: subtypeA,
- containedClasses: [A, C, D, E]);
+ disjointMasks: [subtypeA],
+ result: subtypeA,
+ containedClasses: [A, C, D, E]);
check([exactA, exactB, exactD],
- disjointMasks: [subtypeA, exactB],
- flattened: subclassObject,
- containedClasses: [A, B, C, D, E]);
+ disjointMasks: [subtypeA, exactB],
+ flattened: subclassObject,
+ containedClasses: [A, B, C, D, E]);
check([exactA, exactE],
- disjointMasks: [subtypeA],
- result: subtypeA,
- containedClasses: [A, C, D, E]);
+ disjointMasks: [subtypeA],
+ result: subtypeA,
+ containedClasses: [A, C, D, E]);
check([exactA, exactB, exactE],
- disjointMasks: [subtypeA, exactB],
- flattened: subclassObject,
- containedClasses: [A, B, C, D, E]);
+ disjointMasks: [subtypeA, exactB],
+ flattened: subclassObject,
+ containedClasses: [A, B, C, D, E]);
check([exactB, exactE, exactA],
- disjointMasks: [subclassB, exactA],
- flattened: subclassObject,
- containedClasses: [A, B, E]);
+ disjointMasks: [subclassB, exactA],
+ flattened: subclassObject,
+ containedClasses: [A, B, E]);
check([exactE, exactA, exactB],
- disjointMasks: [subtypeA, exactB],
- flattened: subclassObject,
- containedClasses: [A, B, C, D, E]);
+ disjointMasks: [subtypeA, exactB],
+ flattened: subclassObject,
+ containedClasses: [A, B, C, D, E]);
check([exactE, exactB, exactA],
- disjointMasks: [subclassB, exactA],
- flattened: subclassObject,
- containedClasses: [A, B, E]);
+ disjointMasks: [subclassB, exactA],
+ flattened: subclassObject,
+ containedClasses: [A, B, E]);
}
Future testStringSubtypes() async {
@@ -224,35 +213,34 @@
}
""",
useMockCompiler: false);
- var classWorld = env.compiler.world;
- var backend = env.compiler.backend;
+ var classWorld = env.compiler.world;
+ var backend = env.compiler.backend;
- ClassElement Object_ = env.getElement("Object");
- ClassElement String_ = env.getElement("String");
- ClassElement JSString = backend.helpers.jsStringClass;
+ ClassElement Object_ = env.getElement("Object");
+ ClassElement String_ = env.getElement("String");
+ ClassElement JSString = backend.helpers.jsStringClass;
- List<ClassElement> allClasses = <ClassElement>[Object_, String_];
+ List<ClassElement> allClasses = <ClassElement>[Object_, String_];
- Expect.isFalse(classWorld.isDirectlyInstantiated(Object_));
- Expect.isTrue(classWorld.isIndirectlyInstantiated(Object_));
- Expect.isTrue(classWorld.isInstantiated(Object_));
+ Expect.isFalse(classWorld.isDirectlyInstantiated(Object_));
+ Expect.isTrue(classWorld.isIndirectlyInstantiated(Object_));
+ Expect.isTrue(classWorld.isInstantiated(Object_));
- Expect.isFalse(classWorld.isDirectlyInstantiated(String_));
- Expect.isFalse(classWorld.isIndirectlyInstantiated(String_));
- Expect.isFalse(classWorld.isInstantiated(String_));
+ Expect.isFalse(classWorld.isDirectlyInstantiated(String_));
+ Expect.isFalse(classWorld.isIndirectlyInstantiated(String_));
+ Expect.isFalse(classWorld.isInstantiated(String_));
- Expect.isTrue(classWorld.isDirectlyInstantiated(JSString));
- Expect.isFalse(classWorld.isIndirectlyInstantiated(JSString));
- Expect.isTrue(classWorld.isInstantiated(JSString));
+ Expect.isTrue(classWorld.isDirectlyInstantiated(JSString));
+ Expect.isFalse(classWorld.isIndirectlyInstantiated(JSString));
+ Expect.isTrue(classWorld.isInstantiated(JSString));
- TypeMask subtypeString = new TypeMask.nonNullSubtype(String_, classWorld);
- TypeMask exactJSString = new TypeMask.nonNullExact(JSString, classWorld);
- TypeMask subtypeJSString =
- new TypeMask.nonNullSubtype(JSString, classWorld);
- TypeMask subclassJSString =
- new TypeMask.nonNullSubclass(JSString, classWorld);
+ TypeMask subtypeString = new TypeMask.nonNullSubtype(String_, classWorld);
+ TypeMask exactJSString = new TypeMask.nonNullExact(JSString, classWorld);
+ TypeMask subtypeJSString = new TypeMask.nonNullSubtype(JSString, classWorld);
+ TypeMask subclassJSString =
+ new TypeMask.nonNullSubclass(JSString, classWorld);
- Expect.equals(exactJSString, subtypeString);
- Expect.equals(exactJSString, subtypeJSString);
- Expect.equals(exactJSString, subclassJSString);
+ Expect.equals(exactJSString, subtypeString);
+ Expect.equals(exactJSString, subtypeJSString);
+ Expect.equals(exactJSString, subclassJSString);
}
diff --git a/tests/compiler/dart2js/type_mask_disjoint_test.dart b/tests/compiler/dart2js/type_mask_disjoint_test.dart
index 90d3f53..f27ac57 100644
--- a/tests/compiler/dart2js/type_mask_disjoint_test.dart
+++ b/tests/compiler/dart2js/type_mask_disjoint_test.dart
@@ -40,79 +40,78 @@
main() {
asyncTest(() => compiler.run(uri).then((_) {
+ // Empty
+ check(' ! ', ' ! '); // both non-null
+ check(' ! ', ' '); // one non-null
+ check(' ', ' ! '); // one non-null
+ check(' ', ' ', areDisjoint: false); // null is common
- // Empty
- check(' ! ', ' ! '); // both non-null
- check(' ! ', ' '); // one non-null
- check(' ', ' ! '); // one non-null
- check(' ', ' ', areDisjoint: false); // null is common
+ // Exact
+ check('A!=', 'A!=', areDisjoint: false);
+ check('A!=', 'B!=');
+ check('A!=', 'E!=');
+ check('A =', 'E =', areDisjoint: false); // null is common
+ check('M!=', 'K!=');
+ check('M!=', 'A!=');
- // Exact
- check('A!=', 'A!=', areDisjoint: false);
- check('A!=', 'B!=');
- check('A!=', 'E!=');
- check('A =', 'E =', areDisjoint: false); // null is common
- check('M!=', 'K!=');
- check('M!=', 'A!=');
+ // Exact with subclass
+ check('A!=', 'A!<', areDisjoint: false);
+ check('B!=', 'A!<', areDisjoint: false);
+ check('A!=', 'B!<');
+ check('A!=', 'E!<');
+ check('A =', 'E!<');
+ check('A =', 'E <', areDisjoint: false);
+ check('M!=', 'K!<', areDisjoint: false);
+ check('M!=', 'A!<');
- // Exact with subclass
- check('A!=', 'A!<', areDisjoint: false);
- check('B!=', 'A!<', areDisjoint: false);
- check('A!=', 'B!<');
- check('A!=', 'E!<');
- check('A =', 'E!<');
- check('A =', 'E <', areDisjoint: false);
- check('M!=', 'K!<', areDisjoint: false);
- check('M!=', 'A!<');
+ // Exact with subtype
+ check('A!=', 'A!*', areDisjoint: false);
+ check('B!=', 'A!*', areDisjoint: false);
+ check('A!=', 'B!*');
+ check('A!=', 'E!*');
+ check('A!=', 'I!*');
+ check('J!=', 'H!*', areDisjoint: false);
+ check('M!=', 'K!*', areDisjoint: false);
+ check('M!=', 'A!*', areDisjoint: false);
- // Exact with subtype
- check('A!=', 'A!*', areDisjoint: false);
- check('B!=', 'A!*', areDisjoint: false);
- check('A!=', 'B!*');
- check('A!=', 'E!*');
- check('A!=', 'I!*');
- check('J!=', 'H!*', areDisjoint: false);
- check('M!=', 'K!*', areDisjoint: false);
- check('M!=', 'A!*', areDisjoint: false);
+ // Subclass with subclass
+ check('A!<', 'A!<', areDisjoint: false);
+ check('A!<', 'B!<', areDisjoint: false);
+ check('A!<', 'E!<');
+ check('A!<', 'H!<');
+ check('D!<', 'I!<');
+ check('H!<', 'I!*', areDisjoint: false);
- // Subclass with subclass
- check('A!<', 'A!<', areDisjoint: false);
- check('A!<', 'B!<', areDisjoint: false);
- check('A!<', 'E!<');
- check('A!<', 'H!<');
- check('D!<', 'I!<');
- check('H!<', 'I!*', areDisjoint: false);
+ // Subclass with subtype
+ check('A!<', 'A!*', areDisjoint: false);
+ check('A!<', 'B!*', areDisjoint: false);
+ check('A!<', 'E!*');
+ check('A!<', 'H!*');
+ check('D!<', 'I!*', areDisjoint: false);
- // Subclass with subtype
- check('A!<', 'A!*', areDisjoint: false);
- check('A!<', 'B!*', areDisjoint: false);
- check('A!<', 'E!*');
- check('A!<', 'H!*');
- check('D!<', 'I!*', areDisjoint: false);
+ // Subtype with subtype
+ check('A!*', 'A!*', areDisjoint: false);
+ check('A!*', 'B!*', areDisjoint: false);
+ check('A!*', 'E!*');
+ check('A!*', 'H!*', areDisjoint: false);
+ check('D!*', 'I!*', areDisjoint: false);
- // Subtype with subtype
- check('A!*', 'A!*', areDisjoint: false);
- check('A!*', 'B!*', areDisjoint: false);
- check('A!*', 'E!*');
- check('A!*', 'H!*', areDisjoint: false);
- check('D!*', 'I!*', areDisjoint: false);
+ // Unions!
+ checkUnions(['B!=', 'C!='], ['A!=']);
+ checkUnions(['B!=', 'C!='], ['A =']);
+ checkUnions(['B!=', 'C ='], ['A ='], areDisjoint: false);
- // Unions!
- checkUnions(['B!=', 'C!='], ['A!=']);
- checkUnions(['B!=', 'C!='], ['A =']);
- checkUnions(['B!=', 'C ='], ['A ='], areDisjoint: false);
+ checkUnions(['B!=', 'C!='], ['A!<'], areDisjoint: false);
+ checkUnions(['B!=', 'C!='], ['B!='], areDisjoint: false);
+ checkUnions(['A!<', 'E!<'], ['C!='], areDisjoint: false);
+ checkUnions(['A!<', 'E!<'], ['F!='], areDisjoint: false);
- checkUnions(['B!=', 'C!='], ['A!<'], areDisjoint: false);
- checkUnions(['B!=', 'C!='], ['B!='], areDisjoint: false);
- checkUnions(['A!<', 'E!<'], ['C!='], areDisjoint: false);
- checkUnions(['A!<', 'E!<'], ['F!='], areDisjoint: false);
-
- checkUnions(['A!=', 'E!='], ['C!=', 'F!=']);
- checkUnions(['A!=', 'E!='], ['A!=', 'F!='], areDisjoint: false);
- checkUnions(['B!=', 'E!='], ['A!<', 'F!='], areDisjoint: false);
- checkUnions(['A!<', 'E!<'], ['C!=', 'F!='], areDisjoint: false);
- checkUnions(['A!=', 'E!='], ['C!=', 'F!=']);
- }));
+ checkUnions(['A!=', 'E!='], ['C!=', 'F!=']);
+ checkUnions(['A!=', 'E!='], ['A!=', 'F!='], areDisjoint: false);
+ checkUnions(['B!=', 'E!='], ['A!<', 'F!='], areDisjoint: false);
+ checkUnions(['A!<', 'E!<'], ['C!=', 'F!='], areDisjoint: false);
+ checkUnions(['A!=', 'E!='], ['C!=', 'F!=']);
+ }));
}
/// Checks the expectation of `isDisjoint` for two mask. Also checks that the
@@ -137,7 +136,6 @@
areDisjoint: areDisjoint);
}
-
checkUnions(List descriptors1, List descriptors2, {areDisjoint: true}) {
print('[$descriptors1] & [$descriptors2]');
var m1 = new TypeMask.unionOf(descriptors1.map(maskOf).toList(), world);
@@ -160,28 +158,27 @@
/// "Type =" - nullable exact Type
/// "Type!<" - non-null subclass of Type
/// "Type!*" - non-null subtype of Type
-TypeMask maskOf(String descriptor) =>
- _maskCache.putIfAbsent(descriptor, () {
- Expect.isTrue(descriptor.length >= 3);
- var type = descriptor.substring(0, descriptor.length - 2);
- bool isNullable = descriptor[descriptor.length - 2] != '!';
- bool isExact = descriptor[descriptor.length - 1] == '=';
- bool isSubclass = descriptor[descriptor.length - 1] == '<';
- bool isSubtype = descriptor[descriptor.length - 1] == '*';
+TypeMask maskOf(String descriptor) => _maskCache.putIfAbsent(descriptor, () {
+ Expect.isTrue(descriptor.length >= 3);
+ var type = descriptor.substring(0, descriptor.length - 2);
+ bool isNullable = descriptor[descriptor.length - 2] != '!';
+ bool isExact = descriptor[descriptor.length - 1] == '=';
+ bool isSubclass = descriptor[descriptor.length - 1] == '<';
+ bool isSubtype = descriptor[descriptor.length - 1] == '*';
- if (type == " ") {
- Expect.isFalse(isExact || isSubclass || isSubtype);
- return isNullable ? new TypeMask.empty() : new TypeMask.nonNullEmpty();
- }
+ if (type == " ") {
+ Expect.isFalse(isExact || isSubclass || isSubtype);
+ return isNullable ? new TypeMask.empty() : new TypeMask.nonNullEmpty();
+ }
- Expect.isTrue(isExact || isSubclass || isSubtype);
- var element = _elementCache.putIfAbsent(type,
- () => type == " " ? null : findElement(compiler, type));
+ Expect.isTrue(isExact || isSubclass || isSubtype);
+ var element = _elementCache.putIfAbsent(
+ type, () => type == " " ? null : findElement(compiler, type));
- var mask = isExact
- ? new TypeMask.nonNullExact(element, world)
- : (isSubclass
- ? new TypeMask.nonNullSubclass(element, world)
- : new TypeMask.nonNullSubtype(element, world));
- return isNullable ? mask.nullable() : mask;
- });
+ var mask = isExact
+ ? new TypeMask.nonNullExact(element, world)
+ : (isSubclass
+ ? new TypeMask.nonNullSubclass(element, world)
+ : new TypeMask.nonNullSubtype(element, world));
+ return isNullable ? mask.nullable() : mask;
+ });
diff --git a/tests/compiler/dart2js/type_mask_test.dart b/tests/compiler/dart2js/type_mask_test.dart
index 0547260..29a89ce 100644
--- a/tests/compiler/dart2js/type_mask_test.dart
+++ b/tests/compiler/dart2js/type_mask_test.dart
@@ -24,104 +24,107 @@
var classWorld = compiler.world;
asyncTest(() => compiler.run(uri).then((_) {
- var classA = findElement(compiler, 'A');
- var classB = findElement(compiler, 'B');
- var classC = findElement(compiler, 'C');
- var classD = findElement(compiler, 'D');
+ var classA = findElement(compiler, 'A');
+ var classB = findElement(compiler, 'B');
+ var classC = findElement(compiler, 'C');
+ var classD = findElement(compiler, 'D');
- var exactA = new TypeMask.nonNullExact(classA, classWorld);
- var exactB = new TypeMask.nonNullExact(classB, classWorld);
- var exactC = new TypeMask.nonNullExact(classC, classWorld);
- var exactD = new TypeMask.nonNullExact(classD, classWorld);
+ var exactA = new TypeMask.nonNullExact(classA, classWorld);
+ var exactB = new TypeMask.nonNullExact(classB, classWorld);
+ var exactC = new TypeMask.nonNullExact(classC, classWorld);
+ var exactD = new TypeMask.nonNullExact(classD, classWorld);
- var subclassA = new TypeMask.nonNullSubclass(classA, classWorld);
- var subtypeA = new TypeMask.nonNullSubtype(classA, classWorld);
+ var subclassA = new TypeMask.nonNullSubclass(classA, classWorld);
+ var subtypeA = new TypeMask.nonNullSubtype(classA, classWorld);
- var subclassObject = new TypeMask.nonNullSubclass(
- compiler.coreClasses.objectClass, classWorld);
+ var subclassObject = new TypeMask.nonNullSubclass(
+ compiler.coreClasses.objectClass, classWorld);
- var unionABC = UnionTypeMask.unionOf([exactA, exactB, exactC], classWorld);
- var unionABnC = UnionTypeMask.unionOf([exactA, exactB.nullable(), exactC],
- classWorld);
- var unionAB = UnionTypeMask.unionOf([exactA, exactB], classWorld);
- var unionSubtypeAC = UnionTypeMask.unionOf([subtypeA, exactC], classWorld);
- var unionSubclassAC = UnionTypeMask.unionOf([subclassA, exactC],
- classWorld);
- var unionBCD = UnionTypeMask.unionOf([exactB, exactC, exactD], classWorld);
- var unionBCDn = UnionTypeMask.unionOf([exactB, exactC, exactD.nullable()],
- classWorld);
+ var unionABC =
+ UnionTypeMask.unionOf([exactA, exactB, exactC], classWorld);
+ var unionABnC = UnionTypeMask
+ .unionOf([exactA, exactB.nullable(), exactC], classWorld);
+ var unionAB = UnionTypeMask.unionOf([exactA, exactB], classWorld);
+ var unionSubtypeAC =
+ UnionTypeMask.unionOf([subtypeA, exactC], classWorld);
+ var unionSubclassAC =
+ UnionTypeMask.unionOf([subclassA, exactC], classWorld);
+ var unionBCD =
+ UnionTypeMask.unionOf([exactB, exactC, exactD], classWorld);
+ var unionBCDn = UnionTypeMask
+ .unionOf([exactB, exactC, exactD.nullable()], classWorld);
- Expect.isFalse(unionABC.isNullable);
- Expect.isTrue(unionABnC.isNullable);
- Expect.isFalse(unionBCD.isNullable);
- Expect.isTrue(unionBCDn.isNullable);
+ Expect.isFalse(unionABC.isNullable);
+ Expect.isTrue(unionABnC.isNullable);
+ Expect.isFalse(unionBCD.isNullable);
+ Expect.isTrue(unionBCDn.isNullable);
- rule(a, b, c) => Expect.equals(c, a.isInMask(b, classWorld));
+ rule(a, b, c) => Expect.equals(c, a.isInMask(b, classWorld));
- rule(exactA, exactA, true);
- rule(exactA, exactB, false);
- rule(exactA, exactC, false);
- rule(exactA, subclassA, true);
- rule(exactA, subtypeA, true);
+ rule(exactA, exactA, true);
+ rule(exactA, exactB, false);
+ rule(exactA, exactC, false);
+ rule(exactA, subclassA, true);
+ rule(exactA, subtypeA, true);
- rule(exactB, exactA, false);
- rule(exactB, exactB, true);
- rule(exactB, exactC, false);
- rule(exactB, subclassA, true);
- rule(exactB, subtypeA, true);
+ rule(exactB, exactA, false);
+ rule(exactB, exactB, true);
+ rule(exactB, exactC, false);
+ rule(exactB, subclassA, true);
+ rule(exactB, subtypeA, true);
- rule(exactC, exactA, false);
- rule(exactC, exactB, false);
- rule(exactC, exactC, true);
- rule(exactC, subclassA, false);
- rule(exactC, subtypeA, true);
+ rule(exactC, exactA, false);
+ rule(exactC, exactB, false);
+ rule(exactC, exactC, true);
+ rule(exactC, subclassA, false);
+ rule(exactC, subtypeA, true);
- rule(subclassA, exactA, false);
- rule(subclassA, exactB, false);
- rule(subclassA, exactC, false);
- rule(subclassA, subclassA, true);
- rule(subclassA, subtypeA, true);
+ rule(subclassA, exactA, false);
+ rule(subclassA, exactB, false);
+ rule(subclassA, exactC, false);
+ rule(subclassA, subclassA, true);
+ rule(subclassA, subtypeA, true);
- rule(subtypeA, exactA, false);
- rule(subtypeA, exactB, false);
- rule(subtypeA, exactC, false);
- rule(subtypeA, subclassA, false);
- rule(subtypeA, subtypeA, true);
+ rule(subtypeA, exactA, false);
+ rule(subtypeA, exactB, false);
+ rule(subtypeA, exactC, false);
+ rule(subtypeA, subclassA, false);
+ rule(subtypeA, subtypeA, true);
- rule(unionABC, unionSubtypeAC, true);
- rule(unionSubtypeAC, unionABC, true);
- rule(unionAB, unionSubtypeAC, true);
- rule(unionSubtypeAC, unionAB, false);
- rule(unionABC, unionSubclassAC, true);
- rule(unionSubclassAC, unionABC, true);
- rule(unionAB, unionSubclassAC, true);
- rule(unionSubclassAC, unionAB, false);
- rule(unionAB, subclassA, true);
- rule(subclassA, unionAB, true);
- rule(unionABC, subtypeA, true);
- rule(subtypeA, unionABC, true);
- rule(unionABC, subclassA, false);
- rule(subclassA, unionABC, true);
- rule(unionAB, subclassA, true);
- rule(subclassA, unionAB, true);
+ rule(unionABC, unionSubtypeAC, true);
+ rule(unionSubtypeAC, unionABC, true);
+ rule(unionAB, unionSubtypeAC, true);
+ rule(unionSubtypeAC, unionAB, false);
+ rule(unionABC, unionSubclassAC, true);
+ rule(unionSubclassAC, unionABC, true);
+ rule(unionAB, unionSubclassAC, true);
+ rule(unionSubclassAC, unionAB, false);
+ rule(unionAB, subclassA, true);
+ rule(subclassA, unionAB, true);
+ rule(unionABC, subtypeA, true);
+ rule(subtypeA, unionABC, true);
+ rule(unionABC, subclassA, false);
+ rule(subclassA, unionABC, true);
+ rule(unionAB, subclassA, true);
+ rule(subclassA, unionAB, true);
- rule(exactA, subclassObject, true);
- rule(exactB, subclassObject, true);
- rule(subclassA, subclassObject, true);
- rule(subtypeA, subclassObject, true);
- rule(unionABC, subclassObject, true);
- rule(unionAB, subclassObject, true);
- rule(unionSubtypeAC, subclassObject, true);
- rule(unionSubclassAC, subclassObject, true);
+ rule(exactA, subclassObject, true);
+ rule(exactB, subclassObject, true);
+ rule(subclassA, subclassObject, true);
+ rule(subtypeA, subclassObject, true);
+ rule(unionABC, subclassObject, true);
+ rule(unionAB, subclassObject, true);
+ rule(unionSubtypeAC, subclassObject, true);
+ rule(unionSubclassAC, subclassObject, true);
- rule(unionABnC, unionABC, false);
- rule(unionABC, unionABnC, true);
- rule(exactA.nullable(), unionABnC, true);
- rule(exactA.nullable(), unionABC, false);
- rule(exactB, unionABnC, true);
- rule(unionBCDn, unionBCD, false);
- rule(unionBCD, unionBCDn, true);
- rule(exactB.nullable(), unionBCDn, true);
- rule(exactB.nullable(), unionBCD, false);
- }));
+ rule(unionABnC, unionABC, false);
+ rule(unionABC, unionABnC, true);
+ rule(exactA.nullable(), unionABnC, true);
+ rule(exactA.nullable(), unionABC, false);
+ rule(exactB, unionABnC, true);
+ rule(unionBCDn, unionBCD, false);
+ rule(unionBCD, unionBCDn, true);
+ rule(exactB.nullable(), unionBCDn, true);
+ rule(exactB.nullable(), unionBCD, false);
+ }));
}
diff --git a/tests/compiler/dart2js/type_mask_test_helper.dart b/tests/compiler/dart2js/type_mask_test_helper.dart
index e27c463..0d2d41d 100644
--- a/tests/compiler/dart2js/type_mask_test_helper.dart
+++ b/tests/compiler/dart2js/type_mask_test_helper.dart
@@ -5,8 +5,7 @@
library type_mask_test_helper;
import 'package:compiler/src/types/types.dart';
-import 'package:compiler/src/compiler.dart'
- show Compiler;
+import 'package:compiler/src/compiler.dart' show Compiler;
TypeMask simplify(TypeMask mask, Compiler compiler) {
if (mask is ForwardingTypeMask) {
@@ -16,4 +15,4 @@
} else {
return mask;
}
-}
\ No newline at end of file
+}
diff --git a/tests/compiler/dart2js/type_order_test.dart b/tests/compiler/dart2js/type_order_test.dart
index 87c2aa2..5fa8087 100644
--- a/tests/compiler/dart2js/type_order_test.dart
+++ b/tests/compiler/dart2js/type_order_test.dart
@@ -9,7 +9,7 @@
import 'type_test_helper.dart';
import 'package:compiler/src/dart_types.dart';
import "package:compiler/src/elements/elements.dart"
- show Element, ClassElement, TypedefElement;
+ show Element, ClassElement, TypedefElement;
void main() {
asyncTest(() => TypeEnvironment.create(r"""
@@ -20,53 +20,69 @@
class Y {}
class Z {}
""").then((env) {
+ List types = [];
+ DartType add(DartType type) {
+ types.add(type);
+ return type;
+ }
- List types = [];
- DartType add(DartType type) {
- types.add(type);
- return type;
- }
+ DartType dynamic_ = add(env['dynamic']);
+ DartType void_ = add(env['void']);
- DartType dynamic_ = add(env['dynamic']);
- DartType void_ = add(env['void']);
+ ClassElement A = env.getElement('A');
+ TypedefElement B = env.getElement('B');
+ ClassElement C = env.getElement('C');
+ DartType X = add(env['X']);
+ DartType Y = add(env['Y']);
+ DartType Z = add(env['Z']);
- ClassElement A = env.getElement('A');
- TypedefElement B = env.getElement('B');
- ClassElement C = env.getElement('C');
- DartType X = add(env['X']);
- DartType Y = add(env['Y']);
- DartType Z = add(env['Z']);
+ InterfaceType A_this = add(A.thisType);
+ InterfaceType A_raw = add(A.rawType);
+ TypeVariableType AT = add(A_this.typeArguments[0]);
+ TypeVariableType AS = add(A_this.typeArguments[1]);
+ InterfaceType A_X_Y = add(instantiate(A, [X, Y]));
+ InterfaceType A_Y_X = add(instantiate(A, [Y, X]));
- InterfaceType A_this = add(A.thisType);
- InterfaceType A_raw = add(A.rawType);
- TypeVariableType AT = add(A_this.typeArguments[0]);
- TypeVariableType AS = add(A_this.typeArguments[1]);
- InterfaceType A_X_Y = add(instantiate(A, [X, Y]));
- InterfaceType A_Y_X = add(instantiate(A, [Y, X]));
+ TypedefType B_this = add(B.computeType(env.compiler.resolution));
+ TypedefType B_raw = add(B.rawType);
+ TypeVariableType BT = add(B_this.typeArguments[0]);
+ TypeVariableType BS = add(B_this.typeArguments[1]);
+ FunctionType B_this_alias = add(B.alias);
+ TypedefType B_X_Y = add(instantiate(B, [X, Y]));
+ FunctionType B_X_Y_alias = add(B_X_Y.unaliased);
+ TypedefType B_Y_X = add(instantiate(B, [Y, X]));
+ FunctionType B_Y_X_alias = add(B_Y_X.unaliased);
- TypedefType B_this = add(B.computeType(env.compiler.resolution));
- TypedefType B_raw = add(B.rawType);
- TypeVariableType BT = add(B_this.typeArguments[0]);
- TypeVariableType BS = add(B_this.typeArguments[1]);
- FunctionType B_this_alias = add(B.alias);
- TypedefType B_X_Y = add(instantiate(B, [X, Y]));
- FunctionType B_X_Y_alias = add(B_X_Y.unaliased);
- TypedefType B_Y_X = add(instantiate(B, [Y, X]));
- FunctionType B_Y_X_alias = add(B_Y_X.unaliased);
+ InterfaceType C_this = add(C.thisType);
+ InterfaceType C_raw = add(C.rawType);
+ TypeVariableType CT = add(C_this.typeArguments[0]);
+ TypeVariableType CS = add(C_this.typeArguments[1]);
- InterfaceType C_this = add(C.thisType);
- InterfaceType C_raw = add(C.rawType);
- TypeVariableType CT = add(C_this.typeArguments[0]);
- TypeVariableType CS = add(C_this.typeArguments[1]);
-
- Expect.listEquals(
- [void_, dynamic_,
- A_raw, A_this, A_X_Y, A_Y_X, AT, AS,
- B_raw, B_this, B_X_Y, B_Y_X, BT, BS,
- C_raw, C_this, CT, CS,
- X, Y, Z,
- B_this_alias, B_Y_X_alias, B_X_Y_alias,
- ],
- Types.sorted(types));
- }));
-}
\ No newline at end of file
+ Expect.listEquals([
+ void_,
+ dynamic_,
+ A_raw,
+ A_this,
+ A_X_Y,
+ A_Y_X,
+ AT,
+ AS,
+ B_raw,
+ B_this,
+ B_X_Y,
+ B_Y_X,
+ BT,
+ BS,
+ C_raw,
+ C_this,
+ CT,
+ CS,
+ X,
+ Y,
+ Z,
+ B_this_alias,
+ B_Y_X_alias,
+ B_X_Y_alias,
+ ], Types.sorted(types));
+ }));
+}
diff --git a/tests/compiler/dart2js/type_promotion_test.dart b/tests/compiler/dart2js/type_promotion_test.dart
index b391cf9..a7794e0 100644
--- a/tests/compiler/dart2js/type_promotion_test.dart
+++ b/tests/compiler/dart2js/type_promotion_test.dart
@@ -13,15 +13,16 @@
/// can contain a list of line numbers for keys 'missing' and 'unexpected' for
/// the warnings of each category.
const Map<String, dynamic> TESTS = const {
- 'language/type_promotion_assign_test.dart': null,
- 'language/type_promotion_closure_test.dart': null,
- 'language/type_promotion_functions_test.dart':
- const {'missing': const [62, 63, 64]}, // Issue 14933.
- 'language/type_promotion_local_test.dart': null,
- 'language/type_promotion_logical_and_test.dart': null,
- 'language/type_promotion_more_specific_test.dart': null,
- 'language/type_promotion_multiple_test.dart': null,
- 'language/type_promotion_parameter_test.dart': null,
+ 'language/type_promotion_assign_test.dart': null,
+ 'language/type_promotion_closure_test.dart': null,
+ 'language/type_promotion_functions_test.dart': const {
+ 'missing': const [62, 63, 64]
+ }, // Issue 14933.
+ 'language/type_promotion_local_test.dart': null,
+ 'language/type_promotion_logical_and_test.dart': null,
+ 'language/type_promotion_more_specific_test.dart': null,
+ 'language/type_promotion_multiple_test.dart': null,
+ 'language/type_promotion_parameter_test.dart': null,
};
void main() {
diff --git a/tests/compiler/dart2js/type_representation_test.dart b/tests/compiler/dart2js/type_representation_test.dart
index ce4f3c8..2b16579 100644
--- a/tests/compiler/dart2js/type_representation_test.dart
+++ b/tests/compiler/dart2js/type_representation_test.dart
@@ -9,10 +9,9 @@
import 'type_test_helper.dart';
import 'package:compiler/src/dart_types.dart';
import 'package:compiler/src/js/js.dart';
-import 'package:compiler/src/elements/elements.dart'
- show Element, ClassElement;
+import 'package:compiler/src/elements/elements.dart' show Element, ClassElement;
import 'package:compiler/src/js_backend/js_backend.dart'
- show JavaScriptBackend, TypeRepresentationGenerator;
+ show JavaScriptBackend, TypeRepresentationGenerator;
void main() {
testTypeRepresentations();
@@ -42,216 +41,226 @@
m9(int a, String b, {List<int> c, d}) {}
m10(void f(int a, [b])) {}
""").then((env) {
- TypeRepresentationGenerator typeRepresentation =
- new TypeRepresentationGenerator(env.compiler);
+ TypeRepresentationGenerator typeRepresentation =
+ new TypeRepresentationGenerator(env.compiler);
- Expression onVariable(TypeVariableType variable) {
- return new VariableUse(variable.name);
- }
+ Expression onVariable(TypeVariableType variable) {
+ return new VariableUse(variable.name);
+ }
- String stringify(Expression expression) {
- return prettyPrint(expression, env.compiler);
- }
+ String stringify(Expression expression) {
+ return prettyPrint(expression, env.compiler);
+ }
- void expect(DartType type,
- String expectedRepresentation,
- [String expectedTypedefRepresentation]) {
- bool encodeTypedefName = false;
- Expression expression =
- typeRepresentation.getTypeRepresentation(type, onVariable,
- (x) => encodeTypedefName);
- Expect.stringEquals(expectedRepresentation, stringify(expression));
+ void expect(DartType type, String expectedRepresentation,
+ [String expectedTypedefRepresentation]) {
+ bool encodeTypedefName = false;
+ Expression expression = typeRepresentation.getTypeRepresentation(
+ type, onVariable, (x) => encodeTypedefName);
+ Expect.stringEquals(expectedRepresentation, stringify(expression));
- encodeTypedefName = true;
- expression =
- typeRepresentation.getTypeRepresentation(type, onVariable,
- (x) => encodeTypedefName);
- if (expectedTypedefRepresentation == null) {
- expectedTypedefRepresentation = expectedRepresentation;
- }
- Expect.stringEquals(expectedTypedefRepresentation, stringify(expression));
- }
+ encodeTypedefName = true;
+ expression = typeRepresentation.getTypeRepresentation(
+ type, onVariable, (x) => encodeTypedefName);
+ if (expectedTypedefRepresentation == null) {
+ expectedTypedefRepresentation = expectedRepresentation;
+ }
+ Expect.stringEquals(
+ expectedTypedefRepresentation, stringify(expression));
+ }
- String getJsName(Element cls) {
- Expression name = typeRepresentation.getJavaScriptClassName(cls);
- return stringify(name);
- }
+ String getJsName(Element cls) {
+ Expression name = typeRepresentation.getJavaScriptClassName(cls);
+ return stringify(name);
+ }
- JavaScriptBackend backend = env.compiler.backend;
- String func = backend.namer.functionTypeTag;
- String retvoid = backend.namer.functionTypeVoidReturnTag;
- String ret = backend.namer.functionTypeReturnTypeTag;
- String args = backend.namer.functionTypeRequiredParametersTag;
- String opt = backend.namer.functionTypeOptionalParametersTag;
- String named = backend.namer.functionTypeNamedParametersTag;
- String typedefTag = backend.namer.typedefTag;
+ JavaScriptBackend backend = env.compiler.backend;
+ String func = backend.namer.functionTypeTag;
+ String retvoid = backend.namer.functionTypeVoidReturnTag;
+ String ret = backend.namer.functionTypeReturnTypeTag;
+ String args = backend.namer.functionTypeRequiredParametersTag;
+ String opt = backend.namer.functionTypeOptionalParametersTag;
+ String named = backend.namer.functionTypeNamedParametersTag;
+ String typedefTag = backend.namer.typedefTag;
- ClassElement List_ = env.getElement('List');
- TypeVariableType List_E = List_.typeVariables[0];
- ClassElement Map_ = env.getElement('Map');
- TypeVariableType Map_K = Map_.typeVariables[0];
- TypeVariableType Map_V = Map_.typeVariables[1];
+ ClassElement List_ = env.getElement('List');
+ TypeVariableType List_E = List_.typeVariables[0];
+ ClassElement Map_ = env.getElement('Map');
+ TypeVariableType Map_K = Map_.typeVariables[0];
+ TypeVariableType Map_V = Map_.typeVariables[1];
- DartType Object_ = env['Object'];
- DartType int_ = env['int'];
- DartType String_ = env['String'];
- DartType dynamic_ = env['dynamic'];
- DartType Typedef_ = env['Typedef'];
- DartType Typedef2_ = env['Typedef2'];
- DartType Typedef3_ = env['Typedef3'];
- DartType Typedef4_ = env['Typedef4'];
- DartType Typedef5_ = env['Typedef5'];
- DartType Typedef6_ = env['Typedef6'];
- DartType Typedef7_ = env['Typedef7'];
- DartType Typedef8_ = env['Typedef8'];
- DartType Typedef9_ = env['Typedef9'];
- DartType Typedef10_ = env['Typedef10'];
+ DartType Object_ = env['Object'];
+ DartType int_ = env['int'];
+ DartType String_ = env['String'];
+ DartType dynamic_ = env['dynamic'];
+ DartType Typedef_ = env['Typedef'];
+ DartType Typedef2_ = env['Typedef2'];
+ DartType Typedef3_ = env['Typedef3'];
+ DartType Typedef4_ = env['Typedef4'];
+ DartType Typedef5_ = env['Typedef5'];
+ DartType Typedef6_ = env['Typedef6'];
+ DartType Typedef7_ = env['Typedef7'];
+ DartType Typedef8_ = env['Typedef8'];
+ DartType Typedef9_ = env['Typedef9'];
+ DartType Typedef10_ = env['Typedef10'];
- String List_rep = getJsName(List_);
- String List_E_rep = stringify(onVariable(List_E));
- String Map_rep = getJsName(Map_);
- String Map_K_rep = stringify(onVariable(Map_K));
- String Map_V_rep = stringify(onVariable(Map_V));
+ String List_rep = getJsName(List_);
+ String List_E_rep = stringify(onVariable(List_E));
+ String Map_rep = getJsName(Map_);
+ String Map_K_rep = stringify(onVariable(Map_K));
+ String Map_V_rep = stringify(onVariable(Map_V));
- String Object_rep = getJsName(Object_.element);
- String int_rep = getJsName(int_.element);
- String String_rep = getJsName(String_.element);
+ String Object_rep = getJsName(Object_.element);
+ String int_rep = getJsName(int_.element);
+ String String_rep = getJsName(String_.element);
- String Typedef_rep = getJsName(Typedef_.element);
- String Typedef2_rep = getJsName(Typedef2_.element);
- String Typedef3_rep = getJsName(Typedef3_.element);
- String Typedef4_rep = getJsName(Typedef4_.element);
- String Typedef5_rep = getJsName(Typedef5_.element);
- String Typedef6_rep = getJsName(Typedef6_.element);
- String Typedef7_rep = getJsName(Typedef7_.element);
- String Typedef8_rep = getJsName(Typedef8_.element);
- String Typedef9_rep = getJsName(Typedef9_.element);
- String Typedef10_rep = getJsName(Typedef10_.element);
+ String Typedef_rep = getJsName(Typedef_.element);
+ String Typedef2_rep = getJsName(Typedef2_.element);
+ String Typedef3_rep = getJsName(Typedef3_.element);
+ String Typedef4_rep = getJsName(Typedef4_.element);
+ String Typedef5_rep = getJsName(Typedef5_.element);
+ String Typedef6_rep = getJsName(Typedef6_.element);
+ String Typedef7_rep = getJsName(Typedef7_.element);
+ String Typedef8_rep = getJsName(Typedef8_.element);
+ String Typedef9_rep = getJsName(Typedef9_.element);
+ String Typedef10_rep = getJsName(Typedef10_.element);
- expect(int_, '$int_rep');
- expect(String_, '$String_rep');
- expect(dynamic_, 'null');
+ expect(int_, '$int_rep');
+ expect(String_, '$String_rep');
+ expect(dynamic_, 'null');
- // List<E>
- expect(List_.computeType(env.compiler.resolution),
- '[$List_rep, $List_E_rep]');
- // List
- expect(List_.rawType, '$List_rep');
- // List<dynamic>
- expect(instantiate(List_, [dynamic_]), '$List_rep');
- // List<int>
- expect(instantiate(List_, [int_]), '[$List_rep, $int_rep]');
- // List<Typedef>
- expect(instantiate(List_, [Typedef_]),
- '[$List_rep, {$func: 1, $retvoid: true}]',
- '[$List_rep, {$func: 1, $retvoid: true,'
- ' $typedefTag: $Typedef_rep}]');
- expect(instantiate(List_, [Typedef2_]),
- '[$List_rep, {$func: 1, $ret: $int_rep}]',
- '[$List_rep, {$func: 1, $ret: $int_rep,'
- ' $typedefTag: $Typedef2_rep}]');
- expect(instantiate(List_, [Typedef3_]),
- '[$List_rep, {$func: 1, $ret: [$List_rep, $int_rep]}]',
- '[$List_rep, {$func: 1, $ret: [$List_rep, $int_rep],'
- ' $typedefTag: $Typedef3_rep}]');
- expect(instantiate(List_, [Typedef4_]),
- '[$List_rep, {$func: 1}]',
- '[$List_rep, {$func: 1, $typedefTag: $Typedef4_rep}]');
- expect(instantiate(List_, [Typedef5_]),
- '[$List_rep, {$func: 1,'
- ' $args: [$int_rep, $String_rep]}]',
- '[$List_rep, {$func: 1,'
- ' $args: [$int_rep, $String_rep], $typedefTag: $Typedef5_rep}]');
- expect(instantiate(List_, [Typedef6_]),
- '[$List_rep, {$func: 1,'
- ' $args: [$int_rep], $opt: [$String_rep]}]',
- '[$List_rep, {$func: 1,'
- ' $args: [$int_rep], $opt: [$String_rep],'
- ' $typedefTag: $Typedef6_rep}]');
- expect(instantiate(List_, [Typedef7_]),
- '[$List_rep, {$func: 1, $args: '
- '[$int_rep, $String_rep], $opt: [[$List_rep, $int_rep],,]}]',
- '[$List_rep, {$func: 1, $args: '
- '[$int_rep, $String_rep], $opt: [[$List_rep, $int_rep],,], '
- '$typedefTag: $Typedef7_rep}]');
- expect(instantiate(List_, [Typedef8_]),
- '[$List_rep, {$func: 1, $args: [$int_rep],'
- ' $named: {b: $String_rep}}]',
- '[$List_rep, {$func: 1, $args: [$int_rep],'
- ' $named: {b: $String_rep}, $typedefTag: $Typedef8_rep}]');
- expect(instantiate(List_, [Typedef9_]),
- '[$List_rep, {$func: 1, '
- '$args: [$int_rep, $String_rep], $named: '
- '{c: [$List_rep, $int_rep], d: null}}]',
- '[$List_rep, {$func: 1, '
- '$args: [$int_rep, $String_rep], $named: {c: [$List_rep, $int_rep],'
- ' d: null}, $typedefTag: $Typedef9_rep}]');
- expect(instantiate(List_, [Typedef10_]),
- '[$List_rep, {$func: 1, '
- '$args: [{$func: 1, $retvoid: true, '
- '$args: [$int_rep], $opt: [,]}]}]',
- '[$List_rep, {$func: 1, '
- '$args: [{$func: 1, $retvoid: true, '
- '$args: [$int_rep], $opt: [,]}], $typedefTag: $Typedef10_rep}]');
+ // List<E>
+ expect(List_.computeType(env.compiler.resolution),
+ '[$List_rep, $List_E_rep]');
+ // List
+ expect(List_.rawType, '$List_rep');
+ // List<dynamic>
+ expect(instantiate(List_, [dynamic_]), '$List_rep');
+ // List<int>
+ expect(instantiate(List_, [int_]), '[$List_rep, $int_rep]');
+ // List<Typedef>
+ expect(
+ instantiate(List_, [Typedef_]),
+ '[$List_rep, {$func: 1, $retvoid: true}]',
+ '[$List_rep, {$func: 1, $retvoid: true,'
+ ' $typedefTag: $Typedef_rep}]');
+ expect(
+ instantiate(List_, [Typedef2_]),
+ '[$List_rep, {$func: 1, $ret: $int_rep}]',
+ '[$List_rep, {$func: 1, $ret: $int_rep,'
+ ' $typedefTag: $Typedef2_rep}]');
+ expect(
+ instantiate(List_, [Typedef3_]),
+ '[$List_rep, {$func: 1, $ret: [$List_rep, $int_rep]}]',
+ '[$List_rep, {$func: 1, $ret: [$List_rep, $int_rep],'
+ ' $typedefTag: $Typedef3_rep}]');
+ expect(instantiate(List_, [Typedef4_]), '[$List_rep, {$func: 1}]',
+ '[$List_rep, {$func: 1, $typedefTag: $Typedef4_rep}]');
+ expect(
+ instantiate(List_, [Typedef5_]),
+ '[$List_rep, {$func: 1,'
+ ' $args: [$int_rep, $String_rep]}]',
+ '[$List_rep, {$func: 1,'
+ ' $args: [$int_rep, $String_rep], $typedefTag: $Typedef5_rep}]');
+ expect(
+ instantiate(List_, [Typedef6_]),
+ '[$List_rep, {$func: 1,'
+ ' $args: [$int_rep], $opt: [$String_rep]}]',
+ '[$List_rep, {$func: 1,'
+ ' $args: [$int_rep], $opt: [$String_rep],'
+ ' $typedefTag: $Typedef6_rep}]');
+ expect(
+ instantiate(List_, [Typedef7_]),
+ '[$List_rep, {$func: 1, $args: '
+ '[$int_rep, $String_rep], $opt: [[$List_rep, $int_rep],,]}]',
+ '[$List_rep, {$func: 1, $args: '
+ '[$int_rep, $String_rep], $opt: [[$List_rep, $int_rep],,], '
+ '$typedefTag: $Typedef7_rep}]');
+ expect(
+ instantiate(List_, [Typedef8_]),
+ '[$List_rep, {$func: 1, $args: [$int_rep],'
+ ' $named: {b: $String_rep}}]',
+ '[$List_rep, {$func: 1, $args: [$int_rep],'
+ ' $named: {b: $String_rep}, $typedefTag: $Typedef8_rep}]');
+ expect(
+ instantiate(List_, [Typedef9_]),
+ '[$List_rep, {$func: 1, '
+ '$args: [$int_rep, $String_rep], $named: '
+ '{c: [$List_rep, $int_rep], d: null}}]',
+ '[$List_rep, {$func: 1, '
+ '$args: [$int_rep, $String_rep], $named: {c: [$List_rep, $int_rep],'
+ ' d: null}, $typedefTag: $Typedef9_rep}]');
+ expect(
+ instantiate(List_, [Typedef10_]),
+ '[$List_rep, {$func: 1, '
+ '$args: [{$func: 1, $retvoid: true, '
+ '$args: [$int_rep], $opt: [,]}]}]',
+ '[$List_rep, {$func: 1, '
+ '$args: [{$func: 1, $retvoid: true, '
+ '$args: [$int_rep], $opt: [,]}], $typedefTag: $Typedef10_rep}]');
- // Map<K,V>
- expect(Map_.computeType(env.compiler.resolution),
- '[$Map_rep, $Map_K_rep, $Map_V_rep]');
- // Map
- expect(Map_.rawType, '$Map_rep');
- // Map<dynamic,dynamic>
- expect(instantiate(Map_, [dynamic_, dynamic_]), '$Map_rep');
- // Map<int,String>
- expect(instantiate(Map_, [int_, String_]),
- '[$Map_rep, $int_rep, $String_rep]');
+ // Map<K,V>
+ expect(Map_.computeType(env.compiler.resolution),
+ '[$Map_rep, $Map_K_rep, $Map_V_rep]');
+ // Map
+ expect(Map_.rawType, '$Map_rep');
+ // Map<dynamic,dynamic>
+ expect(instantiate(Map_, [dynamic_, dynamic_]), '$Map_rep');
+ // Map<int,String>
+ expect(instantiate(Map_, [int_, String_]),
+ '[$Map_rep, $int_rep, $String_rep]');
+ // void m1() {}
+ expect(env.getElement('m1').computeType(env.compiler.resolution),
+ '{$func: 1, $retvoid: true}');
- // void m1() {}
- expect(env.getElement('m1').computeType(env.compiler.resolution),
- '{$func: 1, $retvoid: true}');
+ // int m2() => 0;
+ expect(env.getElement('m2').computeType(env.compiler.resolution),
+ '{$func: 1, $ret: $int_rep}');
- // int m2() => 0;
- expect(env.getElement('m2').computeType(env.compiler.resolution),
- '{$func: 1, $ret: $int_rep}');
+ // List<int> m3() => null;
+ expect(env.getElement('m3').computeType(env.compiler.resolution),
+ '{$func: 1, $ret: [$List_rep, $int_rep]}');
- // List<int> m3() => null;
- expect(env.getElement('m3').computeType(env.compiler.resolution),
- '{$func: 1, $ret: [$List_rep, $int_rep]}');
+ // m4() {}
+ expect(env.getElement('m4').computeType(env.compiler.resolution),
+ '{$func: 1}');
- // m4() {}
- expect(env.getElement('m4').computeType(env.compiler.resolution),
- '{$func: 1}');
+ // m5(int a, String b) {}
+ expect(env.getElement('m5').computeType(env.compiler.resolution),
+ '{$func: 1, $args: [$int_rep, $String_rep]}');
- // m5(int a, String b) {}
- expect(env.getElement('m5').computeType(env.compiler.resolution),
- '{$func: 1, $args: [$int_rep, $String_rep]}');
+ // m6(int a, [String b]) {}
+ expect(
+ env.getElement('m6').computeType(env.compiler.resolution),
+ '{$func: 1, $args: [$int_rep],'
+ ' $opt: [$String_rep]}');
- // m6(int a, [String b]) {}
- expect(env.getElement('m6').computeType(env.compiler.resolution),
- '{$func: 1, $args: [$int_rep],'
- ' $opt: [$String_rep]}');
+ // m7(int a, String b, [List<int> c, d]) {}
+ expect(
+ env.getElement('m7').computeType(env.compiler.resolution),
+ '{$func: 1,'
+ ' $args: [$int_rep, $String_rep],'
+ ' $opt: [[$List_rep, $int_rep],,]}');
- // m7(int a, String b, [List<int> c, d]) {}
- expect(env.getElement('m7').computeType(env.compiler.resolution),
- '{$func: 1,'
- ' $args: [$int_rep, $String_rep],'
- ' $opt: [[$List_rep, $int_rep],,]}');
+ // m8(int a, {String b}) {}
+ expect(
+ env.getElement('m8').computeType(env.compiler.resolution),
+ '{$func: 1,'
+ ' $args: [$int_rep], $named: {b: $String_rep}}');
- // m8(int a, {String b}) {}
- expect(env.getElement('m8').computeType(env.compiler.resolution),
- '{$func: 1,'
- ' $args: [$int_rep], $named: {b: $String_rep}}');
+ // m9(int a, String b, {List<int> c, d}) {}
+ expect(
+ env.getElement('m9').computeType(env.compiler.resolution),
+ '{$func: 1,'
+ ' $args: [$int_rep, $String_rep],'
+ ' $named: {c: [$List_rep, $int_rep], d: null}}');
- // m9(int a, String b, {List<int> c, d}) {}
- expect(env.getElement('m9').computeType(env.compiler.resolution),
- '{$func: 1,'
- ' $args: [$int_rep, $String_rep],'
- ' $named: {c: [$List_rep, $int_rep], d: null}}');
-
- // m10(void f(int a, [b])) {}
- expect(env.getElement('m10').computeType(env.compiler.resolution),
- '{$func: 1, $args:'
- ' [{$func: 1,'
- ' $retvoid: true, $args: [$int_rep], $opt: [,]}]}');
- }));
+ // m10(void f(int a, [b])) {}
+ expect(
+ env.getElement('m10').computeType(env.compiler.resolution),
+ '{$func: 1, $args:'
+ ' [{$func: 1,'
+ ' $retvoid: true, $args: [$int_rep], $opt: [,]}]}');
+ }));
}
diff --git a/tests/compiler/dart2js/type_substitution_test.dart b/tests/compiler/dart2js/type_substitution_test.dart
index c8040e5..0114b32 100644
--- a/tests/compiler/dart2js/type_substitution_test.dart
+++ b/tests/compiler/dart2js/type_substitution_test.dart
@@ -48,51 +48,61 @@
class E<T> extends A<A<T>> {}
class F<T, U> extends B<F<T, String>> implements A<F<B<U>, int>> {}
''').then((env) {
- var compiler = env.compiler;
+ var compiler = env.compiler;
- ClassElement A = env.getElement("A");
- ClassElement B = env.getElement("B");
- ClassElement C = env.getElement("C");
- ClassElement D = env.getElement("D");
- ClassElement E = env.getElement("E");
- ClassElement F = env.getElement("F");
+ ClassElement A = env.getElement("A");
+ ClassElement B = env.getElement("B");
+ ClassElement C = env.getElement("C");
+ ClassElement D = env.getElement("D");
+ ClassElement E = env.getElement("E");
+ ClassElement F = env.getElement("F");
- DartType numType = env['num'];
- DartType intType = env['int'];
- DartType stringType = env['String'];
+ DartType numType = env['num'];
+ DartType intType = env['int'];
+ DartType stringType = env['String'];
- InterfaceType C_int = instantiate(C, [intType]);
- Expect.equals(instantiate(C, [intType]), C_int);
- Expect.equals(instantiate(A, [intType]), C_int.asInstanceOf(A));
+ InterfaceType C_int = instantiate(C, [intType]);
+ Expect.equals(instantiate(C, [intType]), C_int);
+ Expect.equals(instantiate(A, [intType]), C_int.asInstanceOf(A));
- InterfaceType D_int = instantiate(D, [stringType]);
- Expect.equals(instantiate(A, [intType]), D_int.asInstanceOf(A));
+ InterfaceType D_int = instantiate(D, [stringType]);
+ Expect.equals(instantiate(A, [intType]), D_int.asInstanceOf(A));
- InterfaceType E_int = instantiate(E, [intType]);
- Expect.equals(instantiate(A, [instantiate(A, [intType])]),
- E_int.asInstanceOf(A));
+ InterfaceType E_int = instantiate(E, [intType]);
+ Expect.equals(
+ instantiate(A, [
+ instantiate(A, [intType])
+ ]),
+ E_int.asInstanceOf(A));
- InterfaceType F_int_string = instantiate(F, [intType, stringType]);
- Expect.equals(instantiate(B, [instantiate(F, [intType, stringType])]),
- F_int_string.asInstanceOf(B));
- Expect.equals(instantiate(A, [instantiate(F, [instantiate(B, [stringType]),
- intType])]),
- F_int_string.asInstanceOf(A));
-
- }));
+ InterfaceType F_int_string = instantiate(F, [intType, stringType]);
+ Expect.equals(
+ instantiate(B, [
+ instantiate(F, [intType, stringType])
+ ]),
+ F_int_string.asInstanceOf(B));
+ Expect.equals(
+ instantiate(A, [
+ instantiate(F, [
+ instantiate(B, [stringType]),
+ intType
+ ])
+ ]),
+ F_int_string.asInstanceOf(A));
+ }));
}
/**
* Test that substitution of [parameters] by [arguments] in the type found
* through [name1] is the same as the type found through [name2].
*/
-void testSubstitution(compiler, arguments, parameters,
- String name1, String name2) {
+void testSubstitution(
+ compiler, arguments, parameters, String name1, String name2) {
DartType type1 = getType(compiler, name1);
DartType type2 = getType(compiler, name2);
DartType subst = type1.subst(arguments, parameters);
- Expect.equals(type2, subst,
- "$type1.subst($arguments,$parameters)=$subst != $type2");
+ Expect.equals(
+ type2, subst, "$type1.subst($arguments,$parameters)=$subst != $type2");
}
void testTypeSubstitution() {
@@ -149,78 +159,92 @@
void Typedef2e(Typedef2<String> b) {}
}
""").then((env) {
- var compiler = env.compiler;
+ var compiler = env.compiler;
- InterfaceType Class_T_S = env["Class"];
- Expect.isNotNull(Class_T_S);
- Expect.identical(Class_T_S.kind, TypeKind.INTERFACE);
- Expect.equals(2, Class_T_S.typeArguments.length);
+ InterfaceType Class_T_S = env["Class"];
+ Expect.isNotNull(Class_T_S);
+ Expect.identical(Class_T_S.kind, TypeKind.INTERFACE);
+ Expect.equals(2, Class_T_S.typeArguments.length);
- DartType T = Class_T_S.typeArguments[0];
- Expect.isNotNull(T);
- Expect.identical(T.kind, TypeKind.TYPE_VARIABLE);
+ DartType T = Class_T_S.typeArguments[0];
+ Expect.isNotNull(T);
+ Expect.identical(T.kind, TypeKind.TYPE_VARIABLE);
- DartType S = Class_T_S.typeArguments[1];
- Expect.isNotNull(S);
- Expect.identical(S.kind, TypeKind.TYPE_VARIABLE);
+ DartType S = Class_T_S.typeArguments[1];
+ Expect.isNotNull(S);
+ Expect.identical(S.kind, TypeKind.TYPE_VARIABLE);
- DartType intType = env['int'];//getType(compiler, "int1");
- Expect.isNotNull(intType);
- Expect.identical(intType.kind, TypeKind.INTERFACE);
+ DartType intType = env['int']; //getType(compiler, "int1");
+ Expect.isNotNull(intType);
+ Expect.identical(intType.kind, TypeKind.INTERFACE);
- DartType StringType = env['String'];//getType(compiler, "String1");
- Expect.isNotNull(StringType);
- Expect.identical(StringType.kind, TypeKind.INTERFACE);
+ DartType StringType = env['String']; //getType(compiler, "String1");
+ Expect.isNotNull(StringType);
+ Expect.identical(StringType.kind, TypeKind.INTERFACE);
- List<DartType> parameters = <DartType>[T, S];
- List<DartType> arguments = <DartType>[intType, StringType];
+ List<DartType> parameters = <DartType>[T, S];
+ List<DartType> arguments = <DartType>[intType, StringType];
- // TODO(johnniwinther): Create types directly from strings to improve test
- // readability.
+ // TODO(johnniwinther): Create types directly from strings to improve test
+ // readability.
- testSubstitution(compiler, arguments, parameters, "void1", "void2");
- testSubstitution(compiler, arguments, parameters, "dynamic1", "dynamic2");
- testSubstitution(compiler, arguments, parameters, "int1", "int2");
- testSubstitution(compiler, arguments, parameters, "String1", "String2");
- testSubstitution(compiler, arguments, parameters, "ListInt1", "ListInt2");
- testSubstitution(compiler, arguments, parameters, "ListT1", "ListT2");
- testSubstitution(compiler, arguments, parameters, "ListS1", "ListS2");
- testSubstitution(compiler, arguments, parameters, "ListListT1", "ListListT2");
- testSubstitution(compiler, arguments, parameters, "ListRaw1", "ListRaw2");
- testSubstitution(compiler, arguments, parameters,
- "ListDynamic1", "ListDynamic2");
- testSubstitution(compiler, arguments, parameters,
- "MapIntString1", "MapIntString2");
- testSubstitution(compiler, arguments, parameters,
- "MapTString1", "MapTString2");
- testSubstitution(compiler, arguments, parameters,
- "MapDynamicString1", "MapDynamicString2");
- testSubstitution(compiler, arguments, parameters, "TypeVarT1", "TypeVarT2");
- testSubstitution(compiler, arguments, parameters, "TypeVarS1", "TypeVarS2");
- testSubstitution(compiler, arguments, parameters, "Function1a", "Function2a");
- testSubstitution(compiler, arguments, parameters, "Function1b", "Function2b");
- testSubstitution(compiler, arguments, parameters, "Function1c", "Function2c");
- testSubstitution(compiler, arguments, parameters, "Typedef1a", "Typedef2a");
- testSubstitution(compiler, arguments, parameters, "Typedef1b", "Typedef2b");
- testSubstitution(compiler, arguments, parameters, "Typedef1c", "Typedef2c");
- testSubstitution(compiler, arguments, parameters, "Typedef1d", "Typedef2d");
- testSubstitution(compiler, arguments, parameters, "Typedef1e", "Typedef2e");
+ testSubstitution(compiler, arguments, parameters, "void1", "void2");
+ testSubstitution(
+ compiler, arguments, parameters, "dynamic1", "dynamic2");
+ testSubstitution(compiler, arguments, parameters, "int1", "int2");
+ testSubstitution(compiler, arguments, parameters, "String1", "String2");
+ testSubstitution(
+ compiler, arguments, parameters, "ListInt1", "ListInt2");
+ testSubstitution(compiler, arguments, parameters, "ListT1", "ListT2");
+ testSubstitution(compiler, arguments, parameters, "ListS1", "ListS2");
+ testSubstitution(
+ compiler, arguments, parameters, "ListListT1", "ListListT2");
+ testSubstitution(
+ compiler, arguments, parameters, "ListRaw1", "ListRaw2");
+ testSubstitution(
+ compiler, arguments, parameters, "ListDynamic1", "ListDynamic2");
+ testSubstitution(
+ compiler, arguments, parameters, "MapIntString1", "MapIntString2");
+ testSubstitution(
+ compiler, arguments, parameters, "MapTString1", "MapTString2");
+ testSubstitution(compiler, arguments, parameters, "MapDynamicString1",
+ "MapDynamicString2");
+ testSubstitution(
+ compiler, arguments, parameters, "TypeVarT1", "TypeVarT2");
+ testSubstitution(
+ compiler, arguments, parameters, "TypeVarS1", "TypeVarS2");
+ testSubstitution(
+ compiler, arguments, parameters, "Function1a", "Function2a");
+ testSubstitution(
+ compiler, arguments, parameters, "Function1b", "Function2b");
+ testSubstitution(
+ compiler, arguments, parameters, "Function1c", "Function2c");
+ testSubstitution(
+ compiler, arguments, parameters, "Typedef1a", "Typedef2a");
+ testSubstitution(
+ compiler, arguments, parameters, "Typedef1b", "Typedef2b");
+ testSubstitution(
+ compiler, arguments, parameters, "Typedef1c", "Typedef2c");
+ testSubstitution(
+ compiler, arguments, parameters, "Typedef1d", "Typedef2d");
+ testSubstitution(
+ compiler, arguments, parameters, "Typedef1e", "Typedef2e");
- // Substitution in unalias.
- DartType Typedef2_int_String = getType(compiler, "Typedef2a");
- Expect.isNotNull(Typedef2_int_String);
- DartType Function_int_String = getType(compiler, "Function2b");
- Expect.isNotNull(Function_int_String);
- DartType unalias1 = Typedef2_int_String.unaliased;
- Expect.equals(Function_int_String, unalias1,
- '$Typedef2_int_String.unalias=$unalias1 != $Function_int_String');
+ // Substitution in unalias.
+ DartType Typedef2_int_String = getType(compiler, "Typedef2a");
+ Expect.isNotNull(Typedef2_int_String);
+ DartType Function_int_String = getType(compiler, "Function2b");
+ Expect.isNotNull(Function_int_String);
+ DartType unalias1 = Typedef2_int_String.unaliased;
+ Expect.equals(Function_int_String, unalias1,
+ '$Typedef2_int_String.unalias=$unalias1 != $Function_int_String');
- DartType Typedef1 = getType(compiler, "Typedef1c");
- Expect.isNotNull(Typedef1);
- DartType Function_dynamic_dynamic = getType(compiler, "Function1c");
- Expect.isNotNull(Function_dynamic_dynamic);
- DartType unalias2 = Typedef1.unaliased;
- Expect.equals(Function_dynamic_dynamic, unalias2,
- '$Typedef1.unalias=$unalias2 != $Function_dynamic_dynamic');
- }));
+ DartType Typedef1 = getType(compiler, "Typedef1c");
+ Expect.isNotNull(Typedef1);
+ DartType Function_dynamic_dynamic = getType(compiler, "Function1c");
+ Expect.isNotNull(Function_dynamic_dynamic);
+ DartType unalias2 = Typedef1.unaliased;
+ Expect.equals(Function_dynamic_dynamic, unalias2,
+ '$Typedef1.unalias=$unalias2 != $Function_dynamic_dynamic');
+ }));
}
diff --git a/tests/compiler/dart2js/type_test_helper.dart b/tests/compiler/dart2js/type_test_helper.dart
index 5e91f77..cc0ae90 100644
--- a/tests/compiler/dart2js/type_test_helper.dart
+++ b/tests/compiler/dart2js/type_test_helper.dart
@@ -11,16 +11,12 @@
import 'package:compiler/src/common/resolution.dart';
import 'package:compiler/src/commandline_options.dart';
import 'package:compiler/src/dart_types.dart';
-import 'package:compiler/src/compiler.dart'
- show Compiler;
+import 'package:compiler/src/compiler.dart' show Compiler;
import 'package:compiler/src/elements/elements.dart'
- show Element,
- MemberElement,
- TypeDeclarationElement,
- ClassElement;
+ show Element, MemberElement, TypeDeclarationElement, ClassElement;
-GenericType instantiate(TypeDeclarationElement element,
- List<DartType> arguments) {
+GenericType instantiate(
+ TypeDeclarationElement element, List<DartType> arguments) {
if (element.isClass) {
return new InterfaceType(element, arguments);
} else {
@@ -34,12 +30,12 @@
Resolution get resolution => compiler.resolution;
- static Future<TypeEnvironment> create(
- String source, {bool useMockCompiler: true,
- bool expectNoErrors: false,
- bool expectNoWarningsOrErrors: false,
- bool stopAfterTypeInference: false,
- String mainSource}) {
+ static Future<TypeEnvironment> create(String source,
+ {bool useMockCompiler: true,
+ bool expectNoErrors: false,
+ bool expectNoWarningsOrErrors: false,
+ bool stopAfterTypeInference: false,
+ String mainSource}) {
Uri uri;
Compiler compiler;
bool stopAfterTypeInference = mainSource != null;
@@ -53,9 +49,7 @@
memory.DiagnosticCollector collector;
if (useMockCompiler) {
uri = new Uri(scheme: 'source');
- mock.MockCompiler mockCompiler = mock.compilerFor(
- source,
- uri,
+ mock.MockCompiler mockCompiler = mock.compilerFor(source, uri,
analyzeAll: !stopAfterTypeInference,
analyzeOnly: !stopAfterTypeInference);
mockCompiler.diagnosticHandler = mock.createHandler(mockCompiler, source);
@@ -69,19 +63,18 @@
memorySourceFiles: {'main.dart': source},
diagnosticHandler: collector,
options: stopAfterTypeInference
- ? [] : [Flags.analyzeAll, Flags.analyzeOnly]);
+ ? []
+ : [Flags.analyzeAll, Flags.analyzeOnly]);
}
compiler.stopAfterTypeInference = stopAfterTypeInference;
return compiler.run(uri).then((_) {
if (expectNoErrors || expectNoWarningsOrErrors) {
var errors = collector.errors;
- Expect.isTrue(errors.isEmpty,
- 'Unexpected errors: ${errors}');
+ Expect.isTrue(errors.isEmpty, 'Unexpected errors: ${errors}');
}
if (expectNoWarningsOrErrors) {
var warnings = collector.warnings;
- Expect.isTrue(warnings.isEmpty,
- 'Unexpected warnings: ${warnings}');
+ Expect.isTrue(warnings.isEmpty, 'Unexpected warnings: ${warnings}');
}
return new TypeEnvironment._(compiler);
});
@@ -105,7 +98,7 @@
return element.computeType(compiler.resolution);
}
- DartType operator[] (String name) {
+ DartType operator [](String name) {
if (name == 'dynamic') return const DynamicType();
if (name == 'void') return const VoidType();
return getElementType(name);
@@ -132,11 +125,9 @@
return compiler.types.flatten(T);
}
- FunctionType functionType(DartType returnType,
- List<DartType> parameters,
- {List<DartType> optionalParameters:
- const <DartType>[],
- Map<String,DartType> namedParameters}) {
+ FunctionType functionType(DartType returnType, List<DartType> parameters,
+ {List<DartType> optionalParameters: const <DartType>[],
+ Map<String, DartType> namedParameters}) {
List<String> namedParameterNames = <String>[];
List<DartType> namedParameterTypes = <DartType>[];
if (namedParameters != null) {
@@ -145,8 +136,7 @@
namedParameterTypes.add(type);
});
}
- return new FunctionType.synthesized(
- returnType, parameters, optionalParameters,
- namedParameterNames, namedParameterTypes);
+ return new FunctionType.synthesized(returnType, parameters,
+ optionalParameters, namedParameterNames, namedParameterTypes);
}
}
diff --git a/tests/compiler/dart2js/type_variable_bound_test.dart b/tests/compiler/dart2js/type_variable_bound_test.dart
index 544d664..ed2d150 100644
--- a/tests/compiler/dart2js/type_variable_bound_test.dart
+++ b/tests/compiler/dart2js/type_variable_bound_test.dart
@@ -17,7 +17,7 @@
});
}
-Future test(String source, {var errors, var warnings}) async{
+Future test(String source, {var errors, var warnings}) async {
if (errors == null) errors = [];
if (errors is! List) errors = [errors];
if (warnings == null) warnings = [];
@@ -25,17 +25,21 @@
var compiler = await compile(source);
DiagnosticCollector collector = compiler.diagnosticCollector;
Expect.equals(!errors.isEmpty, compiler.compilationFailed);
- Expect.equals(errors.length, collector.errors.length,
- 'unexpected error count: ${collector.errors.length} '
- 'expected ${errors.length}');
- Expect.equals(warnings.length, collector.warnings.length,
- 'unexpected warning count: ${collector.warnings.length} '
- 'expected ${warnings.length}');
+ Expect.equals(
+ errors.length,
+ collector.errors.length,
+ 'unexpected error count: ${collector.errors.length} '
+ 'expected ${errors.length}');
+ Expect.equals(
+ warnings.length,
+ collector.warnings.length,
+ 'unexpected warning count: ${collector.warnings.length} '
+ 'expected ${warnings.length}');
- for (int i = 0 ; i < errors.length ; i++) {
+ for (int i = 0; i < errors.length; i++) {
Expect.equals(errors[i], collector.errors.elementAt(i).message.kind);
}
- for (int i = 0 ; i < warnings.length ; i++) {
+ for (int i = 0; i < warnings.length; i++) {
Expect.equals(warnings[i], collector.warnings.elementAt(i).message.kind);
}
}
@@ -50,14 +54,14 @@
""");
DiagnosticCollector collector = compiler.diagnosticCollector;
Expect.isFalse(compiler.compilationFailed);
- Expect.isTrue(collector.errors.isEmpty,
- 'unexpected errors: ${collector.errors}');
+ Expect.isTrue(
+ collector.errors.isEmpty, 'unexpected errors: ${collector.errors}');
Expect.equals(1, collector.warnings.length,
- 'expected exactly one warning, but got ${collector.warnings}');
+ 'expected exactly one warning, but got ${collector.warnings}');
print(collector.warnings.elementAt(0));
Expect.equals(MessageKind.CYCLIC_TYPE_VARIABLE,
- collector.warnings.elementAt(0).message.kind);
+ collector.warnings.elementAt(0).message.kind);
Expect.equals("T",
collector.warnings.elementAt(0).message.arguments['typeVariableName']);
}
@@ -75,15 +79,15 @@
print(collector.errors);
Expect.isTrue(collector.errors.isEmpty, 'unexpected errors');
Expect.equals(2, collector.warnings.length,
- 'expected exactly two errors, but got ${collector.warnings}');
+ 'expected exactly two errors, but got ${collector.warnings}');
Expect.equals(MessageKind.CYCLIC_TYPE_VARIABLE,
- collector.warnings.elementAt(0).message.kind);
+ collector.warnings.elementAt(0).message.kind);
Expect.equals("T",
collector.warnings.elementAt(0).message.arguments['typeVariableName']);
Expect.equals(MessageKind.CYCLIC_TYPE_VARIABLE,
- collector.warnings.elementAt(1).message.kind);
+ collector.warnings.elementAt(1).message.kind);
Expect.equals("S",
collector.warnings.elementAt(1).message.arguments['typeVariableName']);
}
@@ -101,20 +105,20 @@
print(collector.errors);
Expect.isTrue(collector.errors.isEmpty, 'unexpected errors');
Expect.equals(3, collector.warnings.length,
- 'expected exactly one error, but got ${collector.warnings}');
+ 'expected exactly one error, but got ${collector.warnings}');
Expect.equals(MessageKind.CYCLIC_TYPE_VARIABLE,
- collector.warnings.elementAt(0).message.kind);
+ collector.warnings.elementAt(0).message.kind);
Expect.equals("T",
collector.warnings.elementAt(0).message.arguments['typeVariableName']);
Expect.equals(MessageKind.CYCLIC_TYPE_VARIABLE,
- collector.warnings.elementAt(1).message.kind);
+ collector.warnings.elementAt(1).message.kind);
Expect.equals("S",
collector.warnings.elementAt(1).message.arguments['typeVariableName']);
Expect.equals(MessageKind.CYCLIC_TYPE_VARIABLE,
- collector.warnings.elementAt(2).message.kind);
+ collector.warnings.elementAt(2).message.kind);
Expect.equals("U",
collector.warnings.elementAt(2).message.arguments['typeVariableName']);
}
@@ -132,15 +136,15 @@
print(collector.errors);
Expect.isTrue(collector.errors.isEmpty, 'unexpected errors');
Expect.equals(2, collector.warnings.length,
- 'expected exactly one error, but got ${collector.warnings}');
+ 'expected exactly one error, but got ${collector.warnings}');
Expect.equals(MessageKind.CYCLIC_TYPE_VARIABLE,
- collector.warnings.elementAt(0).message.kind);
+ collector.warnings.elementAt(0).message.kind);
Expect.equals("S",
collector.warnings.elementAt(0).message.arguments['typeVariableName']);
Expect.equals(MessageKind.CYCLIC_TYPE_VARIABLE,
- collector.warnings.elementAt(1).message.kind);
+ collector.warnings.elementAt(1).message.kind);
Expect.equals("U",
collector.warnings.elementAt(1).message.arguments['typeVariableName']);
}
@@ -160,17 +164,20 @@
}
Future test6() {
- return test(r"""
+ return test(
+ r"""
class A<T extends num> {}
void main() {
new A<String>();
}
-""", warnings: MessageKind.INVALID_TYPE_VARIABLE_BOUND);
+""",
+ warnings: MessageKind.INVALID_TYPE_VARIABLE_BOUND);
}
Future test7() {
- return test(r"""
+ return test(
+ r"""
class A<T extends num> {}
class B<T> extends A<T> {} // Warning produced here.
@@ -178,7 +185,8 @@
new B(); // No warning produced here.
new B<String>(); // No warning produced here.
}
-""", warnings: MessageKind.INVALID_TYPE_VARIABLE_BOUND);
+""",
+ warnings: MessageKind.INVALID_TYPE_VARIABLE_BOUND);
}
Future test8() {
@@ -209,7 +217,8 @@
}
Future test9() {
- return test(r"""
+ return test(
+ r"""
class B<T extends B<T>> {}
class C<T extends B<T>> extends B<T> {}
class D<T extends C<T>> extends C<T> {}
@@ -220,8 +229,11 @@
new D<B<F>>(); // Warning: B<F> is not a subtype of C<T>.
new E<D<F>>(); // Warning: E<F> is not a subtype of E<T>.
}
-""", warnings: [MessageKind.INVALID_TYPE_VARIABLE_BOUND,
- MessageKind.INVALID_TYPE_VARIABLE_BOUND]);
+""",
+ warnings: [
+ MessageKind.INVALID_TYPE_VARIABLE_BOUND,
+ MessageKind.INVALID_TYPE_VARIABLE_BOUND
+ ]);
}
Future test10() {
@@ -242,7 +254,8 @@
// TODO(het): The error is reported twice because both the Dart and JS constant
// compilers are run on the const constructor, investigate why.
Future test11() {
- return test(r"""
+ return test(
+ r"""
class A {
const A();
}
@@ -256,7 +269,8 @@
main() {
print(const Test<B>());
}
-""", errors: [MessageKind.NOT_ASSIGNABLE, MessageKind.NOT_ASSIGNABLE]);
+""",
+ errors: [MessageKind.NOT_ASSIGNABLE, MessageKind.NOT_ASSIGNABLE]);
}
main() {
diff --git a/tests/compiler/dart2js/type_variable_occurrence_test.dart b/tests/compiler/dart2js/type_variable_occurrence_test.dart
index a30a552..6816288 100644
--- a/tests/compiler/dart2js/type_variable_occurrence_test.dart
+++ b/tests/compiler/dart2js/type_variable_occurrence_test.dart
@@ -8,8 +8,7 @@
import "package:async_helper/async_helper.dart";
import 'type_test_helper.dart';
import 'package:compiler/src/dart_types.dart';
-import "package:compiler/src/elements/elements.dart"
- show Element, ClassElement;
+import "package:compiler/src/elements/elements.dart" show Element, ClassElement;
void main() {
testTypeVariableOccurrence();
@@ -54,76 +53,75 @@
void method8({T t}) {}
}
""").then((env) {
+ ClassElement A = env.getElement('A');
- ClassElement A = env.getElement('A');
+ expect(bool expectResult, String memberName) {
+ DartType memberType = env.getMemberType(A, memberName);
+ TypeVariableType typeVariable = memberType.typeVariableOccurrence;
+ if (expectResult) {
+ Expect.isNotNull(typeVariable);
+ Expect.equals(A, Types.getClassContext(memberType));
+ } else {
+ Expect.isNull(typeVariable);
+ Expect.isNull(Types.getClassContext(memberType));
+ }
+ }
- expect(bool expectResult, String memberName) {
- DartType memberType = env.getMemberType(A, memberName);
- TypeVariableType typeVariable = memberType.typeVariableOccurrence;
- if (expectResult) {
- Expect.isNotNull(typeVariable);
- Expect.equals(A, Types.getClassContext(memberType));
- } else {
- Expect.isNull(typeVariable);
- Expect.isNull(Types.getClassContext(memberType));
- }
- }
+ // int field1;
+ expect(false, 'field1');
+ // T field2;
+ expect(true, 'field2');
+ // A<int> field3;
+ expect(false, 'field3');
+ // A<T> field4;
+ expect(true, 'field4');
+ // A<A<int>> field5;
+ expect(false, 'field5');
+ // A<A<T>> field6;
+ expect(true, 'field6');
- // int field1;
- expect(false, 'field1');
- // T field2;
- expect(true, 'field2');
- // A<int> field3;
- expect(false, 'field3');
- // A<T> field4;
- expect(true, 'field4');
- // A<A<int>> field5;
- expect(false, 'field5');
- // A<A<T>> field6;
- expect(true, 'field6');
+ // Typedef1 field7;
+ expect(false, 'field7');
+ // Typedef1<int> field8;
+ expect(false, 'field8');
+ // Typedef1<T> field9;
+ expect(true, 'field9');
+ // Typedef1<Typedef1<T>> field10;
+ expect(true, 'field10');
- // Typedef1 field7;
- expect(false, 'field7');
- // Typedef1<int> field8;
- expect(false, 'field8');
- // Typedef1<T> field9;
- expect(true, 'field9');
- // Typedef1<Typedef1<T>> field10;
- expect(true, 'field10');
+ // Typedef2 field11;
+ expect(false, 'field11');
+ // Typedef2<int> field12;
+ expect(false, 'field12');
+ // Typedef2<T> field13;
+ expect(true, 'field13');
+ // Typedef2<Typedef1<T>> field14;
+ expect(true, 'field14');
- // Typedef2 field11;
- expect(false, 'field11');
- // Typedef2<int> field12;
- expect(false, 'field12');
- // Typedef2<T> field13;
- expect(true, 'field13');
- // Typedef2<Typedef1<T>> field14;
- expect(true, 'field14');
+ // Typedef3 field15;
+ expect(false, 'field15');
+ // Typedef3<int> field16;
+ expect(false, 'field16');
+ // Typedef3<T> field17;
+ expect(true, 'field17');
+ // Typedef3<Typedef1<T>> field18;
+ expect(true, 'field18');
- // Typedef3 field15;
- expect(false, 'field15');
- // Typedef3<int> field16;
- expect(false, 'field16');
- // Typedef3<T> field17;
- expect(true, 'field17');
- // Typedef3<Typedef1<T>> field18;
- expect(true, 'field18');
-
- // void method1() {}
- expect(false, 'method1');
- // T method2() => null;
- expect(true, 'method2');
- // A<T> method3() => null;
- expect(true, 'method3');
- // void method4(T t) {}
- expect(true, 'method4');
- // void method5(A<T> t) {}
- expect(true, 'method5');
- // void method6(void foo(T t)) {}
- expect(true, 'method6');
- // void method7([T t]);
- expect(true, 'method7');
- // void method8({T t});
- expect(true, 'method8');
- }));
+ // void method1() {}
+ expect(false, 'method1');
+ // T method2() => null;
+ expect(true, 'method2');
+ // A<T> method3() => null;
+ expect(true, 'method3');
+ // void method4(T t) {}
+ expect(true, 'method4');
+ // void method5(A<T> t) {}
+ expect(true, 'method5');
+ // void method6(void foo(T t)) {}
+ expect(true, 'method6');
+ // void method7([T t]);
+ expect(true, 'method7');
+ // void method8({T t});
+ expect(true, 'method8');
+ }));
}
diff --git a/tests/compiler/dart2js/types_of_captured_variables_test.dart b/tests/compiler/dart2js/types_of_captured_variables_test.dart
index 32f61e3..d08f543 100644
--- a/tests/compiler/dart2js/types_of_captured_variables_test.dart
+++ b/tests/compiler/dart2js/types_of_captured_variables_test.dart
@@ -37,17 +37,17 @@
main() {
// Test that we know the type of captured, non-mutated variables.
asyncTest(() => compileAll(TEST1).then((generated) {
- Expect.isTrue(generated.contains('+ 87'));
- }));
+ Expect.isTrue(generated.contains('+ 87'));
+ }));
// Test that we know the type of captured, mutated variables.
asyncTest(() => compileAll(TEST2).then((generated) {
- Expect.isTrue(generated.contains('+ 87'));
- }));
+ Expect.isTrue(generated.contains('+ 87'));
+ }));
// Test that we know when types of a captured, mutated variable
// conflict.
asyncTest(() => compileAll(TEST3).then((generated) {
- Expect.isFalse(generated.contains('+ 87'));
- }));
+ Expect.isFalse(generated.contains('+ 87'));
+ }));
}
diff --git a/tests/compiler/dart2js/union_type_test.dart b/tests/compiler/dart2js/union_type_test.dart
index 4ae2dac..2d18f18 100644
--- a/tests/compiler/dart2js/union_type_test.dart
+++ b/tests/compiler/dart2js/union_type_test.dart
@@ -9,19 +9,19 @@
import 'type_test_helper.dart';
main() {
-
asyncTest(() async {
- TypeEnvironment env = await TypeEnvironment.create(r"""
+ TypeEnvironment env = await TypeEnvironment.create(
+ r"""
class A {}
class B {}
""",
- mainSource: r"""
+ mainSource: r"""
main() {
new A();
new B();
}
""",
- useMockCompiler: false);
+ useMockCompiler: false);
World world = env.compiler.world;
world.populate();
FlatTypeMask mask1 = new FlatTypeMask.exact(env.getElement('A'));
diff --git a/tests/compiler/dart2js/unparser2_test.dart b/tests/compiler/dart2js/unparser2_test.dart
index 7053e6a..d63bdb4 100644
--- a/tests/compiler/dart2js/unparser2_test.dart
+++ b/tests/compiler/dart2js/unparser2_test.dart
@@ -12,11 +12,9 @@
import "package:compiler/src/diagnostics/diagnostic_listener.dart";
import "package:compiler/src/elements/elements.dart"
- show CompilationUnitElement,
- LibraryElement;
+ show CompilationUnitElement, LibraryElement;
import "package:compiler/src/elements/modelx.dart"
- show CompilationUnitElementX,
- LibraryElementX;
+ show CompilationUnitElementX, LibraryElementX;
import "package:compiler/src/script.dart";
import "options_helper.dart";
@@ -93,8 +91,8 @@
CompilationUnitElement element = new CompilationUnitElementX(script, lib);
StringScanner scanner = new StringScanner.fromString(source);
Token beginToken = scanner.tokenize();
- NodeListener listener = new NodeListener(
- const ScannerOptions(), diagnosticListener, element);
+ NodeListener listener =
+ new NodeListener(const ScannerOptions(), diagnosticListener, element);
Parser parser = new Parser(listener, new MockParserOptions());
parser.parseUnit(beginToken);
Node node = listener.popNode();
diff --git a/tests/compiler/dart2js/unparser_test.dart b/tests/compiler/dart2js/unparser_test.dart
index e19ed0d..cd815c8 100644
--- a/tests/compiler/dart2js/unparser_test.dart
+++ b/tests/compiler/dart2js/unparser_test.dart
@@ -99,20 +99,16 @@
}
testConditionalImport() {
- testUnparseTopLevelWithMetadata(
- 'import "søhest" if(some.dotted.id)"other";');
- testUnparseTopLevelWithMetadata(
- 'import "søhest" if(id=="some str")"other";');
- testUnparseTopLevelWithMetadata(
- 'import "søhest"'
+ testUnparseTopLevelWithMetadata('import "søhest" if(some.dotted.id)"other";');
+ testUnparseTopLevelWithMetadata('import "søhest" if(id=="some str")"other";');
+ testUnparseTopLevelWithMetadata('import "søhest"'
' if(id=="some str")"other"'
' if(id)"other2";');
testUnparseTopLevelWithMetadata(
'import "søhest" if(some.dotted.id)"other" as fiskehest;');
testUnparseTopLevelWithMetadata(
'import "søhest" if(id=="some str")"other" as fiskehest;');
- testUnparseTopLevelWithMetadata(
- 'import "søhest"'
+ testUnparseTopLevelWithMetadata('import "søhest"'
' if(id=="some str")"other"'
' if(id)"other2"'
' as fiskehest;');
@@ -120,13 +116,11 @@
'import "søhest" if(some.dotted.id)"other" deferred as fiskehest;');
testUnparseTopLevelWithMetadata(
'import "søhest" if(id=="some str")"other" deferred as fiskehest;');
- testUnparseTopLevelWithMetadata(
- 'import "søhest"'
+ testUnparseTopLevelWithMetadata('import "søhest"'
' if(id=="some str")"other"'
' if(id)"other2"'
' deferred as fiskehest;');
- testUnparseTopLevelWithMetadata(
- 'import "søhest"'
+ testUnparseTopLevelWithMetadata('import "søhest"'
' if(id=="some str")"other"'
' if(id)"other2"'
' deferred as fiskehest'
@@ -134,16 +128,12 @@
}
testConditionalExport() {
- testUnparseTopLevelWithMetadata(
- 'export "søhest" if(some.dotted.id)"other";');
- testUnparseTopLevelWithMetadata(
- 'export "søhest" if(id=="some str")"other";');
- testUnparseTopLevelWithMetadata(
- 'export "søhest"'
+ testUnparseTopLevelWithMetadata('export "søhest" if(some.dotted.id)"other";');
+ testUnparseTopLevelWithMetadata('export "søhest" if(id=="some str")"other";');
+ testUnparseTopLevelWithMetadata('export "søhest"'
' if(id=="some str")"other"'
' if(id)"other2";');
- testUnparseTopLevelWithMetadata(
- 'export "søhest"'
+ testUnparseTopLevelWithMetadata('export "søhest"'
' if(id=="some str")"other"'
' if(id)"other2"'
' show foo,bar;');
@@ -277,15 +267,13 @@
testUnparseMemberAndAsMemberOfFoo("factory Foo()=prefix.Bar<T>;");
testUnparseMemberAndAsMemberOfFoo("factory Foo()=prefix.Bar<List<T>,T>;");
testUnparseMemberAndAsMemberOfFoo("factory Foo()=prefix.Bar<T>.baz;");
- testUnparseMemberAndAsMemberOfFoo(
- "factory Foo()=prefix.Bar<List<T>,T>.baz;");
+ testUnparseMemberAndAsMemberOfFoo("factory Foo()=prefix.Bar<List<T>,T>.baz;");
testUnparseMemberAndAsMemberOfFoo("const factory Foo()=Bar;");
testUnparseMemberAndAsMemberOfFoo("const factory Foo()=Bar.baz;");
testUnparseMemberAndAsMemberOfFoo("const factory Foo()=Bar<T>;");
testUnparseMemberAndAsMemberOfFoo("const factory Foo()=Bar<List<T>,T>;");
testUnparseMemberAndAsMemberOfFoo("const factory Foo()=Bar<T>.baz;");
- testUnparseMemberAndAsMemberOfFoo(
- "const factory Foo()=Bar<List<T>,T>.baz;");
+ testUnparseMemberAndAsMemberOfFoo("const factory Foo()=Bar<List<T>,T>.baz;");
testUnparseMemberAndAsMemberOfFoo("const factory Foo()=prefix.Bar;");
testUnparseMemberAndAsMemberOfFoo("const factory Foo()=prefix.Bar.baz;");
testUnparseMemberAndAsMemberOfFoo("const factory Foo()=prefix.Bar<T>;");
@@ -315,12 +303,10 @@
testUnparseMemberAndAsMemberOfFoo("external const factory Foo()=Bar<T>;");
testUnparseMemberAndAsMemberOfFoo(
"external const factory Foo()=Bar<List<T>,T>;");
- testUnparseMemberAndAsMemberOfFoo(
- "external const factory Foo()=Bar<T>.baz;");
+ testUnparseMemberAndAsMemberOfFoo("external const factory Foo()=Bar<T>.baz;");
testUnparseMemberAndAsMemberOfFoo(
"external const factory Foo()=Bar<List<T>,T>.baz;");
- testUnparseMemberAndAsMemberOfFoo(
- "external const factory Foo()=prefix.Bar;");
+ testUnparseMemberAndAsMemberOfFoo("external const factory Foo()=prefix.Bar;");
testUnparseMemberAndAsMemberOfFoo(
"external const factory Foo()=prefix.Bar.baz;");
testUnparseMemberAndAsMemberOfFoo(
@@ -378,22 +364,20 @@
Expect.equals(variableDeclarations[index], unparse(parameter));
index++;
}
-
}
testParameters() {
- testUnparseParameters(
- ["foo", "bar=0", "int baz", "int boz=0"]);
+ testUnparseParameters(["foo", "bar=0", "int baz", "int boz=0"]);
testUnparseParameters(
["this.foo", "this.bar=0", "int this.baz", "int this.boz=0"]);
testUnparseParameters(
["foo()", "void bar()", "int baz(a)", "int boz(int a,int b)=null"]);
- testUnparseParameters(
- ["this.foo()",
- //"void this.bar()", // Commented out due to Issue 7852
- //"int this.baz(a)", // Commented out due to Issue 7852
- //"int this.boz(int a,int b)=null" // Commented out due to Issue 7852
- ]);
+ testUnparseParameters([
+ "this.foo()",
+ //"void this.bar()", // Commented out due to Issue 7852
+ //"int this.baz(a)", // Commented out due to Issue 7852
+ //"int this.boz(int a,int b)=null" // Commented out due to Issue 7852
+ ]);
testUnparseParameters(
["@a foo", "@b @c bar=0", "@D(0) int baz", "@E([f],{g:h}) int boz=0"]);
}
diff --git a/tests/compiler/dart2js/unused_empty_map_test.dart b/tests/compiler/dart2js/unused_empty_map_test.dart
index 5f806bc..8ba2168 100644
--- a/tests/compiler/dart2js/unused_empty_map_test.dart
+++ b/tests/compiler/dart2js/unused_empty_map_test.dart
@@ -8,12 +8,14 @@
import 'package:async_helper/async_helper.dart';
import 'memory_compiler.dart';
-const TEST_SOURCE = const {"main.dart": r"""
+const TEST_SOURCE = const {
+ "main.dart": r"""
void main() {
var x = {};
return;
}
-"""};
+"""
+};
const HASHMAP_EMPTY_CONSTRUCTOR = r"LinkedHashMap_LinkedHashMap$_empty";
@@ -21,7 +23,7 @@
asyncTest(() async {
var collector = new OutputCollector();
var result = await runCompiler(
- memorySourceFiles: TEST_SOURCE, outputProvider: collector);
+ memorySourceFiles: TEST_SOURCE, outputProvider: collector);
var compiler = result.compiler;
String generated = collector.getOutput('', 'js');
Expect.isFalse(generated.contains(HASHMAP_EMPTY_CONSTRUCTOR));
diff --git a/tests/compiler/dart2js/uri_extras_test.dart b/tests/compiler/dart2js/uri_extras_test.dart
index 6e263d6..b53db4b 100644
--- a/tests/compiler/dart2js/uri_extras_test.dart
+++ b/tests/compiler/dart2js/uri_extras_test.dart
@@ -6,7 +6,6 @@
import 'package:compiler/src/util/uri_extras.dart';
-
void testRelativize() {
void c(String expected, String base, String path, bool isWindows) {
if (isWindows == null) {
@@ -27,18 +26,15 @@
Expect.stringEquals(expected, r);
}
- test(Uri.parse('file:$base'),
- Uri.parse('file:$path'));
+ test(Uri.parse('file:$base'), Uri.parse('file:$path'));
- test(Uri.parse('FILE:$base'),
- Uri.parse('FILE:$path'));
+ test(Uri.parse('FILE:$base'), Uri.parse('FILE:$path'));
- test(Uri.parse('file:$base'),
- Uri.parse('FILE:$path'));
+ test(Uri.parse('file:$base'), Uri.parse('FILE:$path'));
- test(Uri.parse('FILE:$base'),
- Uri.parse('file:$path'));
+ test(Uri.parse('FILE:$base'), Uri.parse('file:$path'));
}
+
c('bar', '/', '/bar', null);
c('bar', '/foo', '/bar', null);
c('/bar', '/foo/', '/bar', null);
@@ -51,44 +47,40 @@
c('BAR', '///c:/foo', '///c:/BAR', true);
c('/c:/BAR', '///c:/foo/', '///c:/BAR', true);
- c('../sdk/lib/_internal/compiler/implementation/dart2js.dart',
- '///C:/Users/person/dart_checkout_for_stuff/dart/ReleaseIA32/dart.exe',
- '///c:/Users/person/dart_checkout_for_stuff/dart/sdk/lib/_internal/compiler/'
- 'implementation/dart2js.dart',
- true);
+ c(
+ '../sdk/lib/_internal/compiler/implementation/dart2js.dart',
+ '///C:/Users/person/dart_checkout_for_stuff/dart/ReleaseIA32/dart.exe',
+ '///c:/Users/person/dart_checkout_for_stuff/dart/sdk/lib/_internal/compiler/'
+ 'implementation/dart2js.dart',
+ true);
c('/Users/person/file.dart', '/users/person/', '/Users/person/file.dart',
- false);
+ false);
c('file.dart', '/Users/person/', '/Users/person/file.dart', null);
c('../person/file.dart', '/Users/other/', '/Users/person/file.dart', false);
c('/Users/person/file.dart', '/Users/other/', '/Users/person/file.dart',
- true);
+ true);
c('out.js.map', '/Users/person/out.js', '/Users/person/out.js.map', null);
- c('../person/out.js.map',
- '/Users/other/out.js',
- '/Users/person/out.js.map', false);
+ c('../person/out.js.map', '/Users/other/out.js', '/Users/person/out.js.map',
+ false);
- c('/Users/person/out.js.map',
- '/Users/other/out.js',
- '/Users/person/out.js.map', true);
+ c('/Users/person/out.js.map', '/Users/other/out.js',
+ '/Users/person/out.js.map', true);
c('out.js', '/Users/person/out.js.map', '/Users/person/out.js', null);
- c('../person/out.js',
- '/Users/other/out.js.map',
- '/Users/person/out.js', false);
+ c('../person/out.js', '/Users/other/out.js.map', '/Users/person/out.js',
+ false);
- c('/Users/person/out.js',
- '/Users/other/out.js.map',
- '/Users/person/out.js', true);
+ c('/Users/person/out.js', '/Users/other/out.js.map', '/Users/person/out.js',
+ true);
c('out.js', '/out.js.map', '/out.js', null);
-
}
void main() {
diff --git a/tests/compiler/dart2js/uri_retention_test.dart b/tests/compiler/dart2js/uri_retention_test.dart
index 8a7a47f..d841490 100644
--- a/tests/compiler/dart2js/uri_retention_test.dart
+++ b/tests/compiler/dart2js/uri_retention_test.dart
@@ -9,8 +9,7 @@
import 'package:expect/expect.dart';
import "package:async_helper/async_helper.dart";
-import 'memory_compiler.dart' show
- runCompiler, OutputCollector;
+import 'memory_compiler.dart' show runCompiler, OutputCollector;
Future<String> compileSources(sources, {bool minify, bool preserveUri}) async {
var options = [];
@@ -24,9 +23,9 @@
return outputCollector.getOutput('', 'js');
}
-Future test(sources, { bool libName, bool fileName }) {
- return
- compileSources(sources, minify: false, preserveUri: false).then((output) {
+Future test(sources, {bool libName, bool fileName}) {
+ return compileSources(sources, minify: false, preserveUri: false)
+ .then((output) {
// Unminified the sources should always contain the library name and the
// file name.
Expect.isTrue(output.contains("main_lib"));
@@ -47,13 +46,14 @@
void main() {
asyncTest(() {
return new Future.value()
- .then((_) => test(MEMORY_SOURCE_FILES1, libName: false, fileName: false))
- .then((_) => test(MEMORY_SOURCE_FILES2, libName: true, fileName: false))
- .then((_) => test(MEMORY_SOURCE_FILES3, libName: true, fileName: true));
+ .then(
+ (_) => test(MEMORY_SOURCE_FILES1, libName: false, fileName: false))
+ .then((_) => test(MEMORY_SOURCE_FILES2, libName: true, fileName: false))
+ .then((_) => test(MEMORY_SOURCE_FILES3, libName: true, fileName: true));
});
}
-const MEMORY_SOURCE_FILES1 = const <String, String> {
+const MEMORY_SOURCE_FILES1 = const <String, String>{
'main.dart': """
library main_lib;
@@ -68,9 +68,8 @@
""",
};
-
// Requires the library name, but not the URIs.
-const MEMORY_SOURCE_FILES2 = const <String, String> {
+const MEMORY_SOURCE_FILES2 = const <String, String>{
'main.dart': """
library main_lib;
@@ -89,7 +88,7 @@
print(reflectClass(A).declarations.length);
}
""",
- 'file2.dart': """
+ 'file2.dart': """
library other_lib;
class B {
@@ -99,7 +98,7 @@
};
// Requires the uri (and will contain the library-name, too).
-const MEMORY_SOURCE_FILES3 = const <String, String> {
+const MEMORY_SOURCE_FILES3 = const <String, String>{
'main.dart': """
library main_lib;
diff --git a/tests/compiler/dart2js/use_strict_test.dart b/tests/compiler/dart2js/use_strict_test.dart
index d3eb09b..0461fb7 100644
--- a/tests/compiler/dart2js/use_strict_test.dart
+++ b/tests/compiler/dart2js/use_strict_test.dart
@@ -9,7 +9,7 @@
// Use strict does not allow parameters or locals named "arguments" or "eval".
const MEMORY_SOURCE_FILES = const {
- 'main.dart': '''
+ 'main.dart': '''
class A {
final arguments;
final eval;
@@ -42,7 +42,8 @@
for (int i = 0; i < list.length; i++) {
print(list[i].foo(i, i + 1));
}
- }'''};
+ }'''
+};
main() {
OutputCollector collector = new OutputCollector();
@@ -54,9 +55,8 @@
// Skip comments.
List<String> lines = jsOutput.split("\n");
RegExp commentLine = new RegExp(r' *//');
- String filtered = lines
- .where((String line) => !commentLine.hasMatch(line))
- .join("\n");
+ String filtered =
+ lines.where((String line) => !commentLine.hasMatch(line)).join("\n");
// TODO(floitsch): we will need to adjust this filter if we start using
// 'eval' or 'arguments' ourselves. Currently we disallow any 'eval' or
diff --git a/tests/compiler/dart2js/user_crash_test.dart b/tests/compiler/dart2js/user_crash_test.dart
index 305de2a..0af3e67 100644
--- a/tests/compiler/dart2js/user_crash_test.dart
+++ b/tests/compiler/dart2js/user_crash_test.dart
@@ -13,34 +13,43 @@
main() {
asyncTest(() async {
test('Empty program', await run());
- test('Crash diagnostics',
- await run(diagnostics: new CrashingDiagnostics()),
- expectedLines: [
- 'Uncaught exception in diagnostic handler: $EXCEPTION',
- null /* Stack trace*/],
- expectedExceptions: [EXCEPTION]);
- test('Throw in package discovery',
- await run(packagesDiscoveryProvider: (_) { throw EXCEPTION; }),
- expectedLines: [
- 'Uncaught exception in package discovery: $EXCEPTION',
- null /* Stack trace*/],
- expectedExceptions: [EXCEPTION]);
- test('new Future.error in package discovery',
- await run(packagesDiscoveryProvider:
- (_) => new Future.error(EXCEPTION)),
- expectedExceptions: [EXCEPTION]);
+ test('Crash diagnostics', await run(diagnostics: new CrashingDiagnostics()),
+ expectedLines: [
+ 'Uncaught exception in diagnostic handler: $EXCEPTION',
+ null /* Stack trace*/
+ ],
+ expectedExceptions: [
+ EXCEPTION
+ ]);
+ test(
+ 'Throw in package discovery',
+ await run(packagesDiscoveryProvider: (_) {
+ throw EXCEPTION;
+ }),
+ expectedLines: [
+ 'Uncaught exception in package discovery: $EXCEPTION',
+ null /* Stack trace*/
+ ],
+ expectedExceptions: [
+ EXCEPTION
+ ]);
+ test(
+ 'new Future.error in package discovery',
+ await run(
+ packagesDiscoveryProvider: (_) => new Future.error(EXCEPTION)),
+ expectedExceptions: [EXCEPTION]);
test('Throw in input provider',
- await run(memorySourceFiles: new CrashingMap()),
- expectedLines: [
- 'Uncaught exception in input provider: $EXCEPTION',
- null, // Stack trace
- 'memory:main.dart:\nError: $EXCEPTION' /* READ_SELF_ERROR */]);
+ await run(memorySourceFiles: new CrashingMap()),
+ expectedLines: [
+ 'Uncaught exception in input provider: $EXCEPTION',
+ null, // Stack trace
+ 'memory:main.dart:\nError: $EXCEPTION' /* READ_SELF_ERROR */
+ ]);
});
}
void test(String title, RunResult result,
- {List expectedLines: const [],
- List expectedExceptions: const []}) {
+ {List expectedLines: const [], List expectedExceptions: const []}) {
print('--------------------------------------------------------------------');
print('Running $title');
print('--------------------------------------------------------------------');
@@ -61,8 +70,8 @@
Future<RunResult> run(
{Map<String, String> memorySourceFiles: const {'main.dart': 'main() {}'},
- CompilerDiagnostics diagnostics,
- PackagesDiscoveryProvider packagesDiscoveryProvider}) async {
+ CompilerDiagnostics diagnostics,
+ PackagesDiscoveryProvider packagesDiscoveryProvider}) async {
RunResult result = new RunResult();
await runZoned(() async {
try {
@@ -74,10 +83,8 @@
} catch (e) {
result.exceptions.add(e);
}
-
- },
- zoneSpecification: new ZoneSpecification(print:
- (Zone self, ZoneDelegate parent, Zone zone, String line) {
+ }, zoneSpecification: new ZoneSpecification(
+ print: (Zone self, ZoneDelegate parent, Zone zone, String line) {
result.lines.add(line);
}));
return result;
@@ -99,4 +106,4 @@
operator [](_) => throw EXCEPTION;
noSuchMethod(_) => null;
-}
\ No newline at end of file
+}
diff --git a/tests/compiler/dart2js/value_range2_test.dart b/tests/compiler/dart2js/value_range2_test.dart
index d14311b..3d97c5e 100644
--- a/tests/compiler/dart2js/value_range2_test.dart
+++ b/tests/compiler/dart2js/value_range2_test.dart
@@ -55,7 +55,6 @@
}
checkSubRange(Range one, Range two, [lower, upper]) {
-
buildBound(one, two) {
// Create a bound just like our current implementation in dart2js does.
if (two is IntValue) {
diff --git a/tests/compiler/dart2js/value_range3_test.dart b/tests/compiler/dart2js/value_range3_test.dart
index 91c3c37..851a36a 100644
--- a/tests/compiler/dart2js/value_range3_test.dart
+++ b/tests/compiler/dart2js/value_range3_test.dart
@@ -31,4 +31,3 @@
Expect.isFalse(code.contains('ioore'));
});
}
-
diff --git a/tests/compiler/dart2js/value_range_test.dart b/tests/compiler/dart2js/value_range_test.dart
index 0cdb5de..fe7c1de 100644
--- a/tests/compiler/dart2js/value_range_test.dart
+++ b/tests/compiler/dart2js/value_range_test.dart
@@ -16,7 +16,7 @@
const int BELOW_ZERO_CHECK = 6;
final List TESTS = [
-"""
+ """
main() {
var a = new List();
var sum = 0;
@@ -26,9 +26,8 @@
return sum;
}
""",
-REMOVED,
-
-"""
+ REMOVED,
+ """
main(value) {
var a = new List();
var sum = 0;
@@ -38,9 +37,8 @@
return sum;
}
""",
-ABOVE_ZERO,
-
-"""
+ ABOVE_ZERO,
+ """
main(check) {
// Make sure value is an int.
var value = check ? 42 : 54;
@@ -52,89 +50,78 @@
return sum;
}
""",
-REMOVED,
-
-"""
+ REMOVED,
+ """
main() {
var a = new List();
return a[0];
}
""",
-KEPT,
-
-"""
+ KEPT,
+ """
main() {
var a = new List();
return a.removeLast();
}
""",
-KEPT,
-
-"""
+ KEPT,
+ """
main() {
var a = new List(4);
return a[0];
}
""",
-REMOVED,
-
-"""
+ REMOVED,
+ """
main() {
var a = new List(4);
return a.removeLast();
}
""",
-REMOVED,
-
-"""
+ REMOVED,
+ """
main(value) {
var a = new List(value);
return a[value];
}
""",
-KEPT,
-
-"""
+ KEPT,
+ """
main(value) {
var a = new List(1024);
return a[1023 & value];
}
""",
-REMOVED,
-
-"""
+ REMOVED,
+ """
main(value) {
var a = new List(1024);
return a[1024 & value];
}
""",
-ABOVE_ZERO,
-
-"""
+ ABOVE_ZERO,
+ """
main(value) {
var a = new List();
return a[1];
}
""",
-ABOVE_ZERO,
-
-"""
+ ABOVE_ZERO,
+ """
main(value, call) {
var a = new List();
return a[value] + call() + a[value];
}
""",
-ONE_ZERO_CHECK,
-
-"""
+ ONE_ZERO_CHECK,
+ """
main(value) {
var a = new List();
return a[1] + a[0];
}
""",
-ONE_CHECK,
-
-"""
+ ONE_CHECK,
+ """
main() {
var a = new List();
var sum = 0;
@@ -144,9 +131,8 @@
return sum;
}
""",
-REMOVED,
-
-"""
+ REMOVED,
+ """
main() {
var a = new List();
var sum = 0;
@@ -156,9 +142,8 @@
return sum;
}
""",
-REMOVED,
-
-"""
+ REMOVED,
+ """
main(value) {
value = value is int ? value as int : 42;
int sum = ~value;
@@ -169,9 +154,8 @@
return a[value];
}
""",
-REMOVED,
-
-"""
+ REMOVED,
+ """
main(value) {
value = value is int ? value as int : 42;
int sum = ~value;
@@ -184,8 +168,8 @@
}
}
""",
-REMOVED,
-"""
+ REMOVED,
+ """
main(value) {
value = value is int ? value as int : 42;
int sum = ~value;
@@ -196,8 +180,8 @@
return a[value];
}
""",
-REMOVED,
-"""
+ REMOVED,
+ """
main(value) {
var a = new List(4);
var sum = 0;
@@ -208,8 +192,8 @@
return sum;
}
""",
-REMOVED,
-"""
+ REMOVED,
+ """
main(value) {
var a = new List(5);
var sum = 0;
@@ -220,8 +204,8 @@
return sum;
}
""",
-REMOVED,
-"""
+ REMOVED,
+ """
main(value) {
var a = new List(6);
var sum = 0;
@@ -232,8 +216,8 @@
return sum;
}
""",
-BELOW_ZERO_CHECK,
-"""
+ BELOW_ZERO_CHECK,
+ """
main(value) {
var a = new List(7);
var sum = 0;
@@ -244,8 +228,8 @@
return sum;
}
""",
-BELOW_ZERO_CHECK,
-"""
+ BELOW_ZERO_CHECK,
+ """
main(value) {
var a = new List(7);
var sum = 0;
@@ -255,16 +239,14 @@
return sum;
}
""",
-BELOW_ZERO_CHECK,
+ BELOW_ZERO_CHECK,
];
// TODO(ahe): It would probably be better if this test used the real
// core library sources, as its purpose is to detect failure to
// optimize fixed-sized arrays.
Future expect(String code, int kind) {
- return compile(
- code,
- check: (String generated) {
+ return compile(code, check: (String generated) {
switch (kind) {
case REMOVED:
Expect.isTrue(!generated.contains('ioore'));
@@ -305,7 +287,6 @@
});
}
-
main() {
int i = 0;
Future testNext() {
diff --git a/tests/compiler/dart2js/warnings_checker.dart b/tests/compiler/dart2js/warnings_checker.dart
index 3e50eae..fdbd12c 100644
--- a/tests/compiler/dart2js/warnings_checker.dart
+++ b/tests/compiler/dart2js/warnings_checker.dart
@@ -23,61 +23,62 @@
bool warningsMismatch = false;
bool verbose = arguments != null && arguments.contains('-v');
asyncTest(() => Future.forEach(tests.keys, (String test) async {
- Uri uri = script.resolve('../../$test');
- String source = UTF8.decode(readAll(uriPathToNative(uri.path)));
- SourceFile file = new StringSourceFile(
- uri, relativize(currentDirectory, uri, isWindows), source);
- Map<int,String> expectedWarnings = {};
- int lineNo = 0;
- for (String line in source.split('\n')) {
- if (line.contains('///') &&
- (line.contains('static type warning') ||
- line.contains('static warning'))) {
- expectedWarnings[lineNo] = line;
- }
- lineNo++;
- }
- Set<int> unseenWarnings = new Set<int>.from(expectedWarnings.keys);
- DiagnosticCollector collector = new DiagnosticCollector();
- await runCompiler(
- entryPoint: uri,
- diagnosticHandler: collector,
- options: [Flags.analyzeOnly],
- showDiagnostics: verbose);
- Map<String, List<int>> statusMap = tests[test];
- // Line numbers with known unexpected warnings.
- List<int> unexpectedStatus = [];
- if (statusMap != null && statusMap.containsKey('unexpected')) {
- unexpectedStatus = statusMap['unexpected'];
- }
- // Line numbers with known missing warnings.
- List<int> missingStatus = [];
- if (statusMap != null && statusMap.containsKey('missing')) {
- missingStatus = statusMap['missing'];
- }
- for (CollectedMessage message in collector.warnings) {
- Expect.equals(uri, message.uri);
- int lineNo = file.getLine(message.begin);
- if (expectedWarnings.containsKey(lineNo)) {
- unseenWarnings.remove(lineNo);
- } else if (!unexpectedStatus.contains(lineNo+1)) {
- warningsMismatch = true;
- print(file.getLocationMessage(
- 'Unexpected warning: ${message.message}',
- message.begin, message.end));
- }
- }
- if (!unseenWarnings.isEmpty) {
- for (int lineNo in unseenWarnings) {
- if (!missingStatus.contains(lineNo+1)) {
- warningsMismatch = true;
- String line = expectedWarnings[lineNo];
- print('$uri [${lineNo+1}]: Missing static type warning.');
- print(line);
+ Uri uri = script.resolve('../../$test');
+ String source = UTF8.decode(readAll(uriPathToNative(uri.path)));
+ SourceFile file = new StringSourceFile(
+ uri, relativize(currentDirectory, uri, isWindows), source);
+ Map<int, String> expectedWarnings = {};
+ int lineNo = 0;
+ for (String line in source.split('\n')) {
+ if (line.contains('///') &&
+ (line.contains('static type warning') ||
+ line.contains('static warning'))) {
+ expectedWarnings[lineNo] = line;
+ }
+ lineNo++;
}
- }
- }
- }).then((_) {
- Expect.isFalse(warningsMismatch);
- }));
+ Set<int> unseenWarnings = new Set<int>.from(expectedWarnings.keys);
+ DiagnosticCollector collector = new DiagnosticCollector();
+ await runCompiler(
+ entryPoint: uri,
+ diagnosticHandler: collector,
+ options: [Flags.analyzeOnly],
+ showDiagnostics: verbose);
+ Map<String, List<int>> statusMap = tests[test];
+ // Line numbers with known unexpected warnings.
+ List<int> unexpectedStatus = [];
+ if (statusMap != null && statusMap.containsKey('unexpected')) {
+ unexpectedStatus = statusMap['unexpected'];
+ }
+ // Line numbers with known missing warnings.
+ List<int> missingStatus = [];
+ if (statusMap != null && statusMap.containsKey('missing')) {
+ missingStatus = statusMap['missing'];
+ }
+ for (CollectedMessage message in collector.warnings) {
+ Expect.equals(uri, message.uri);
+ int lineNo = file.getLine(message.begin);
+ if (expectedWarnings.containsKey(lineNo)) {
+ unseenWarnings.remove(lineNo);
+ } else if (!unexpectedStatus.contains(lineNo + 1)) {
+ warningsMismatch = true;
+ print(file.getLocationMessage(
+ 'Unexpected warning: ${message.message}',
+ message.begin,
+ message.end));
+ }
+ }
+ if (!unseenWarnings.isEmpty) {
+ for (int lineNo in unseenWarnings) {
+ if (!missingStatus.contains(lineNo + 1)) {
+ warningsMismatch = true;
+ String line = expectedWarnings[lineNo];
+ print('$uri [${lineNo+1}]: Missing static type warning.');
+ print(line);
+ }
+ }
+ }
+ }).then((_) {
+ Expect.isFalse(warningsMismatch);
+ }));
}
diff --git a/tests/compiler/dart2js/world_test.dart b/tests/compiler/dart2js/world_test.dart
index 0109f8d..b80f0c0 100644
--- a/tests/compiler/dart2js/world_test.dart
+++ b/tests/compiler/dart2js/world_test.dart
@@ -8,8 +8,7 @@
import 'package:async_helper/async_helper.dart';
import 'type_test_helper.dart';
import 'package:compiler/src/common.dart';
-import 'package:compiler/src/elements/elements.dart'
- show Element, ClassElement;
+import 'package:compiler/src/elements/elements.dart' show Element, ClassElement;
import 'package:compiler/src/universe/class_set.dart';
import 'package:compiler/src/world.dart' show ClassWorld;
@@ -21,7 +20,8 @@
}
testClassSets() async {
- var env = await TypeEnvironment.create(r"""
+ var env = await TypeEnvironment.create(
+ r"""
class A implements X {}
class B {}
class C_Super extends A {}
@@ -56,21 +56,20 @@
ClassElement G = env.getElement("G");
ClassElement X = env.getElement("X");
- void checkClasses(
- String property,
- ClassElement cls,
- Iterable<ClassElement> foundClasses,
- List<ClassElement> expectedClasses,
+ void checkClasses(String property, ClassElement cls,
+ Iterable<ClassElement> foundClasses, List<ClassElement> expectedClasses,
{bool exact: true}) {
-
for (ClassElement expectedClass in expectedClasses) {
- Expect.isTrue(foundClasses.contains(expectedClass),
+ Expect.isTrue(
+ foundClasses.contains(expectedClass),
"Expect $expectedClass in '$property' on $cls. "
"Found:\n ${foundClasses.join('\n ')}\n"
"${env.compiler.world.dump(cls)}");
}
if (exact) {
- Expect.equals(expectedClasses.length, foundClasses.length,
+ Expect.equals(
+ expectedClasses.length,
+ foundClasses.length,
"Unexpected classes "
"${foundClasses.where((c) => !expectedClasses.contains(c))} "
"in '$property' on $cls.\n"
@@ -78,14 +77,11 @@
}
}
- void check(
- String property,
- ClassElement cls,
- Iterable<ClassElement> foundClasses,
- List<ClassElement> expectedClasses,
+ void check(String property, ClassElement cls,
+ Iterable<ClassElement> foundClasses, List<ClassElement> expectedClasses,
{bool exact: true,
- void forEach(ClassElement cls, ForEachFunction f),
- int getCount(ClassElement cls)}) {
+ void forEach(ClassElement cls, ForEachFunction f),
+ int getCount(ClassElement cls)}) {
checkClasses(property, cls, foundClasses, expectedClasses, exact: exact);
if (forEach != null) {
@@ -93,69 +89,49 @@
forEach(cls, (ClassElement c) {
visited.add(c);
});
- checkClasses(
- 'forEach($property)', cls, visited, expectedClasses, exact: exact);
+ checkClasses('forEach($property)', cls, visited, expectedClasses,
+ exact: exact);
}
if (getCount != null && exact) {
int count = getCount(cls);
- Expect.equals(expectedClasses.length, count,
+ Expect.equals(
+ expectedClasses.length,
+ count,
"Unexpected class count in '$property' on $cls.\n"
"${env.compiler.world.dump(cls)}");
}
-
}
- void testSubclasses(
- ClassElement cls,
- List<ClassElement> expectedClasses,
+ void testSubclasses(ClassElement cls, List<ClassElement> expectedClasses,
{bool exact: true}) {
- check(
- 'subclassesOf',
- cls,
- classWorld.subclassesOf(cls),
- expectedClasses,
- exact: exact);
+ check('subclassesOf', cls, classWorld.subclassesOf(cls), expectedClasses,
+ exact: exact);
}
void testStrictSubclasses(
- ClassElement cls,
- List<ClassElement> expectedClasses,
+ ClassElement cls, List<ClassElement> expectedClasses,
{bool exact: true}) {
- check(
- 'strictSubclassesOf',
- cls,
- classWorld.strictSubclassesOf(cls),
- expectedClasses,
- exact: exact,
- forEach: classWorld.forEachStrictSubclassOf,
- getCount: classWorld.strictSubclassCount);
+ check('strictSubclassesOf', cls, classWorld.strictSubclassesOf(cls),
+ expectedClasses,
+ exact: exact,
+ forEach: classWorld.forEachStrictSubclassOf,
+ getCount: classWorld.strictSubclassCount);
}
- void testStrictSubtypes(
- ClassElement cls,
- List<ClassElement> expectedClasses,
+ void testStrictSubtypes(ClassElement cls, List<ClassElement> expectedClasses,
{bool exact: true}) {
- check(
- 'strictSubtypesOf',
- cls,
- classWorld.strictSubtypesOf(cls),
- expectedClasses,
- exact: exact,
- forEach: classWorld.forEachStrictSubtypeOf,
- getCount: classWorld.strictSubtypeCount);
+ check('strictSubtypesOf', cls, classWorld.strictSubtypesOf(cls),
+ expectedClasses,
+ exact: exact,
+ forEach: classWorld.forEachStrictSubtypeOf,
+ getCount: classWorld.strictSubtypeCount);
}
- void testMixinUses(
- ClassElement cls,
- List<ClassElement> expectedClasses,
+ void testMixinUses(ClassElement cls, List<ClassElement> expectedClasses,
{bool exact: true}) {
- check(
- 'mixinUsesOf',
- cls,
- classWorld.mixinUsesOf(cls),
- expectedClasses,
- exact: exact);
+ check('mixinUsesOf', cls, classWorld.mixinUsesOf(cls), expectedClasses,
+ exact: exact);
}
testSubclasses(Object_, [A, B, C, D, E, F, G], exact: false);
@@ -200,7 +176,8 @@
}
testProperties() async {
- var env = await TypeEnvironment.create(r"""
+ var env = await TypeEnvironment.create(
+ r"""
class A {}
class A1 extends A {}
class A2 implements A {}
@@ -259,9 +236,7 @@
useMockCompiler: false);
ClassWorld classWorld = env.compiler.world;
- check(String name,
- {bool hasStrictSubtype,
- bool hasOnlySubclasses}) {
+ check(String name, {bool hasStrictSubtype, bool hasOnlySubclasses}) {
ClassElement cls = env.getElement(name);
Expect.equals(hasStrictSubtype, classWorld.hasAnyStrictSubtype(cls),
"Unexpected hasAnyStrictSubtype property on $cls.");
diff --git a/tests/compiler/dart2js/zero_termination_test.dart b/tests/compiler/dart2js/zero_termination_test.dart
index 7599bc5..36022c1 100644
--- a/tests/compiler/dart2js/zero_termination_test.dart
+++ b/tests/compiler/dart2js/zero_termination_test.dart
@@ -32,9 +32,9 @@
final File file = new File(requestPath.toFilePath());
return file.exists().then((bool found) {
if (found) {
- file.openRead()
- .pipe(request.response)
- .catchError((e) { _sendNotFound(request.response); });
+ file.openRead().pipe(request.response).catchError((e) {
+ _sendNotFound(request.response);
+ });
} else {
_sendNotFound(request.response);
}
@@ -86,7 +86,8 @@
}
Future testHttp() {
- return HttpServer.bind(InternetAddress.LOOPBACK_IP_V4, 0)
+ return HttpServer
+ .bind(InternetAddress.LOOPBACK_IP_V4, 0)
.then((HttpServer server) => serverRunning(server));
}
@@ -98,7 +99,7 @@
await testFile();
await testHttp();
} finally {
- await tempDir.delete(recursive:true);
+ await tempDir.delete(recursive: true);
}
}
diff --git a/tests/compiler/dart2js_extra/10216a_test.dart b/tests/compiler/dart2js_extra/10216a_test.dart
index a023d6c..5032123 100644
--- a/tests/compiler/dart2js_extra/10216a_test.dart
+++ b/tests/compiler/dart2js_extra/10216a_test.dart
@@ -6,12 +6,11 @@
// Tests codegen of methods reached only via mixin.
-class A {
+class A {
foo(x, [y]) => '$x;$y';
}
-class B extends A with M1, M2, M3 {
-}
+class B extends A with M1, M2, M3 {}
class M1 {}
@@ -32,9 +31,9 @@
// makeB enters the compilation worklist after main, so the selectors are
// registered before the classes.
var b = makeB();
- Expect.equals('1;2', b.foo(1,2));
+ Expect.equals('1;2', b.foo(1, 2));
Expect.equals('2;null', b.foo(2));
Expect.equals('P 3', b.plain(3));
- Expect.equals('100,4', b.bar(4,100));
+ Expect.equals('100,4', b.bar(4, 100));
Expect.equals('null,5', b.bar(5));
}
diff --git a/tests/compiler/dart2js_extra/10216b_test.dart b/tests/compiler/dart2js_extra/10216b_test.dart
index 93394cb..a2ad8bb 100644
--- a/tests/compiler/dart2js_extra/10216b_test.dart
+++ b/tests/compiler/dart2js_extra/10216b_test.dart
@@ -6,12 +6,11 @@
// Tests codegen of methods reached only via mixin.
-class A {
+class A {
foo(x, [y]) => '$x;$y';
}
-class B extends A with M1, M2, M3 {
-}
+class B extends A with M1, M2, M3 {}
class M1 {}
@@ -26,10 +25,10 @@
test() {
var b = [new A(), new B()].last as B;
- Expect.equals('1;2', b.foo(1,2));
+ Expect.equals('1;2', b.foo(1, 2));
Expect.equals('2;null', b.foo(2));
Expect.equals('P 3', b.plain(3));
- Expect.equals('100,4', b.bar(4,100));
+ Expect.equals('100,4', b.bar(4, 100));
Expect.equals('null,5', b.bar(5));
}
diff --git a/tests/compiler/dart2js_extra/11673_test.dart b/tests/compiler/dart2js_extra/11673_test.dart
index f17280a..1d7e667 100644
--- a/tests/compiler/dart2js_extra/11673_test.dart
+++ b/tests/compiler/dart2js_extra/11673_test.dart
@@ -8,10 +8,13 @@
// application.
class JSIB {}
+
class TD {}
+
class M {
foo() => 123;
}
+
class I8 extends TD with M implements JSIB {}
use(x) {
diff --git a/tests/compiler/dart2js_extra/12320_test.dart b/tests/compiler/dart2js_extra/12320_test.dart
index 60317f9..d47c05a 100644
--- a/tests/compiler/dart2js_extra/12320_test.dart
+++ b/tests/compiler/dart2js_extra/12320_test.dart
@@ -18,7 +18,7 @@
}
void run(f) {
- if (f is !int) {
+ if (f is! int) {
f(1);
} else {
x = f;
@@ -31,7 +31,7 @@
void callFoo() {
log += '[Foo]';
- switch(x) {
+ switch (x) {
case 0:
log += '[Foo 0]';
break;
diff --git a/tests/compiler/dart2js_extra/16400_test.dart b/tests/compiler/dart2js_extra/16400_test.dart
index 221eaac..7902f07 100644
--- a/tests/compiler/dart2js_extra/16400_test.dart
+++ b/tests/compiler/dart2js_extra/16400_test.dart
@@ -3,7 +3,8 @@
// BSD-style license that can be found in the LICENSE file.
main() {
- L: {
+ L:
+ {
var seeMe = 0;
if (seeMe == 0) {
++seeMe;
@@ -17,4 +18,3 @@
}
}
}
-
diff --git a/tests/compiler/dart2js_extra/17094_test.dart b/tests/compiler/dart2js_extra/17094_test.dart
index 25452f2..41fba87 100644
--- a/tests/compiler/dart2js_extra/17094_test.dart
+++ b/tests/compiler/dart2js_extra/17094_test.dart
@@ -10,7 +10,10 @@
class A {
int a = 0;
- toString() { ++a; return 'A'; }
+ toString() {
+ ++a;
+ return 'A';
+ }
}
// Many interpolations to make function too big to inline.
@@ -20,9 +23,9 @@
test(a) {
if (a == null) return;
if (never) a.a += 1;
- var b = a.a; // field load
- var c = fmt(a); // field modified through implicit call to toString()
- var d = a.a; // field re-load
+ var b = a.a; // field load
+ var c = fmt(a); // field modified through implicit call to toString()
+ var d = a.a; // field re-load
Expect.equals('A 0 AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA 30', '$a $b $c $d');
// Extra use of [fmt] to prevent inlining on basis of single reference.
diff --git a/tests/compiler/dart2js_extra/17645_test.dart b/tests/compiler/dart2js_extra/17645_test.dart
index 67d8de8..7469a6c 100644
--- a/tests/compiler/dart2js_extra/17645_test.dart
+++ b/tests/compiler/dart2js_extra/17645_test.dart
@@ -14,47 +14,50 @@
var log = [];
-test1(a, xs) { // Called with a = [null|exact=A]
+test1(a, xs) {
+ // Called with a = [null|exact=A]
log.clear();
for (var x in xs) {
if (a != null) {
- log.add('${a.foo}.$x'); // a.foo must not be hoisted
+ log.add('${a.foo}.$x'); // a.foo must not be hoisted
}
}
return '$log';
}
-test2(a, xs) { // Called with a = [exact=A]
+test2(a, xs) {
+ // Called with a = [exact=A]
log.clear();
for (var x in xs) {
if (a != null) {
- log.add('${a.foo}.$x'); // a.foo may be hoisted
+ log.add('${a.foo}.$x'); // a.foo may be hoisted
}
}
return '$log';
}
-test3(a, xs) { // Called with a = [null|exact=A]
+test3(a, xs) {
+ // Called with a = [null|exact=A]
log.clear();
for (var x in xs) {
if (a is A) {
- log.add('${a.foo}.$x'); // a.foo must not be hoisted
+ log.add('${a.foo}.$x'); // a.foo must not be hoisted
}
}
return '$log';
}
-test4(a, xs) { // Called with a = [exact=A]
+test4(a, xs) {
+ // Called with a = [exact=A]
log.clear();
for (var x in xs) {
if (a is A) {
- log.add('${a.foo}.$x'); // a.foo may be hoisted
+ log.add('${a.foo}.$x'); // a.foo may be hoisted
}
}
return '$log';
}
-
main() {
var a1 = new A('a1');
var a2 = new A('a2');
@@ -65,7 +68,6 @@
Expect.equals('[a1.22]', test2(a1, [22]));
Expect.equals('[a2.22]', test2(a2, [22]));
-
Expect.equals('[a1.33]', test3(a1, [33]));
Expect.equals('[]', test3(null, [2]));
diff --git a/tests/compiler/dart2js_extra/17856_test.dart b/tests/compiler/dart2js_extra/17856_test.dart
index 1e6fa63..aa5a243 100644
--- a/tests/compiler/dart2js_extra/17856_test.dart
+++ b/tests/compiler/dart2js_extra/17856_test.dart
@@ -7,7 +7,7 @@
// Regression test for Issue 17856.
void main() {
- var all = { "a": new A(), "b": new B() };
+ var all = {"a": new A(), "b": new B()};
A a = all["a"];
a.load();
@@ -16,22 +16,20 @@
class A {
Loader _loader = new Loader();
- load() => _loader.loadAll({
- 'a1': {}
- });
+ load() => _loader.loadAll({'a1': {}});
}
class B {
Loader _loader = new Loader();
load() => _loader.loadAll({
- 'a2': new DateTime.now(),
- });
+ 'a2': new DateTime.now(),
+ });
}
class Loader {
loadAll(Map assets) {
- for(String key in assets.keys) {
+ for (String key in assets.keys) {
Expect.isTrue(assets[key] is Map);
}
}
diff --git a/tests/compiler/dart2js_extra/18383_test.dart b/tests/compiler/dart2js_extra/18383_test.dart
index 1659129..e15526b 100644
--- a/tests/compiler/dart2js_extra/18383_test.dart
+++ b/tests/compiler/dart2js_extra/18383_test.dart
@@ -22,4 +22,3 @@
var m = f();
Expect.equals(m(66).foo(), "G(66).foo");
}
-
diff --git a/tests/compiler/dart2js_extra/19191_test.dart b/tests/compiler/dart2js_extra/19191_test.dart
index a5c4b56..7e628fd 100644
--- a/tests/compiler/dart2js_extra/19191_test.dart
+++ b/tests/compiler/dart2js_extra/19191_test.dart
@@ -6,7 +6,7 @@
class A {
var method;
-
+
noSuchMethod(Invocation invocation) {
if (invocation.isGetter) {
return method;
@@ -14,20 +14,20 @@
method = invocation.positionalArguments[0];
return null;
} else if (invocation.isMethod) {
- return Function.apply(method, invocation.positionalArguments,
- invocation.namedArguments);
+ return Function.apply(
+ method, invocation.positionalArguments, invocation.namedArguments);
} else {
throw new NoSuchMethodError(this, invocation.memberName,
invocation.positionalArguments, invocation.namedArguments);
}
}
-
+
init() {
closure_fails = (String str) {
return str.toUpperCase();
};
}
-
+
run() {
print(closure_fails("Hello World"));
}
@@ -38,4 +38,3 @@
a.init();
a.run();
}
-
diff --git a/tests/compiler/dart2js_extra/21166_test.dart b/tests/compiler/dart2js_extra/21166_test.dart
index bc8f63b..b060c1f 100644
--- a/tests/compiler/dart2js_extra/21166_test.dart
+++ b/tests/compiler/dart2js_extra/21166_test.dart
@@ -8,9 +8,10 @@
var a = [];
void doStuff() {
- if (a.length) { // This triggers a TypeConversion to bool in checked mode.
+ if (a.length) {
+ // This triggers a TypeConversion to bool in checked mode.
var element = a[0]; // This triggers a bounds check but a.length will have
- a.remove(element); // type [empty].
+ a.remove(element); // type [empty].
}
}
@@ -21,5 +22,3 @@
doStuff(); // This is expected to fail but not crash the compiler.
} catch (_) {}
}
-
-
diff --git a/tests/compiler/dart2js_extra/21351_test.dart b/tests/compiler/dart2js_extra/21351_test.dart
index 3f1d00e..f3c0e53 100644
--- a/tests/compiler/dart2js_extra/21351_test.dart
+++ b/tests/compiler/dart2js_extra/21351_test.dart
@@ -7,8 +7,8 @@
bool get flag => _flag;
}
-main () {
- var value1, value2;
+main() {
+ var value1, value2;
var count = 0;
for (var x = 0; x < 10; x++) {
@@ -27,4 +27,3 @@
if (count == 0) throw "FAIL";
}
-
diff --git a/tests/compiler/dart2js_extra/21666_test.dart b/tests/compiler/dart2js_extra/21666_test.dart
index ceb147a..857b0e3 100644
--- a/tests/compiler/dart2js_extra/21666_test.dart
+++ b/tests/compiler/dart2js_extra/21666_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.
-
// Regression test for issue 21666 - problems with method that has super calls.
//
// Use a method and getter with super calls in various ways.
@@ -12,8 +11,13 @@
@MirrorsUsed(targets: const [A, B, Object])
import 'dart:mirrors';
-class X { const X(); }
-class Y { const Y(); }
+class X {
+ const X();
+}
+
+class Y {
+ const Y();
+}
typedef fInt(int x);
typedef fString(String x);
diff --git a/tests/compiler/dart2js_extra/21724_test.dart b/tests/compiler/dart2js_extra/21724_test.dart
index a578ca6..eff9690 100644
--- a/tests/compiler/dart2js_extra/21724_test.dart
+++ b/tests/compiler/dart2js_extra/21724_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.
-
// Regression test for issue 21724 - invalid call to local closure
main() {
@@ -11,4 +10,3 @@
foo();
} catch (_) {}
}
-
diff --git a/tests/compiler/dart2js_extra/22776_test.dart b/tests/compiler/dart2js_extra/22776_test.dart
index e9f12ea..8c355f9 100644
--- a/tests/compiler/dart2js_extra/22776_test.dart
+++ b/tests/compiler/dart2js_extra/22776_test.dart
@@ -20,4 +20,3 @@
@AssumeDynamic()
@NoInline()
id(x) => x;
-
diff --git a/tests/compiler/dart2js_extra/22917_test.dart b/tests/compiler/dart2js_extra/22917_test.dart
index e4f46da..35a629a 100644
--- a/tests/compiler/dart2js_extra/22917_test.dart
+++ b/tests/compiler/dart2js_extra/22917_test.dart
@@ -7,7 +7,7 @@
import 'package:expect/expect.dart';
m(x) => print('x: $x');
-
+
test() => Function.apply(m, []);
main() {
diff --git a/tests/compiler/dart2js_extra/23056_test.dart b/tests/compiler/dart2js_extra/23056_test.dart
index c8953f2..a30e4ee 100644
--- a/tests/compiler/dart2js_extra/23056_test.dart
+++ b/tests/compiler/dart2js_extra/23056_test.dart
@@ -21,7 +21,8 @@
bool get foo => super.foo;
}
-@AssumeDynamic() @NoInline()
+@AssumeDynamic()
+@NoInline()
bool hide(bool x) => x;
main() {
diff --git a/tests/compiler/dart2js_extra/23264_test.dart b/tests/compiler/dart2js_extra/23264_test.dart
index 89538be..a834426 100644
--- a/tests/compiler/dart2js_extra/23264_test.dart
+++ b/tests/compiler/dart2js_extra/23264_test.dart
@@ -1,4 +1,7 @@
import 'package:expect/expect.dart';
-class A { A(ignore); }
+class A {
+ A(ignore);
+}
+
main() => Expect.throws(() => A(const [])); // oops, `new` is missing!
diff --git a/tests/compiler/dart2js_extra/23404_test.dart b/tests/compiler/dart2js_extra/23404_test.dart
index bfd52ba..65dd8fb 100644
--- a/tests/compiler/dart2js_extra/23404_test.dart
+++ b/tests/compiler/dart2js_extra/23404_test.dart
@@ -8,7 +8,7 @@
// Dart2js crashed when the global metadata had escaped characters. That
// happens, for example, when tearing off a function that uses a default
// argument containing escape characters.
-foo([a='\u00a0']) => a;
+foo([a = '\u00a0']) => a;
bar() => '';
@NoInline()
diff --git a/tests/compiler/dart2js_extra/23432_test.dart b/tests/compiler/dart2js_extra/23432_test.dart
index 385bbf1..b0fc3d9 100644
--- a/tests/compiler/dart2js_extra/23432_test.dart
+++ b/tests/compiler/dart2js_extra/23432_test.dart
@@ -9,10 +9,14 @@
import 'package:expect/expect.dart';
class N {
- noSuchMethod(i) { print('x'); return 42; }
+ noSuchMethod(i) {
+ print('x');
+ return 42;
+ }
}
-@NoInline() @AssumeDynamic()
+@NoInline()
+@AssumeDynamic()
get NEVER => false;
main() {
@@ -20,7 +24,9 @@
if (NEVER) c = new N();
var e;
try {
- c..toString()..add(88);
+ c
+ ..toString()
+ ..add(88);
} catch (ex) {
e = ex;
}
diff --git a/tests/compiler/dart2js_extra/26243_test.dart b/tests/compiler/dart2js_extra/26243_test.dart
index 156f54d..7f09cf3 100644
--- a/tests/compiler/dart2js_extra/26243_test.dart
+++ b/tests/compiler/dart2js_extra/26243_test.dart
@@ -35,6 +35,6 @@
foo();
bar();
baz();
- Expect.listEquals(['foo 0 1', 'bar 0 1', 'baz-notry 0 1', 'baz-try 0 1'],
- trace);
+ Expect.listEquals(
+ ['foo 0 1', 'bar 0 1', 'baz-notry 0 1', 'baz-try 0 1'], trace);
}
diff --git a/tests/compiler/dart2js_extra/27199_test.dart b/tests/compiler/dart2js_extra/27199_test.dart
index 4409247..485bf3a 100644
--- a/tests/compiler/dart2js_extra/27199_test.dart
+++ b/tests/compiler/dart2js_extra/27199_test.dart
@@ -16,7 +16,8 @@
Map<String, ItemListFilter<T>> f = {};
}
-@NoInline() @AssumeDynamic()
+@NoInline()
+@AssumeDynamic()
confuse(x) => x;
main() {
diff --git a/tests/compiler/dart2js_extra/27354_test.dart b/tests/compiler/dart2js_extra/27354_test.dart
new file mode 100644
index 0000000..942dc49
--- /dev/null
+++ b/tests/compiler/dart2js_extra/27354_test.dart
@@ -0,0 +1,14 @@
+// Copyright (c) 2016, 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 Issue 27354.
+
+int total = 1;
+void inc() => total++ < 10 ? null : throw "do not loop forever!";
+
+void main() {
+ // Problem was moving the load of 'total' inside the loop.
+ int count = null ?? total;
+ for (int i = 0; i < count; i++) inc();
+}
diff --git a/tests/compiler/dart2js_extra/assert_with_message_test.dart b/tests/compiler/dart2js_extra/assert_with_message_test.dart
index 58b7796..a5b14ee 100644
--- a/tests/compiler/dart2js_extra/assert_with_message_test.dart
+++ b/tests/compiler/dart2js_extra/assert_with_message_test.dart
@@ -5,10 +5,10 @@
import "package:expect/expect.dart";
-@AssumeDynamic() @NoInline()
+@AssumeDynamic()
+@NoInline()
confuse(x) => x;
-
testFalse(name, fault) {
try {
fault();
@@ -21,20 +21,27 @@
}
test1() {
- testFalse('constant false', () { assert(false, 'Mumble'); });
+ testFalse('constant false', () {
+ assert(false, 'Mumble');
+ });
}
test2() {
- testFalse('constant function', () { assert(() => false, 'Mumble'); });
+ testFalse('constant function', () {
+ assert(() => false, 'Mumble');
+ });
}
test3() {
- testFalse('variable false', () { assert(confuse(false), 'Mumble'); });
+ testFalse('variable false', () {
+ assert(confuse(false), 'Mumble');
+ });
}
test4() {
- testFalse('variable function',
- () { assert(confuse(() => false), 'Mumble'); });
+ testFalse('variable function', () {
+ assert(confuse(() => false), 'Mumble');
+ });
}
testTypeErrors() {
@@ -42,16 +49,22 @@
try {
fault();
} catch (e) {
- Expect.isTrue(e is TypeError,
- 'name: <<$e>> (${e.runtimeType}) is TypeError');
+ Expect.isTrue(
+ e is TypeError, 'name: <<$e>> (${e.runtimeType}) is TypeError');
return;
}
Expect.fail('Expected assert to throw');
}
- check('constant type error', () { assert(null, 'Mumble'); });
- check('variable type error', () { assert(confuse(null), 'Mumble'); });
- check('function type error', () { assert(confuse(() => null), 'Mumble'); });
+ check('constant type error', () {
+ assert(null, 'Mumble');
+ });
+ check('variable type error', () {
+ assert(confuse(null), 'Mumble');
+ });
+ check('function type error', () {
+ assert(confuse(() => null), 'Mumble');
+ });
}
testMessageEffect1() {
diff --git a/tests/compiler/dart2js_extra/async_helper.dart b/tests/compiler/dart2js_extra/async_helper.dart
index a4263b5..b7ee2fd 100644
--- a/tests/compiler/dart2js_extra/async_helper.dart
+++ b/tests/compiler/dart2js_extra/async_helper.dart
@@ -18,6 +18,7 @@
if (!success) throw 'test failed';
print('unittest-suite-success');
}
+
test(onDone);
print('unittest-suite-wait-for-done');
}
diff --git a/tests/compiler/dart2js_extra/async_stacktrace_test.dart b/tests/compiler/dart2js_extra/async_stacktrace_test.dart
index 4c8aa7f..687222f 100644
--- a/tests/compiler/dart2js_extra/async_stacktrace_test.dart
+++ b/tests/compiler/dart2js_extra/async_stacktrace_test.dart
@@ -27,9 +27,10 @@
}
test1(Tracer tracer) {
- foo() async
- * /// asyncStar: ok
- {
+ foo() async*
+
+ /// asyncStar: ok
+ {
var savedStackTrace;
try {
try {
@@ -48,16 +49,19 @@
}
tracer.trace("f");
}
- return foo()
- .toList() /// asyncStar: continued
- ;
+
+ return foo().toList()
+
+ /// asyncStar: continued
+ ;
}
test2(Tracer tracer) {
var savedStackTrace;
- foo() async
- * /// asyncStar: continued
- {
+ foo() async*
+
+ /// asyncStar: continued
+ {
try {
tracer.trace("a");
throw "Error";
@@ -69,8 +73,10 @@
await new Future.error("Error 2", savedStackTrace);
tracer.trace("d");
}
- return foo()
- .toList() /// asyncStar: continued
+
+ return foo().toList()
+
+ /// asyncStar: continued
.catchError((e, st) {
tracer.trace("e");
Expect.equals(savedStackTrace.toString(), st.toString());
@@ -79,9 +85,10 @@
test3(Tracer tracer) {
var savedStackTrace;
- foo() async
- * /// asyncStar: continued
- {
+ foo() async*
+
+ /// asyncStar: continued
+ {
try {
tracer.trace("a");
throw "Error";
@@ -91,8 +98,10 @@
rethrow;
}
}
- return foo()
- .toList() /// asyncStar: continued
+
+ return foo().toList()
+
+ /// asyncStar: continued
.catchError((e, st) {
tracer.trace("c");
Expect.equals(savedStackTrace.toString(), st.toString());
@@ -113,4 +122,4 @@
main() {
asyncTest(runTests);
-}
\ No newline at end of file
+}
diff --git a/tests/compiler/dart2js_extra/bailout_aborting_if_test.dart b/tests/compiler/dart2js_extra/bailout_aborting_if_test.dart
index 9020f26..fe67525 100644
--- a/tests/compiler/dart2js_extra/bailout_aborting_if_test.dart
+++ b/tests/compiler/dart2js_extra/bailout_aborting_if_test.dart
@@ -4,7 +4,7 @@
import "package:expect/expect.dart";
-bar() => {'bar' : 21};
+bar() => {'bar': 21};
foo() => 'bar';
main() {
diff --git a/tests/compiler/dart2js_extra/bailout_on_break_test.dart b/tests/compiler/dart2js_extra/bailout_on_break_test.dart
index ff09790..c545d95 100644
--- a/tests/compiler/dart2js_extra/bailout_on_break_test.dart
+++ b/tests/compiler/dart2js_extra/bailout_on_break_test.dart
@@ -5,7 +5,7 @@
import "package:expect/expect.dart";
class A {
- operator+(arg) => 42;
+ operator +(arg) => 42;
}
get42() => 42;
@@ -42,7 +42,8 @@
void testInNestedWhileLoop2() {
var c = get42();
- L0: while (true) {
+ L0:
+ while (true) {
while (true) {
var e = getNonInt();
Expect.equals(42, e + 2);
@@ -99,7 +100,8 @@
void testLabeledIf() {
var c = get42();
- L1: if (c == 42) {
+ L1:
+ if (c == 42) {
var e = getNonInt();
Expect.equals(42, e + 2);
if (e == null) break L1;
@@ -113,7 +115,8 @@
void testLabeledIf2() {
var c = get42();
- L1: if (c == 42) {
+ L1:
+ if (c == 42) {
var e = getNonInt();
Expect.equals(42, e + 2);
if (e == null) break L1;
diff --git a/tests/compiler/dart2js_extra/bailout_on_continue_test.dart b/tests/compiler/dart2js_extra/bailout_on_continue_test.dart
index ca0377a..adfe356 100644
--- a/tests/compiler/dart2js_extra/bailout_on_continue_test.dart
+++ b/tests/compiler/dart2js_extra/bailout_on_continue_test.dart
@@ -5,7 +5,7 @@
import "package:expect/expect.dart";
class A {
- operator+(arg) => 42;
+ operator +(arg) => 42;
}
get42() => 42;
@@ -43,7 +43,8 @@
void testInNestedWhileLoop2() {
var c = get42();
int index = 0;
- L0: while (index++ != 2) {
+ L0:
+ while (index++ != 2) {
while (true) {
var e = getNonInt();
Expect.equals(42, e + 2);
diff --git a/tests/compiler/dart2js_extra/bailout_test.dart b/tests/compiler/dart2js_extra/bailout_test.dart
index 52b02a1..ab762c9 100644
--- a/tests/compiler/dart2js_extra/bailout_test.dart
+++ b/tests/compiler/dart2js_extra/bailout_test.dart
@@ -131,8 +131,10 @@
var a = 0;
var c = 0;
- if (a == 0) c = a++;
- else c = a--;
+ if (a == 0)
+ c = a++;
+ else
+ c = a--;
if (bailout == 1) {
var o = myString;
@@ -143,8 +145,10 @@
Expect.equals(1, a);
Expect.equals(0, c);
- if (a == 0) c = a++;
- else c = a--;
+ if (a == 0)
+ c = a++;
+ else
+ c = a--;
if (bailout == 2) {
var o = myString;
diff --git a/tests/compiler/dart2js_extra/bound_closure_interceptor_methods_test.dart b/tests/compiler/dart2js_extra/bound_closure_interceptor_methods_test.dart
index 3e115d3..f17b647 100644
--- a/tests/compiler/dart2js_extra/bound_closure_interceptor_methods_test.dart
+++ b/tests/compiler/dart2js_extra/bound_closure_interceptor_methods_test.dart
@@ -32,7 +32,7 @@
main() {
inscrutable = (x) => x;
- var array = ['foo', 'bar', [] , [], new A(), new A(), const [], const A()];
+ var array = ['foo', 'bar', [], [], new A(), new A(), const [], const A()];
array = inscrutable(array);
getter1 = inscrutable(getter1);
diff --git a/tests/compiler/dart2js_extra/bound_closure_interceptor_type_test.dart b/tests/compiler/dart2js_extra/bound_closure_interceptor_type_test.dart
index fa1b7a1..7d4ea10 100644
--- a/tests/compiler/dart2js_extra/bound_closure_interceptor_type_test.dart
+++ b/tests/compiler/dart2js_extra/bound_closure_interceptor_type_test.dart
@@ -14,7 +14,7 @@
class A<T> {
const A();
- void add(T x) { }
+ void add(T x) {}
T elementAt(int index) => index == 0 ? 42 : 'string';
// This call get:elementAt has a known receiver type, so is is potentially
@@ -29,7 +29,7 @@
var getAddOfA = (a) => a.getAdd();
var getElementAtOfA = (a) => a.getElementAt();
-var getAdd1 = (a) => a.add; // receiver has unknown type here.
+var getAdd1 = (a) => a.add; // receiver has unknown type here.
var getAdd2 = (a) {
// Call needs to be indirect to avoid inlining.
@@ -37,7 +37,7 @@
return a.add;
};
-var getElementAt1 = (a) => a.elementAt; // receiver has unknown type here.
+var getElementAt1 = (a) => a.elementAt; // receiver has unknown type here.
var getElementAt2 = (a) {
// Call needs to be indirect to avoid inlining.
@@ -45,7 +45,6 @@
return a.elementAt;
};
-
typedef void IntToVoid(int x);
typedef void StringToVoid(String x);
@@ -71,7 +70,6 @@
'getElementAt2': (x) => getElementAt2(x),
};
-
main() {
inscrutable = (x) => x;
@@ -95,9 +93,7 @@
var description = '$object';
checkers.forEach((checkName, checkFn) {
bool answer = trueCheckNames.contains(checkName);
- Expect.equals(
- answer,
- checkFn(methodFn(object)),
+ Expect.equals(answer, checkFn(methodFn(object)),
'$methodName($description) is $checkName');
});
}
@@ -116,8 +112,13 @@
check(m, objectsLst, []);
m = ['getElementAt1', 'getElementAt2'];
- check(m, objectsDyn, ['IntToInt', 'IntToString', 'IntToVoid', 'IntToT<int>',
- 'IntToT<String>']);
+ check(m, objectsDyn, [
+ 'IntToInt',
+ 'IntToString',
+ 'IntToVoid',
+ 'IntToT<int>',
+ 'IntToT<String>'
+ ]);
check(m, objectsInt, ['IntToInt', 'IntToVoid', 'IntToT<int>']);
check(m, objectsStr, ['IntToString', 'IntToVoid', 'IntToT<String>']);
check(m, objectsLst, ['IntToVoid']);
diff --git a/tests/compiler/dart2js_extra/break_test.dart b/tests/compiler/dart2js_extra/break_test.dart
index 96b0481..830fe73 100644
--- a/tests/compiler/dart2js_extra/break_test.dart
+++ b/tests/compiler/dart2js_extra/break_test.dart
@@ -7,7 +7,8 @@
break1(int x, int y, int ew, int ez) {
int w = 1;
int z = 0;
- bk1: if (x == 2) {
+ bk1:
+ if (x == 2) {
z = 1;
if (y == 3) {
w = 2;
@@ -32,7 +33,8 @@
break2(int x, int y, int ew, int ez) {
int w = 1;
int z = 0;
- bk1: do {
+ bk1:
+ do {
if (x == 2) {
z = 1;
if (y == 3) {
@@ -85,13 +87,17 @@
obscureBreaks(x) {
bool result = true;
- bar: do {
+ bar:
+ do {
if (x == 1) {
- foo: break;
+ foo:
+ break;
} else if (x == 2) {
- foo: break bar;
+ foo:
+ break bar;
} else if (x == 3) {
- bar: break;
+ bar:
+ break;
} else if (x == 4) {
break bar;
} else {
@@ -103,25 +109,31 @@
ifBreaks(x, y) {
int res = 2;
- foo: if (x == 1) bar: {
- if (y == 2) {
- res = 4;
- break foo;
- } else if (y == 3) {
- res = 5;
- break bar;
- }
- res = 3;
- } else baz: {
- if (y == 2) {
- res = 7;
- break foo;
- } else if (y == 3) {
- res = 8;
- break baz;
- }
- res = 6;
- }
+ foo:
+ if (x == 1)
+ bar:
+ {
+ if (y == 2) {
+ res = 4;
+ break foo;
+ } else if (y == 3) {
+ res = 5;
+ break bar;
+ }
+ res = 3;
+ }
+ else
+ baz:
+ {
+ if (y == 2) {
+ res = 7;
+ break foo;
+ } else if (y == 3) {
+ res = 8;
+ break baz;
+ }
+ res = 6;
+ }
return res;
}
diff --git a/tests/compiler/dart2js_extra/checked_accessor_test.dart b/tests/compiler/dart2js_extra/checked_accessor_test.dart
index 38e4b38..b67f17a 100644
--- a/tests/compiler/dart2js_extra/checked_accessor_test.dart
+++ b/tests/compiler/dart2js_extra/checked_accessor_test.dart
@@ -16,6 +16,7 @@
f(x) {
x.field = true;
}
+
Expect.throws(() {
[new E(), new WithGetter()].forEach(f);
new missingType();
diff --git a/tests/compiler/dart2js_extra/closure7_test.dart b/tests/compiler/dart2js_extra/closure7_test.dart
index f7b966d..bae471e 100644
--- a/tests/compiler/dart2js_extra/closure7_test.dart
+++ b/tests/compiler/dart2js_extra/closure7_test.dart
@@ -57,4 +57,4 @@
main() {
globalTest();
staticTest();
-}
\ No newline at end of file
+}
diff --git a/tests/compiler/dart2js_extra/closure_capture2_test.dart b/tests/compiler/dart2js_extra/closure_capture2_test.dart
index b49bf98..4d22b10 100644
--- a/tests/compiler/dart2js_extra/closure_capture2_test.dart
+++ b/tests/compiler/dart2js_extra/closure_capture2_test.dart
@@ -11,12 +11,16 @@
var g;
{
var x = 499;
- f = () { return x; };
+ f = () {
+ return x;
+ };
x++;
}
{
var x = 42;
- g = () { return x; };
+ g = () {
+ return x;
+ };
x++;
}
Expect.equals(500, f());
@@ -27,7 +31,9 @@
// f captures variable $0 which once could yield to troubles with HForeign if
// we did not mangle correctly.
var $1 = 499;
- var f = () { return $1; };
+ var f = () {
+ return $1;
+ };
$1++;
Expect.equals(500, f());
}
diff --git a/tests/compiler/dart2js_extra/closure_capture3_test.dart b/tests/compiler/dart2js_extra/closure_capture3_test.dart
index 5a54b13..f74f7f5 100644
--- a/tests/compiler/dart2js_extra/closure_capture3_test.dart
+++ b/tests/compiler/dart2js_extra/closure_capture3_test.dart
@@ -25,8 +25,12 @@
}
nestedClosure() {
- var f = () { return x; };
- return () { return f() + 2; };
+ var f = () {
+ return x;
+ };
+ return () {
+ return f() + 2;
+ };
}
}
diff --git a/tests/compiler/dart2js_extra/closure_capture4_test.dart b/tests/compiler/dart2js_extra/closure_capture4_test.dart
index aa52d74..5112a5d 100644
--- a/tests/compiler/dart2js_extra/closure_capture4_test.dart
+++ b/tests/compiler/dart2js_extra/closure_capture4_test.dart
@@ -8,7 +8,9 @@
var input = [1, 2, 3];
var fs = [];
for (var x in input) {
- fs.add(() { return x; });
+ fs.add(() {
+ return x;
+ });
}
Expect.equals(3, fs.length);
Expect.equals(1, fs[0]());
@@ -20,7 +22,9 @@
var input = [1, 2, 3];
var fs = [];
for (var x in input) {
- fs.add(() { return x; });
+ fs.add(() {
+ return x;
+ });
x++;
}
Expect.equals(3, fs.length);
@@ -34,7 +38,9 @@
var fs = [];
for (var i = 0; i < input.length; i++) {
var j = i;
- fs.add(() { return input[j]; });
+ fs.add(() {
+ return input[j];
+ });
}
Expect.equals(3, fs.length);
Expect.equals(1, fs[0]());
@@ -47,7 +53,9 @@
var fs = [];
for (var i = 0; i < input.length; i++) {
var x = input[i];
- fs.add(() { return x; });
+ fs.add(() {
+ return x;
+ });
x++;
}
Expect.equals(3, fs.length);
@@ -62,7 +70,9 @@
var x;
for (var i = 0; i < input.length; i++) {
x = input[i];
- fs.add(() { return x; });
+ fs.add(() {
+ return x;
+ });
x++;
}
Expect.equals(3, fs.length);
@@ -77,7 +87,9 @@
var i = 0;
do {
var x = input[i];
- fs.add(() { return x; });
+ fs.add(() {
+ return x;
+ });
} while (++i < input.length);
Expect.equals(3, fs.length);
Expect.equals(1, fs[0]());
diff --git a/tests/compiler/dart2js_extra/closure_capture5_test.dart b/tests/compiler/dart2js_extra/closure_capture5_test.dart
index 37df6df..c95bbc6 100644
--- a/tests/compiler/dart2js_extra/closure_capture5_test.dart
+++ b/tests/compiler/dart2js_extra/closure_capture5_test.dart
@@ -7,7 +7,9 @@
closure0() {
var fs = [];
for (var x = 1; x <= 3; x++) {
- fs.add(() { return x; });
+ fs.add(() {
+ return x;
+ });
}
Expect.equals(3, fs.length);
Expect.equals(1, fs[0]());
@@ -18,7 +20,9 @@
closure1() {
var fs = [];
for (var x = 0; x < 6; x++) {
- fs.add(() { return x; });
+ fs.add(() {
+ return x;
+ });
x++;
}
Expect.equals(3, fs.length);
@@ -31,7 +35,9 @@
var input = [1, 2, 3];
var fs = [];
for (var i = 0; i < input.length; i++) {
- fs.add(() { return input[i]; });
+ fs.add(() {
+ return input[i];
+ });
}
Expect.equals(3, fs.length);
Expect.equals(1, fs[0]());
@@ -42,11 +48,11 @@
closure3() {
var fs = [];
for (var i = 0;
- i < 3;
- (() {
- fs.add(() => i);
- i++;
- })()) {
+ i < 3;
+ (() {
+ fs.add(() => i);
+ i++;
+ })()) {
i++;
}
Expect.equals(2, fs.length);
@@ -57,11 +63,11 @@
closure4() {
var g;
for (var i = 0;
- (() {
- g = () => i;
- return false;
- })();
- i++){
+ (() {
+ g = () => i;
+ return false;
+ })();
+ i++) {
Expect.equals(false, true);
}
Expect.equals(0, g());
diff --git a/tests/compiler/dart2js_extra/closure_capture_test.dart b/tests/compiler/dart2js_extra/closure_capture_test.dart
index c55317b..cc12c58 100644
--- a/tests/compiler/dart2js_extra/closure_capture_test.dart
+++ b/tests/compiler/dart2js_extra/closure_capture_test.dart
@@ -6,14 +6,18 @@
closure0() {
var x = 499;
- var f = () { return x; };
+ var f = () {
+ return x;
+ };
Expect.equals(499, f());
}
class A {
closure1() {
var x = 499;
- var f = () { return x; };
+ var f = () {
+ return x;
+ };
Expect.equals(499, f());
}
}
@@ -24,12 +28,16 @@
closure2() {
var x = 499;
- Expect.equals(499, applyFun(() { return x; }));
+ Expect.equals(499, applyFun(() {
+ return x;
+ }));
}
closure3() {
var y = 400;
- var f = (x) { return y + x; };
+ var f = (x) {
+ return y + x;
+ };
Expect.equals(499, f(99));
}
@@ -39,12 +47,16 @@
closure4() {
var z = 9;
- Expect.equals(499, applyFun2((x, y) { return x + y + z; }));
+ Expect.equals(499, applyFun2((x, y) {
+ return x + y + z;
+ }));
}
closure5() {
var x = 498;
- var f = () { return x; };
+ var f = () {
+ return x;
+ };
x++;
Expect.equals(499, f());
}
@@ -52,7 +64,9 @@
class A2 {
closure6() {
var x = 498;
- var f = () { return x; };
+ var f = () {
+ return x;
+ };
x++;
Expect.equals(499, f());
}
@@ -60,21 +74,27 @@
closure7() {
var x = 498;
- var f = () { return x; };
+ var f = () {
+ return x;
+ };
x++;
Expect.equals(499, applyFun(f));
}
closure8() {
var y = 399;
- var f = (x) { return y + x; };
+ var f = (x) {
+ return y + x;
+ };
y++;
Expect.equals(499, f(99));
}
closure9() {
var z = 9;
- Expect.equals(499, applyFun2((x, y) { return x + y + z; }));
+ Expect.equals(499, applyFun2((x, y) {
+ return x + y + z;
+ }));
}
main() {
diff --git a/tests/compiler/dart2js_extra/closure_test.dart b/tests/compiler/dart2js_extra/closure_test.dart
index b0bdeec..5ad4247 100644
--- a/tests/compiler/dart2js_extra/closure_test.dart
+++ b/tests/compiler/dart2js_extra/closure_test.dart
@@ -5,13 +5,17 @@
import "package:expect/expect.dart";
closure0() {
- var f = () { return 499; };
+ var f = () {
+ return 499;
+ };
Expect.equals(499, f());
}
class A {
closure1() {
- var f = () { return 499; };
+ var f = () {
+ return 499;
+ };
Expect.equals(499, f());
}
}
@@ -21,11 +25,15 @@
}
closure2() {
- Expect.equals(499, applyFun(() { return 499; }));
+ Expect.equals(499, applyFun(() {
+ return 499;
+ }));
}
closure3() {
- var f = (x) { return 400 + x; };
+ var f = (x) {
+ return 400 + x;
+ };
Expect.equals(499, f(99));
}
@@ -34,7 +42,9 @@
}
closure4() {
- Expect.equals(499, applyFun2((x, y) { return x + y; }));
+ Expect.equals(499, applyFun2((x, y) {
+ return x + y;
+ }));
}
main() {
diff --git a/tests/compiler/dart2js_extra/closure_type_reflection2_test.dart b/tests/compiler/dart2js_extra/closure_type_reflection2_test.dart
index ef97222..398dab5 100644
--- a/tests/compiler/dart2js_extra/closure_type_reflection2_test.dart
+++ b/tests/compiler/dart2js_extra/closure_type_reflection2_test.dart
@@ -17,6 +17,6 @@
}
main() {
- Expect.isFalse(reflect(new C().foo).function.returnType.toString()
- .contains('dynamic'));
+ Expect.isFalse(
+ reflect(new C().foo).function.returnType.toString().contains('dynamic'));
}
diff --git a/tests/compiler/dart2js_extra/closure_type_reflection_test.dart b/tests/compiler/dart2js_extra/closure_type_reflection_test.dart
index e289f4d..8acb4c0 100644
--- a/tests/compiler/dart2js_extra/closure_type_reflection_test.dart
+++ b/tests/compiler/dart2js_extra/closure_type_reflection_test.dart
@@ -18,5 +18,5 @@
main() {
Expect.equals("ClassMirror on 'A'",
- reflect(new C().foo).function.returnType.toString());
+ reflect(new C().foo).function.returnType.toString());
}
diff --git a/tests/compiler/dart2js_extra/code_motion_exception_test.dart b/tests/compiler/dart2js_extra/code_motion_exception_test.dart
index 529f3a7..95ed395 100644
--- a/tests/compiler/dart2js_extra/code_motion_exception_test.dart
+++ b/tests/compiler/dart2js_extra/code_motion_exception_test.dart
@@ -12,8 +12,8 @@
// gA and gB have type [null|num], so they compile to a receiver check, and
// argument check and then the operation.
-var gA; // [null|num]
-var gB; // [null|num]
+var gA; // [null|num]
+var gB; // [null|num]
foo1(a, b) {
// The checks on a and b are not equivalent, so can't be merged.
@@ -24,7 +24,9 @@
}
}
-call1() { return foo1(gA, gB); }
+call1() {
+ return foo1(gA, gB);
+}
test1() {
gA = 1;
@@ -41,10 +43,9 @@
gA = null;
gB = 2;
- Expect.throws(call1, (e) => e is ArgumentError, 'foo1($gA, $gB) AE');
+ Expect.throws(call1, (e) => e is ArgumentError, 'foo1($gA, $gB) AE');
}
-
foo2a(a, b) {
// The common receiver check on [a] cannot be merged because the operation
// (selector) is different.
@@ -66,14 +67,19 @@
}
}
-call2a() { return foo2a(gA, gB); }
-call2b() { return foo2b(gA, gB); }
+call2a() {
+ return foo2a(gA, gB);
+}
+
+call2b() {
+ return foo2b(gA, gB);
+}
checkNSME(text) {
return (e) {
Expect.isTrue(e is NoSuchMethodError,
'expecting NoSuchMethodError, got "${e.runtimeType}"');
- Expect.isTrue('$e'.contains(text), '"$e".contains("$text")');
+ Expect.isTrue('$e'.contains(text), '"$e".contains("$text")');
return e is NoSuchMethodError;
};
}
@@ -96,8 +102,8 @@
gA = null;
gB = 2;
- Expect.throws(call2a, checkNSME(r'$and'), 'foo2($gA, $gB) NSME');
- Expect.throws(call2b, checkNSME(r'$xor'), 'foo2($gA, $gB) NSME');
+ Expect.throws(call2a, checkNSME(r'$and'), 'foo2($gA, $gB) NSME');
+ Expect.throws(call2b, checkNSME(r'$xor'), 'foo2($gA, $gB) NSME');
}
main() {
diff --git a/tests/compiler/dart2js_extra/compound_operator_index_test.dart b/tests/compiler/dart2js_extra/compound_operator_index_test.dart
index 67d30d0..508a9e0 100644
--- a/tests/compiler/dart2js_extra/compound_operator_index_test.dart
+++ b/tests/compiler/dart2js_extra/compound_operator_index_test.dart
@@ -43,6 +43,7 @@
trace.add(-1);
return new B(trace);
}
+
int getIndex(trace) {
trace.add(-2);
return 42;
diff --git a/tests/compiler/dart2js_extra/conditional_send_test.dart b/tests/compiler/dart2js_extra/conditional_send_test.dart
index c95203d..b064f2e 100644
--- a/tests/compiler/dart2js_extra/conditional_send_test.dart
+++ b/tests/compiler/dart2js_extra/conditional_send_test.dart
@@ -5,7 +5,8 @@
// SharedOptions=--enable-null-aware-operators
import "package:expect/expect.dart";
-@NoInline() @AssumeDynamic()
+@NoInline()
+@AssumeDynamic()
confuse(x) => x;
class A {
diff --git a/tests/compiler/dart2js_extra/conditional_test.dart b/tests/compiler/dart2js_extra/conditional_test.dart
index c1e30b9..13cf988 100644
--- a/tests/compiler/dart2js_extra/conditional_test.dart
+++ b/tests/compiler/dart2js_extra/conditional_test.dart
@@ -4,7 +4,9 @@
import "package:expect/expect.dart";
-getZero() { return 0; }
+getZero() {
+ return 0;
+}
main() {
int i = getZero();
diff --git a/tests/compiler/dart2js_extra/consistent_add_error_test.dart b/tests/compiler/dart2js_extra/consistent_add_error_test.dart
index 22927e2..0796085 100644
--- a/tests/compiler/dart2js_extra/consistent_add_error_test.dart
+++ b/tests/compiler/dart2js_extra/consistent_add_error_test.dart
@@ -19,6 +19,7 @@
}
Expect.fail('should throw: $name.$part');
}
+
var e1 = trap(name1, f1);
var e2 = trap(name2, f2);
var s1 = '$e1';
@@ -53,12 +54,12 @@
}
static f5() {
- var a = confuse(true) ? 1 : 2; // Small int with unknown value.
+ var a = confuse(true) ? 1 : 2; // Small int with unknown value.
return a + confuse(null);
}
static f6() {
- var a = confuse(true) ? 1 : 2; // Small int with unknown value.
+ var a = confuse(true) ? 1 : 2; // Small int with unknown value.
return a + null;
}
@@ -117,7 +118,7 @@
}
static f3() {
- var a = confuse(true) ? 1 : 2; // Small int with unknown value.
+ var a = confuse(true) ? 1 : 2; // Small int with unknown value.
return a + confuse('a');
}
@@ -130,7 +131,7 @@
}
static f6() {
- var a = confuse(true) ? 1 : 2; // Small int with unknown value.
+ var a = confuse(true) ? 1 : 2; // Small int with unknown value.
return a + 'a';
}
diff --git a/tests/compiler/dart2js_extra/consistent_codeUnitAt_error_test.dart b/tests/compiler/dart2js_extra/consistent_codeUnitAt_error_test.dart
index 8d3929f..0787ab3 100644
--- a/tests/compiler/dart2js_extra/consistent_codeUnitAt_error_test.dart
+++ b/tests/compiler/dart2js_extra/consistent_codeUnitAt_error_test.dart
@@ -20,6 +20,7 @@
}
Expect.fail('should throw: $name.$part');
}
+
var e1 = trap(name1, f1);
var e2 = trap(name2, f2);
var s1 = '$e1';
@@ -33,20 +34,19 @@
if (f4 != null) check2(name, 'f1', f1, 'f4', f4);
}
-
class TooHigh {
static f1() {
- return confuse('AB').codeUnitAt(3); // dynamic receiver.
+ return confuse('AB').codeUnitAt(3); // dynamic receiver.
}
static f2() {
- var a = confuse(true) ? 'AB' : 'ABCDE'; // String with unknown length.
+ var a = confuse(true) ? 'AB' : 'ABCDE'; // String with unknown length.
var i = confuse(3);
return a.codeUnitAt(i);
}
static f3() {
- var a = confuse(true) ? 'AB' : 'ABCDE'; // String with unknown length.
+ var a = confuse(true) ? 'AB' : 'ABCDE'; // String with unknown length.
return a.codeUnitAt(3);
}
@@ -57,23 +57,23 @@
class Negative {
static f1() {
- return confuse('AB').codeUnitAt(-3); // dynamic receiver.
+ return confuse('AB').codeUnitAt(-3); // dynamic receiver.
}
static f2() {
- var a = confuse(true) ? 'AB' : 'ABCDE'; // String with unknown length.
+ var a = confuse(true) ? 'AB' : 'ABCDE'; // String with unknown length.
var i = confuse(-3);
return a.codeUnitAt(i);
}
static f3() {
- var a = confuse(true) ? 'AB' : 'ABCDE'; // String with unknown length.
+ var a = confuse(true) ? 'AB' : 'ABCDE'; // String with unknown length.
var i = confuse(true) ? -3 : 0;
return a.codeUnitAt(i);
}
static f4() {
- var a = confuse(true) ? 'AB' : 'ABCDE'; // String with unknown length.
+ var a = confuse(true) ? 'AB' : 'ABCDE'; // String with unknown length.
return a.codeUnitAt(-3);
}
@@ -84,17 +84,17 @@
class Empty {
static f1() {
- return confuse('').codeUnitAt(0); // dynamic receiver.
+ return confuse('').codeUnitAt(0); // dynamic receiver.
}
static f2() {
- var a = confuse(true) ? '' : 'ABCDE'; // Empty String with unknown length.
+ var a = confuse(true) ? '' : 'ABCDE'; // Empty String with unknown length.
var i = confuse(true) ? 0 : 1;
return a.codeUnitAt(i);
}
static f3() {
- var a = confuse(true) ? '' : 'ABCDE'; // Empty String with unknown length.
+ var a = confuse(true) ? '' : 'ABCDE'; // Empty String with unknown length.
return a.codeUnitAt(0);
}
@@ -105,17 +105,17 @@
class BadType {
static f1() {
- return confuse('AB').codeUnitAt('a'); // dynamic receiver.
+ return confuse('AB').codeUnitAt('a'); // dynamic receiver.
}
static f2() {
- var a = confuse(true) ? 'AB' : 'ABCDE'; // String with unknown length.
+ var a = confuse(true) ? 'AB' : 'ABCDE'; // String with unknown length.
var i = confuse('a');
return a.codeUnitAt(i);
}
static f3() {
- var a = confuse(true) ? 'AB' : 'ABCDE'; // String with unknown length.
+ var a = confuse(true) ? 'AB' : 'ABCDE'; // String with unknown length.
return a.codeUnitAt('a');
}
diff --git a/tests/compiler/dart2js_extra/consistent_index_error_array_test.dart b/tests/compiler/dart2js_extra/consistent_index_error_array_test.dart
index 90b9ac2..0a3b726 100644
--- a/tests/compiler/dart2js_extra/consistent_index_error_array_test.dart
+++ b/tests/compiler/dart2js_extra/consistent_index_error_array_test.dart
@@ -13,7 +13,7 @@
class TooHigh {
static load1() {
- var a = confuse(true) ? [10,11] : [10,11,12,13,14];
+ var a = confuse(true) ? [10, 11] : [10, 11, 12, 13, 14];
try {
// dynamic receiver causes method to be called via interceptor.
return confuse(a)[3];
@@ -31,8 +31,9 @@
}
Expect.fail('unreached');
}
+
static load2x(i) {
- var a = confuse(true) ? [10,11] : [10,11,12,13,14];
+ var a = confuse(true) ? [10, 11] : [10, 11, 12, 13, 14];
// 'a' is inferred as JSArray of unknown length so has optimized check.
return a[i];
}
@@ -46,7 +47,7 @@
class Negative {
static load1() {
- var a = confuse(true) ? [10,11] : [10,11,12,13,14];
+ var a = confuse(true) ? [10, 11] : [10, 11, 12, 13, 14];
try {
// dynamic receiver causes method to be called via interceptor.
return confuse(a)[-3];
@@ -64,8 +65,9 @@
}
Expect.fail('unreached');
}
+
static load2x(i) {
- var a = confuse(true) ? [10,11] : [10,11,12,13,14];
+ var a = confuse(true) ? [10, 11] : [10, 11, 12, 13, 14];
// 'a' is inferred as JSArray of unknown length so has optimized check.
return a[i];
}
@@ -79,7 +81,7 @@
class Empty {
static load1() {
- var a = confuse(true) ? [] : [10,11,12,13,14];
+ var a = confuse(true) ? [] : [10, 11, 12, 13, 14];
try {
// dynamic receiver causes method to be called via interceptor.
return confuse(a)[-3];
@@ -97,8 +99,9 @@
}
Expect.fail('unreached');
}
+
static load2x(i) {
- var a = confuse(true) ? [] : [10,11,12,13,14];
+ var a = confuse(true) ? [] : [10, 11, 12, 13, 14];
// 'a' is inferred as JSArray of unknown length so has optimized check.
return a[i];
}
@@ -112,7 +115,7 @@
class BadType {
static load1() {
- var a = confuse(true) ? [10,11] : [10,11,12,13,14];
+ var a = confuse(true) ? [10, 11] : [10, 11, 12, 13, 14];
try {
// dynamic receiver causes method to be called via interceptor.
return confuse(a)['a'];
@@ -130,8 +133,9 @@
}
Expect.fail('unreached');
}
+
static load2x(i) {
- var a = confuse(true) ? [10,11] : [10,11,12,13,14];
+ var a = confuse(true) ? [10, 11] : [10, 11, 12, 13, 14];
// 'a' is inferred as JSArray of unknown length so has optimized check.
return a[i];
}
diff --git a/tests/compiler/dart2js_extra/consistent_index_error_string_test.dart b/tests/compiler/dart2js_extra/consistent_index_error_string_test.dart
index 836a13d..898933f 100644
--- a/tests/compiler/dart2js_extra/consistent_index_error_string_test.dart
+++ b/tests/compiler/dart2js_extra/consistent_index_error_string_test.dart
@@ -15,7 +15,7 @@
static load1() {
var a = confuse(true) ? 'AB' : 'ABCDE';
try {
- return confuse(a)[3]; // dynamic receiver for indexer.
+ return confuse(a)[3]; // dynamic receiver for indexer.
} catch (e) {
return e;
}
@@ -30,9 +30,10 @@
}
Expect.fail('unreached');
}
+
static load2x(i) {
var a = confuse(true) ? 'AB' : 'ABCDE';
- return a[i]; // 'a' is String of unknown length.
+ return a[i]; // 'a' is String of unknown length.
}
static test() {
@@ -47,7 +48,7 @@
static load1() {
var a = confuse(true) ? 'AB' : 'ABCDE';
try {
- return confuse(a)[-3]; // dynamic receiver for indexer.
+ return confuse(a)[-3]; // dynamic receiver for indexer.
} catch (e) {
return e;
}
@@ -62,9 +63,10 @@
}
Expect.fail('unreached');
}
+
static load2x(i) {
var a = confuse(true) ? 'AB' : 'ABCDE';
- return a[i]; // 'a' is String of unknown length.
+ return a[i]; // 'a' is String of unknown length.
}
static test() {
@@ -79,7 +81,7 @@
static load1() {
var a = confuse(true) ? '' : 'ABCDE';
try {
- return confuse(a)[-3]; // dynamic receiver for indexer.
+ return confuse(a)[-3]; // dynamic receiver for indexer.
} catch (e) {
return e;
}
@@ -94,9 +96,10 @@
}
Expect.fail('unreached');
}
+
static load2x(i) {
var a = confuse(true) ? '' : 'ABCDE';
- return a[i]; // 'a' is String of unknown length.
+ return a[i]; // 'a' is String of unknown length.
}
static test() {
@@ -111,7 +114,7 @@
static load1() {
var a = confuse(true) ? 'AB' : 'ABCDE';
try {
- return confuse(a)['a']; // dynamic receiver for indexer.
+ return confuse(a)['a']; // dynamic receiver for indexer.
} catch (e) {
return e;
}
@@ -126,9 +129,10 @@
}
Expect.fail('unreached');
}
+
static load2x(i) {
var a = confuse(true) ? 'AB' : 'ABCDE';
- return a[i]; // 'a' is String of unknown length.
+ return a[i]; // 'a' is String of unknown length.
}
static test() {
diff --git a/tests/compiler/dart2js_extra/consistent_index_error_typed_list_test.dart b/tests/compiler/dart2js_extra/consistent_index_error_typed_list_test.dart
index 1cd949d..b086cfa 100644
--- a/tests/compiler/dart2js_extra/consistent_index_error_typed_list_test.dart
+++ b/tests/compiler/dart2js_extra/consistent_index_error_typed_list_test.dart
@@ -14,10 +14,10 @@
class TooHigh {
static load1() {
var a = confuse(true)
- ? new Uint8List.fromList([10,11])
- : new Uint8List.fromList([10,11,12,13,14]);
+ ? new Uint8List.fromList([10, 11])
+ : new Uint8List.fromList([10, 11, 12, 13, 14]);
try {
- return confuse(a)[3]; // dynamic receiver for indexer.
+ return confuse(a)[3]; // dynamic receiver for indexer.
} catch (e) {
return e;
}
@@ -32,10 +32,11 @@
}
Expect.fail('unreached');
}
+
static load2x(i) {
var a = confuse(true)
- ? new Uint8List.fromList([10,11])
- : new Uint8List.fromList([10,11,12,13,14]);
+ ? new Uint8List.fromList([10, 11])
+ : new Uint8List.fromList([10, 11, 12, 13, 14]);
return a[i];
}
@@ -49,10 +50,10 @@
class Negative {
static load1() {
var a = confuse(true)
- ? new Uint8List.fromList([10,11])
- : new Uint8List.fromList([10,11,12,13,14]);
+ ? new Uint8List.fromList([10, 11])
+ : new Uint8List.fromList([10, 11, 12, 13, 14]);
try {
- return confuse(a)[-3]; // dynamic receiver for indexer.
+ return confuse(a)[-3]; // dynamic receiver for indexer.
} catch (e) {
return e;
}
@@ -67,10 +68,11 @@
}
Expect.fail('unreached');
}
+
static load2x(i) {
var a = confuse(true)
- ? new Uint8List.fromList([10,11])
- : new Uint8List.fromList([10,11,12,13,14]);
+ ? new Uint8List.fromList([10, 11])
+ : new Uint8List.fromList([10, 11, 12, 13, 14]);
return a[i];
}
@@ -85,9 +87,9 @@
static load1() {
var a = confuse(true)
? new Uint8List.fromList([])
- : new Uint8List.fromList([10,11,12,13,14]);
+ : new Uint8List.fromList([10, 11, 12, 13, 14]);
try {
- return confuse(a)[-3]; // dynamic receiver for indexer.
+ return confuse(a)[-3]; // dynamic receiver for indexer.
} catch (e) {
return e;
}
@@ -102,10 +104,11 @@
}
Expect.fail('unreached');
}
+
static load2x(i) {
var a = confuse(true)
? new Uint8List.fromList([])
- : new Uint8List.fromList([10,11,12,13,14]);
+ : new Uint8List.fromList([10, 11, 12, 13, 14]);
return a[i];
}
@@ -119,10 +122,10 @@
class BadType {
static load1() {
var a = confuse(true)
- ? new Uint8List.fromList([10,11])
- : new Uint8List.fromList([10,11,12,13,14]);
+ ? new Uint8List.fromList([10, 11])
+ : new Uint8List.fromList([10, 11, 12, 13, 14]);
try {
- return confuse(a)['a']; // dynamic receiver for indexer.
+ return confuse(a)['a']; // dynamic receiver for indexer.
} catch (e) {
return e;
}
@@ -137,10 +140,11 @@
}
Expect.fail('unreached');
}
+
static load2x(i) {
var a = confuse(true)
- ? new Uint8List.fromList([10,11])
- : new Uint8List.fromList([10,11,12,13,14]);
+ ? new Uint8List.fromList([10, 11])
+ : new Uint8List.fromList([10, 11, 12, 13, 14]);
return a[i];
}
diff --git a/tests/compiler/dart2js_extra/consistent_null_add_error_test.dart b/tests/compiler/dart2js_extra/consistent_null_add_error_test.dart
index 2c47018..5417ee0 100644
--- a/tests/compiler/dart2js_extra/consistent_null_add_error_test.dart
+++ b/tests/compiler/dart2js_extra/consistent_null_add_error_test.dart
@@ -8,7 +8,6 @@
//
// They don't, sometimes we generate null.$add, sometimes JSNull_methods.$add.
-
@NoInline()
@AssumeDynamic()
confuse(x) => x;
@@ -22,6 +21,7 @@
}
Expect.fail('should throw: $name.$part');
}
+
var e1 = trap(name1, f1);
var e2 = trap(name2, f2);
var s1 = '$e1';
@@ -37,7 +37,6 @@
if (f6 != null) check2(name, 'f1', f1, 'f6', f6);
}
-
class NullPlusInt {
static f1() {
return confuse(null) + confuse(1);
diff --git a/tests/compiler/dart2js_extra/consistent_subtract_error_test.dart b/tests/compiler/dart2js_extra/consistent_subtract_error_test.dart
index 757c37d..ed39691 100644
--- a/tests/compiler/dart2js_extra/consistent_subtract_error_test.dart
+++ b/tests/compiler/dart2js_extra/consistent_subtract_error_test.dart
@@ -19,6 +19,7 @@
}
Expect.fail('should throw: $name.$part');
}
+
var e1 = trap(name1, f1);
var e2 = trap(name2, f2);
var s1 = '$e1';
@@ -53,12 +54,12 @@
}
static f5() {
- var a = confuse(true) ? 1 : 2; // Small int with unknown value.
+ var a = confuse(true) ? 1 : 2; // Small int with unknown value.
return a - confuse(null);
}
static f6() {
- var a = confuse(true) ? 1 : 2; // Small int with unknown value.
+ var a = confuse(true) ? 1 : 2; // Small int with unknown value.
return a - null;
}
@@ -81,7 +82,7 @@
}
static f3() {
- var a = confuse(true) ? 1 : 2; // Small int with unknown value.
+ var a = confuse(true) ? 1 : 2; // Small int with unknown value.
return a - confuse('a');
}
@@ -94,7 +95,7 @@
}
static f6() {
- var a = confuse(true) ? 1 : 2; // Small int with unknown value.
+ var a = confuse(true) ? 1 : 2; // Small int with unknown value.
return a - 'a';
}
diff --git a/tests/compiler/dart2js_extra/constant_javascript_semantics2_test.dart b/tests/compiler/dart2js_extra/constant_javascript_semantics2_test.dart
index 13f0a93..6ca6693 100644
--- a/tests/compiler/dart2js_extra/constant_javascript_semantics2_test.dart
+++ b/tests/compiler/dart2js_extra/constant_javascript_semantics2_test.dart
@@ -16,12 +16,11 @@
if (inscrutable(i) == 0) {
i = 0x100000001;
}
- i = 0xFFFFFFFFF & i; // In JS semantics [:i:] will be truncated to 32 bits.
+ i = 0xFFFFFFFFF & i; // In JS semantics [:i:] will be truncated to 32 bits.
i = 0x100000001 - i;
return a[i];
}
main() {
- Expect.throws(() => foo(),
- (e) => e is RangeError);
+ Expect.throws(() => foo(), (e) => e is RangeError);
}
diff --git a/tests/compiler/dart2js_extra/constant_javascript_semantics3_test.dart b/tests/compiler/dart2js_extra/constant_javascript_semantics3_test.dart
index 4fd4128..2cdf6b0 100644
--- a/tests/compiler/dart2js_extra/constant_javascript_semantics3_test.dart
+++ b/tests/compiler/dart2js_extra/constant_javascript_semantics3_test.dart
@@ -29,11 +29,10 @@
i--;
i--;
i--;
- i -= 8007199254740992; // In JS semantics [i] would be -3, now.
+ i -= 8007199254740992; // In JS semantics [i] would be -3, now.
return a[i];
}
main() {
- Expect.throws(() => foo(),
- (e) => e is RangeError);
+ Expect.throws(() => foo(), (e) => e is RangeError);
}
diff --git a/tests/compiler/dart2js_extra/deferred/deferred_class_library.dart b/tests/compiler/dart2js_extra/deferred/deferred_class_library.dart
index 138036c..03dad35 100644
--- a/tests/compiler/dart2js_extra/deferred/deferred_class_library.dart
+++ b/tests/compiler/dart2js_extra/deferred/deferred_class_library.dart
@@ -19,6 +19,6 @@
final value;
const Constant(this.value);
- operator==(other) => other is Constant && value == other.value;
+ operator ==(other) => other is Constant && value == other.value;
get hashCode => 0;
}
diff --git a/tests/compiler/dart2js_extra/deferred/deferred_class_library2.dart b/tests/compiler/dart2js_extra/deferred/deferred_class_library2.dart
index 82359bc..fecca53 100644
--- a/tests/compiler/dart2js_extra/deferred/deferred_class_library2.dart
+++ b/tests/compiler/dart2js_extra/deferred/deferred_class_library2.dart
@@ -19,7 +19,7 @@
final value;
const Constant(this.value);
- operator==(other) => other is Constant && value == other.value;
+ operator ==(other) => other is Constant && value == other.value;
get hashCode => 0;
}
@@ -35,15 +35,15 @@
Gee([this.c = const Constant(111)]);
const Gee.n321([this.c = const Constant(321)]);
- Gee.n135({ arg: const Constant(135) }) : this.c = arg;
- const Gee.n246({ arg: const Constant(246) }) : this.c = arg;
+ Gee.n135({arg: const Constant(135)}) : this.c = arg;
+ const Gee.n246({arg: const Constant(246)}) : this.c = arg;
const Gee.n888() : this.c = const Constant(888);
const Gee.constant(this.c);
}
class Gee2 extends Gee {
Gee2() : super(const Constant(979));
- const Gee2.n321(): super.n321();
- const Gee2.n151(): super.constant(const Constant(151));
+ const Gee2.n321() : super.n321();
+ const Gee2.n151() : super.constant(const Constant(151));
const Gee2.n888() : super.n888();
}
diff --git a/tests/compiler/dart2js_extra/deferred/deferred_class_test.dart b/tests/compiler/dart2js_extra/deferred/deferred_class_test.dart
index 3d43f5d..22ab8ba 100644
--- a/tests/compiler/dart2js_extra/deferred/deferred_class_test.dart
+++ b/tests/compiler/dart2js_extra/deferred/deferred_class_test.dart
@@ -13,7 +13,9 @@
main() {
var x;
- Expect.throws(() { x = new lib.MyClass(); }, isError);
+ Expect.throws(() {
+ x = new lib.MyClass();
+ }, isError);
Expect.isNull(x);
int counter = 0;
asyncStart();
@@ -36,6 +38,8 @@
});
Expect.equals(0, counter);
Expect.isNull(x);
- Expect.throws(() { x = new lib.MyClass(); }, isError);
+ Expect.throws(() {
+ x = new lib.MyClass();
+ }, isError);
Expect.isNull(x);
}
diff --git a/tests/compiler/dart2js_extra/deferred/deferred_function_test.dart b/tests/compiler/dart2js_extra/deferred/deferred_function_test.dart
index 9bb7fd2..27d780a 100644
--- a/tests/compiler/dart2js_extra/deferred/deferred_function_test.dart
+++ b/tests/compiler/dart2js_extra/deferred/deferred_function_test.dart
@@ -17,7 +17,9 @@
}
main() {
- Expect.throws(() { lib.foo('a'); }, isError);
+ Expect.throws(() {
+ lib.foo('a');
+ }, isError);
Expect.throws(readFoo, isError);
int counter = 0;
asyncStart();
@@ -38,6 +40,8 @@
asyncEnd();
});
Expect.equals(0, counter);
- Expect.throws(() { lib.foo('a'); }, isError);
+ Expect.throws(() {
+ lib.foo('a');
+ }, isError);
Expect.throws(readFoo, isError);
}
diff --git a/tests/compiler/dart2js_extra/deferred/deferred_mirrors2_lazy.dart b/tests/compiler/dart2js_extra/deferred/deferred_mirrors2_lazy.dart
index 9ec9473..9bfdee8 100644
--- a/tests/compiler/dart2js_extra/deferred/deferred_mirrors2_lazy.dart
+++ b/tests/compiler/dart2js_extra/deferred/deferred_mirrors2_lazy.dart
@@ -6,8 +6,7 @@
import 'deferred_mirrors2_lib3.dart';
-@MirrorsUsed(metaTargets: const [Reflectable],
- override: 'lazy')
+@MirrorsUsed(metaTargets: const [Reflectable], override: 'lazy')
import 'dart:mirrors';
class Reflectable {
diff --git a/tests/compiler/dart2js_extra/deferred/deferred_mirrors2_lib2.dart b/tests/compiler/dart2js_extra/deferred/deferred_mirrors2_lib2.dart
index 1a16daf..93f32a0 100644
--- a/tests/compiler/dart2js_extra/deferred/deferred_mirrors2_lib2.dart
+++ b/tests/compiler/dart2js_extra/deferred/deferred_mirrors2_lib2.dart
@@ -3,4 +3,5 @@
// BSD-style license that can be found in the LICENSE file.
library lib2;
+
import 'deferred_mirrors2_lazy.dart' deferred as admin;
diff --git a/tests/compiler/dart2js_extra/deferred/deferred_mirrors2_lib3.dart b/tests/compiler/dart2js_extra/deferred/deferred_mirrors2_lib3.dart
index 51b695f..abbd6d0 100644
--- a/tests/compiler/dart2js_extra/deferred/deferred_mirrors2_lib3.dart
+++ b/tests/compiler/dart2js_extra/deferred/deferred_mirrors2_lib3.dart
@@ -6,9 +6,7 @@
import 'deferred_mirrors2_lib4.dart';
-@MirrorsUsed(targets: const [
- 'lib3'
-])
+@MirrorsUsed(targets: const ['lib3'])
import 'dart:mirrors';
class R {
diff --git a/tests/compiler/dart2js_extra/deferred/deferred_mirrors2_lib4.dart b/tests/compiler/dart2js_extra/deferred/deferred_mirrors2_lib4.dart
index 446b67d..2ab9a2a 100644
--- a/tests/compiler/dart2js_extra/deferred/deferred_mirrors2_lib4.dart
+++ b/tests/compiler/dart2js_extra/deferred/deferred_mirrors2_lib4.dart
@@ -5,5 +5,4 @@
import 'deferred_mirrors2_lib5.dart' show Injectable;
@Injectable()
-class A {
-}
+class A {}
diff --git a/tests/compiler/dart2js_extra/deferred/deferred_overlapping_lib1.dart b/tests/compiler/dart2js_extra/deferred/deferred_overlapping_lib1.dart
index 3f72583..7b2bac9 100644
--- a/tests/compiler/dart2js_extra/deferred/deferred_overlapping_lib1.dart
+++ b/tests/compiler/dart2js_extra/deferred/deferred_overlapping_lib1.dart
@@ -4,4 +4,4 @@
import "deferred_overlapping_lib3.dart";
-class C1 extends C3 {}
\ No newline at end of file
+class C1 extends C3 {}
diff --git a/tests/compiler/dart2js_extra/deferred/deferred_overlapping_lib2.dart b/tests/compiler/dart2js_extra/deferred/deferred_overlapping_lib2.dart
index fdd2af1..5937171 100644
--- a/tests/compiler/dart2js_extra/deferred/deferred_overlapping_lib2.dart
+++ b/tests/compiler/dart2js_extra/deferred/deferred_overlapping_lib2.dart
@@ -4,4 +4,4 @@
import "deferred_overlapping_lib3.dart";
-class C2 extends C3 {}
\ No newline at end of file
+class C2 extends C3 {}
diff --git a/tests/compiler/dart2js_extra/deferred/deferred_overlapping_lib3.dart b/tests/compiler/dart2js_extra/deferred/deferred_overlapping_lib3.dart
index 80d5c9e..7a87b7b 100644
--- a/tests/compiler/dart2js_extra/deferred/deferred_overlapping_lib3.dart
+++ b/tests/compiler/dart2js_extra/deferred/deferred_overlapping_lib3.dart
@@ -2,4 +2,4 @@
// 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.
-class C3 {}
\ No newline at end of file
+class C3 {}
diff --git a/tests/compiler/dart2js_extra/deferred/deferred_overlapping_test.dart b/tests/compiler/dart2js_extra/deferred/deferred_overlapping_test.dart
index 0e5ee2b..f626d58 100644
--- a/tests/compiler/dart2js_extra/deferred/deferred_overlapping_test.dart
+++ b/tests/compiler/dart2js_extra/deferred/deferred_overlapping_test.dart
@@ -15,4 +15,4 @@
var b = new lib2.C2();
});
});
-}
\ No newline at end of file
+}
diff --git a/tests/compiler/dart2js_extra/deferred/deferred_unused_classes_test.dart b/tests/compiler/dart2js_extra/deferred/deferred_unused_classes_test.dart
index 9db7a8c..95da996 100644
--- a/tests/compiler/dart2js_extra/deferred/deferred_unused_classes_test.dart
+++ b/tests/compiler/dart2js_extra/deferred/deferred_unused_classes_test.dart
@@ -13,5 +13,4 @@
class DerivedNotUsed extends Base {}
-main() {
-}
+main() {}
diff --git a/tests/compiler/dart2js_extra/deferred_custom_loader_test.dart b/tests/compiler/dart2js_extra/deferred_custom_loader_test.dart
index 4889aca..819635d 100644
--- a/tests/compiler/dart2js_extra/deferred_custom_loader_test.dart
+++ b/tests/compiler/dart2js_extra/deferred_custom_loader_test.dart
@@ -23,7 +23,6 @@
}
""";
-
runTest() async {
setup();
await def.loadLibrary();
diff --git a/tests/compiler/dart2js_extra/deferred_fail_and_retry_lib.dart b/tests/compiler/dart2js_extra/deferred_fail_and_retry_lib.dart
index bf021a4..48fbce6 100644
--- a/tests/compiler/dart2js_extra/deferred_fail_and_retry_lib.dart
+++ b/tests/compiler/dart2js_extra/deferred_fail_and_retry_lib.dart
@@ -4,4 +4,4 @@
foo() {
return "loaded";
-}
\ No newline at end of file
+}
diff --git a/tests/compiler/dart2js_extra/deferred_fail_and_retry_test.dart b/tests/compiler/dart2js_extra/deferred_fail_and_retry_test.dart
index 95b2771..5dc34c5 100644
--- a/tests/compiler/dart2js_extra/deferred_fail_and_retry_test.dart
+++ b/tests/compiler/dart2js_extra/deferred_fail_and_retry_test.dart
@@ -12,7 +12,8 @@
main() {
// We patch document.body.appendChild to change the script src on first
// invocation.
- js.context.callMethod("eval", ["""
+ js.context.callMethod("eval", [
+ """
if (self.document) {
oldAppendChild = document.body.appendChild;
document.body.appendChild = function(element) {
@@ -28,7 +29,8 @@
load("non_existing.js");
}
}
- """]);
+ """
+ ]);
asyncStart();
lib.loadLibrary().then((_) {
@@ -42,4 +44,4 @@
asyncEnd();
});
});
-}
\ No newline at end of file
+}
diff --git a/tests/compiler/dart2js_extra/deferred_fail_and_retry_worker_test.dart b/tests/compiler/dart2js_extra/deferred_fail_and_retry_worker_test.dart
index 0e582dd..dffa739 100644
--- a/tests/compiler/dart2js_extra/deferred_fail_and_retry_worker_test.dart
+++ b/tests/compiler/dart2js_extra/deferred_fail_and_retry_worker_test.dart
@@ -13,7 +13,8 @@
void test(SendPort sendPort) {
// Patch XMLHttpRequest to fail on first load.
- js.context.callMethod("eval", ["""
+ js.context.callMethod("eval", [
+ """
oldXMLHttpRequest = XMLHttpRequest;
XMLHttpRequest = function() {
XMLHttpRequest = oldXMLHttpRequest;
@@ -28,7 +29,8 @@
instance.open(x, "non_existing.js");
}
}
- """]);
+ """
+ ]);
lib.loadLibrary().then((_) {
sendPort.send("Library should not have loaded");
}, onError: (error) {
@@ -41,7 +43,6 @@
});
}
-
main() {
ReceivePort receivePort = new ReceivePort();
asyncStart();
diff --git a/tests/compiler/dart2js_extra/deferred_inheritance_test.dart b/tests/compiler/dart2js_extra/deferred_inheritance_test.dart
index bbc5155..ff7005c 100644
--- a/tests/compiler/dart2js_extra/deferred_inheritance_test.dart
+++ b/tests/compiler/dart2js_extra/deferred_inheritance_test.dart
@@ -18,13 +18,14 @@
/// If the check `y is A` is generated as `y.$isA` then the issue is not
/// exposed. We use `AssumeDynamic` to ensure that we generate as `y instanceof
/// A` in JS.
-@NoInline() @AssumeDynamic()
+@NoInline()
+@AssumeDynamic()
check(y) => Expect.isTrue(y is A);
main() {
check(new B());
d.loadLibrary().then((_) {
- check(new d.C());
- check(new B()); // This fails if we overwrite the inheritance chain.
+ check(new d.C());
+ check(new B()); // This fails if we overwrite the inheritance chain.
});
}
diff --git a/tests/compiler/dart2js_extra/do_test.dart b/tests/compiler/dart2js_extra/do_test.dart
index 04d8d87..2b7abc0 100644
--- a/tests/compiler/dart2js_extra/do_test.dart
+++ b/tests/compiler/dart2js_extra/do_test.dart
@@ -12,7 +12,7 @@
if (x == 10) cond = false;
result += x;
x = x + 1;
- } while(cond);
+ } while (cond);
Expect.equals(55, result);
}
@@ -46,9 +46,9 @@
if (j == 9) cond2 = false;
result = result + 1;
j = j + 1;
- } while(cond2);
+ } while (cond2);
i = i + 1;
- } while(cond1);
+ } while (cond1);
Expect.equals(100, result);
}
diff --git a/tests/compiler/dart2js_extra/empty_method_test.dart b/tests/compiler/dart2js_extra/empty_method_test.dart
index 529df2d..7bd2791 100644
--- a/tests/compiler/dart2js_extra/empty_method_test.dart
+++ b/tests/compiler/dart2js_extra/empty_method_test.dart
@@ -2,5 +2,4 @@
// 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.
-void main() {
-}
+void main() {}
diff --git a/tests/compiler/dart2js_extra/empty_negative_test.dart b/tests/compiler/dart2js_extra/empty_negative_test.dart
index e69de29..8b13789 100644
--- a/tests/compiler/dart2js_extra/empty_negative_test.dart
+++ b/tests/compiler/dart2js_extra/empty_negative_test.dart
@@ -0,0 +1 @@
+
diff --git a/tests/compiler/dart2js_extra/equals_test.dart b/tests/compiler/dart2js_extra/equals_test.dart
index 0d20466..55cbc75 100644
--- a/tests/compiler/dart2js_extra/equals_test.dart
+++ b/tests/compiler/dart2js_extra/equals_test.dart
@@ -10,7 +10,9 @@
throw "x != x with x == 3";
}
var y = x;
- if (true) { y = 10; }
+ if (true) {
+ y = 10;
+ }
if (x == y) throw "3 == 10";
if (y == true) throw "10 == true";
if (y == "str") throw "3 == 'str'";
diff --git a/tests/compiler/dart2js_extra/fields_test.dart b/tests/compiler/dart2js_extra/fields_test.dart
index 0debb28..95c2ca3 100644
--- a/tests/compiler/dart2js_extra/fields_test.dart
+++ b/tests/compiler/dart2js_extra/fields_test.dart
@@ -5,8 +5,7 @@
import "package:expect/expect.dart";
class A {
- A() {
- }
+ A() {}
int x;
foo() {
@@ -17,8 +16,7 @@
}
}
-class B extends A {
-}
+class B extends A {}
main() {
A a = new A();
diff --git a/tests/compiler/dart2js_extra/for_in_test.dart b/tests/compiler/dart2js_extra/for_in_test.dart
index eb5de79..46093d8 100644
--- a/tests/compiler/dart2js_extra/for_in_test.dart
+++ b/tests/compiler/dart2js_extra/for_in_test.dart
@@ -37,7 +37,9 @@
class MyListIterator<T> implements Iterator<T> {
final List<T> values;
int index;
- MyListIterator(List<T> values) : this.values = values, index = -1;
+ MyListIterator(List<T> values)
+ : this.values = values,
+ index = -1;
bool moveNext() => ++index < values.length;
T get current => (0 <= index && index < values.length) ? values[index] : null;
@@ -48,13 +50,17 @@
testIterator([], new MyIterable([]));
testIterator([1], [1]);
testIterator([1], new MyIterable([1]));
- testIterator([1,2,3], [1,2,3]);
- testIterator([1,2,3], new MyIterable([1,2,3]));
- testIterator(["a","b","c"], ["a","b","c"]);
- testIterator(["a","b","c"], new MyIterable(["a","b","c"]));
+ testIterator([1, 2, 3], [1, 2, 3]);
+ testIterator([1, 2, 3], new MyIterable([1, 2, 3]));
+ testIterator(["a", "b", "c"], ["a", "b", "c"]);
+ testIterator(["a", "b", "c"], new MyIterable(["a", "b", "c"]));
// Several nested for-in's.
- for (var x in [[["a"]]]) {
+ for (var x in [
+ [
+ ["a"]
+ ]
+ ]) {
for (var y in x) {
for (var z in y) {
Expect.equals("a", z);
@@ -63,7 +69,10 @@
}
// Simultaneous iteration of the same iterable.
- for (var iterable in [[1,2,3], new MyIterable([1,2,3])]) {
+ for (var iterable in [
+ [1, 2, 3],
+ new MyIterable([1, 2, 3])
+ ]) {
int result = 0;
for (var x in iterable) {
for (var y in iterable) {
@@ -76,7 +85,7 @@
// Using the same variable (showing that the expression is evaluated
// in the outer scope).
int result = 0;
- var x = [1,2,3];
+ var x = [1, 2, 3];
for (var x in x) {
result += x;
}
diff --git a/tests/compiler/dart2js_extra/for_test.dart b/tests/compiler/dart2js_extra/for_test.dart
index 068b4b4..fc910be 100644
--- a/tests/compiler/dart2js_extra/for_test.dart
+++ b/tests/compiler/dart2js_extra/for_test.dart
@@ -55,7 +55,7 @@
void for6() {
var i = 0;
var sum = 0;
- for(; i < 5; i++) {
+ for (; i < 5; i++) {
sum += i;
}
Expect.equals(5, i);
@@ -63,7 +63,7 @@
sum = 0;
i = 0;
- for(; i < 5;) {
+ for (; i < 5;) {
sum += i;
i++;
}
@@ -71,7 +71,7 @@
Expect.equals(10, sum);
sum = 0;
- for(i = 0; i < 5;) {
+ for (i = 0; i < 5;) {
sum += i;
i++;
}
diff --git a/tests/compiler/dart2js_extra/getters_setters_test.dart b/tests/compiler/dart2js_extra/getters_setters_test.dart
index 2e41649..139f366 100644
--- a/tests/compiler/dart2js_extra/getters_setters_test.dart
+++ b/tests/compiler/dart2js_extra/getters_setters_test.dart
@@ -5,7 +5,6 @@
import "package:expect/expect.dart";
class GettersSettersTest {
-
static int foo;
static get bar {
diff --git a/tests/compiler/dart2js_extra/hash_code_test.dart b/tests/compiler/dart2js_extra/hash_code_test.dart
index 3329a38..8de6313 100644
--- a/tests/compiler/dart2js_extra/hash_code_test.dart
+++ b/tests/compiler/dart2js_extra/hash_code_test.dart
@@ -42,7 +42,7 @@
bools() {
check(true, false, identityHashCode: false);
- Expect.equals(true.hashCode, hash(true)); // First can be optimized.
+ Expect.equals(true.hashCode, hash(true)); // First can be optimized.
Expect.equals(false.hashCode, hash(false));
}
diff --git a/tests/compiler/dart2js_extra/if_in_loop_test.dart b/tests/compiler/dart2js_extra/if_in_loop_test.dart
index 2eef63d..af3590d 100644
--- a/tests/compiler/dart2js_extra/if_in_loop_test.dart
+++ b/tests/compiler/dart2js_extra/if_in_loop_test.dart
@@ -23,4 +23,4 @@
Expect.equals(30, foo(false, true));
Expect.equals(30, foo(false, false));
Expect.equals(20, foo(true, false));
-}
\ No newline at end of file
+}
diff --git a/tests/compiler/dart2js_extra/if_null_test.dart b/tests/compiler/dart2js_extra/if_null_test.dart
index 5574643..2b25f43 100644
--- a/tests/compiler/dart2js_extra/if_null_test.dart
+++ b/tests/compiler/dart2js_extra/if_null_test.dart
@@ -4,7 +4,8 @@
import "package:expect/expect.dart";
-@NoInline() @AssumeDynamic()
+@NoInline()
+@AssumeDynamic()
confuse(x) => x;
main(args) {
@@ -26,8 +27,13 @@
new D();
}
-class A { m() => 'a'; }
-class B { m() => 'b'; }
+class A {
+ m() => 'a';
+}
+
+class B {
+ m() => 'b';
+}
class C {
var y;
diff --git a/tests/compiler/dart2js_extra/if_test.dart b/tests/compiler/dart2js_extra/if_test.dart
index d2c8ad8..3c1670b 100644
--- a/tests/compiler/dart2js_extra/if_test.dart
+++ b/tests/compiler/dart2js_extra/if_test.dart
@@ -39,8 +39,7 @@
int if5() {
if (true) {
if (false) return 42;
- } else {
- }
+ } else {}
return 499;
}
diff --git a/tests/compiler/dart2js_extra/inference_nsm_mirrors_test.dart b/tests/compiler/dart2js_extra/inference_nsm_mirrors_test.dart
index 46a9737..424f7ca 100644
--- a/tests/compiler/dart2js_extra/inference_nsm_mirrors_test.dart
+++ b/tests/compiler/dart2js_extra/inference_nsm_mirrors_test.dart
@@ -24,6 +24,6 @@
Expect.equals(42, new B().foo(0));
// In checked mode we should get a type error. In unchecked mode it should be
// an argument error.
- Expect.throws(() => new A().foo('foo'),
- (e) => e is ArgumentError || e is TypeError);
+ Expect.throws(
+ () => new A().foo('foo'), (e) => e is ArgumentError || e is TypeError);
}
diff --git a/tests/compiler/dart2js_extra/inferrer_is_int_test.dart b/tests/compiler/dart2js_extra/inferrer_is_int_test.dart
index 6aecf39..445986e 100644
--- a/tests/compiler/dart2js_extra/inferrer_is_int_test.dart
+++ b/tests/compiler/dart2js_extra/inferrer_is_int_test.dart
@@ -11,20 +11,20 @@
@DontInline()
callWithStringAndDouble(value) {
() => 42;
- if (value is !int) throw new ArgumentError(value);
+ if (value is! int) throw new ArgumentError(value);
return 42;
}
@DontInline()
callWithDouble(value) {
() => 42;
- if (value is !int) throw new ArgumentError(value);
+ if (value is! int) throw new ArgumentError(value);
return 42;
}
main() {
- Expect.throws(() => callWithStringAndDouble('foo'),
- (e) => e is ArgumentError);
+ Expect.throws(
+ () => callWithStringAndDouble('foo'), (e) => e is ArgumentError);
Expect.equals(42, callWithStringAndDouble(0.0));
Expect.equals(42, callWithDouble(0.0));
}
diff --git a/tests/compiler/dart2js_extra/interceptor_named_arguments_test.dart b/tests/compiler/dart2js_extra/interceptor_named_arguments_test.dart
index 6911a96..32e9282 100644
--- a/tests/compiler/dart2js_extra/interceptor_named_arguments_test.dart
+++ b/tests/compiler/dart2js_extra/interceptor_named_arguments_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.
-
// Test that the proper one-shot interceptor is used for different
// combinations of named arguments.
import "package:expect/expect.dart";
@@ -23,7 +22,6 @@
@NoInline()
bool wontTell(bool x) => x;
-
// Ensure that we use the interceptor only once per context so that we
// actually get a one-shot interceptor. This is a little brittle...
@NoInline()
@@ -46,7 +44,7 @@
Expect.equals(3, thing.createFragment(null, validator: 1, treeSanitizer: 1));
}
-main () {
+main() {
// Ensure we get interceptors into play.
var thing = wontTell(true) ? new Other() : new DivElement();
testA(thing);
diff --git a/tests/compiler/dart2js_extra/invoke_dynamic_test.dart b/tests/compiler/dart2js_extra/invoke_dynamic_test.dart
index b76c59b..65239f6 100644
--- a/tests/compiler/dart2js_extra/invoke_dynamic_test.dart
+++ b/tests/compiler/dart2js_extra/invoke_dynamic_test.dart
@@ -5,21 +5,45 @@
import "package:expect/expect.dart";
class A {
- foo() { return 499; }
- bar(x) { return x + 499; }
- baz() { return 54; }
- titi() { return 123; }
+ foo() {
+ return 499;
+ }
+
+ bar(x) {
+ return x + 499;
+ }
+
+ baz() {
+ return 54;
+ }
+
+ titi() {
+ return 123;
+ }
}
class B {
- foo() { return 42; }
- bar(x) { return x + 42; }
- toto() { return foo() + 42; }
+ foo() {
+ return 42;
+ }
+
+ bar(x) {
+ return x + 42;
+ }
+
+ toto() {
+ return foo() + 42;
+ }
}
class C extends A {
- foo() { return 99; }
- bar(x) { return x + 99; }
+ foo() {
+ return 99;
+ }
+
+ bar(x) {
+ return x + 99;
+ }
}
void main() {
diff --git a/tests/compiler/dart2js_extra/is_check_instanceof_test.dart b/tests/compiler/dart2js_extra/is_check_instanceof_test.dart
index 024d538..7e9c8a4 100644
--- a/tests/compiler/dart2js_extra/is_check_instanceof_test.dart
+++ b/tests/compiler/dart2js_extra/is_check_instanceof_test.dart
@@ -10,13 +10,19 @@
// This test verifies is-checks work with simple classes that have various
// degrees of instantiation.
-class INSTANTIATED {} // instantiated and used in many ways
-class DEFERRED {} // instantiated after first check
-class UNUSED {} // used only in is-check
-class REMOVED {} // allocated but optimized out of program
-class DEFERRED_AND_REMOVED {} // allocated after first check and removed
-class USED_AS_TYPE_PARAMETER {} // only used as a type parameter
-class USED_AS_TESTED_TYPE_PARAMETER {} // only used as a type parameter
+class INSTANTIATED {} // instantiated and used in many ways
+
+class DEFERRED {} // instantiated after first check
+
+class UNUSED {} // used only in is-check
+
+class REMOVED {} // allocated but optimized out of program
+
+class DEFERRED_AND_REMOVED {} // allocated after first check and removed
+
+class USED_AS_TYPE_PARAMETER {} // only used as a type parameter
+
+class USED_AS_TESTED_TYPE_PARAMETER {} // only used as a type parameter
class Check<T> {
bool check(x) => x is T;
@@ -34,7 +40,7 @@
var checkU1 = new Check<USED_AS_TESTED_TYPE_PARAMETER>();
var checkU2 = new Check<USED_AS_TYPE_PARAMETER>();
- var removed = new REMOVED(); // This is optimized out.
+ var removed = new REMOVED(); // This is optimized out.
// Tests that can be compiled to instanceof:
Expect.isTrue(things[0] is INSTANTIATED);
@@ -51,7 +57,7 @@
Expect.isFalse(checkU1.check(things[1]));
Expect.isFalse(checkU2.check(things[1]));
- var removed2 = new DEFERRED_AND_REMOVED(); // This is optimized out.
+ var removed2 = new DEFERRED_AND_REMOVED(); // This is optimized out.
// First allocation of DEFERRED is after the above tests.
things.setRange(0, 3, [new INSTANTIATED(), 1, new DEFERRED()]);
diff --git a/tests/compiler/dart2js_extra/is_operator_test.dart b/tests/compiler/dart2js_extra/is_operator_test.dart
index e3a88ca..bc18d7b9 100644
--- a/tests/compiler/dart2js_extra/is_operator_test.dart
+++ b/tests/compiler/dart2js_extra/is_operator_test.dart
@@ -4,11 +4,9 @@
import "package:expect/expect.dart";
-class A {
-}
+class A {}
-class B extends A {
-}
+class B extends A {}
main() {
var a = new A();
diff --git a/tests/compiler/dart2js_extra/js_array_index_error_test.dart b/tests/compiler/dart2js_extra/js_array_index_error_test.dart
index 9cfc873..798c758 100644
--- a/tests/compiler/dart2js_extra/js_array_index_error_test.dart
+++ b/tests/compiler/dart2js_extra/js_array_index_error_test.dart
@@ -5,13 +5,12 @@
// Test that optimized JSArray indexers enerate the same error as dyncamically
// dispatched calls.
-
import 'package:expect/expect.dart';
-@NoInline() @AssumeDynamic()
+@NoInline()
+@AssumeDynamic()
confuse(x) => x;
-
Error getError(action(), name, part) {
try {
action();
@@ -35,7 +34,6 @@
Expect.equals('$e1'.length + 9, '$e3'.length);
}
-
compare(name, fault1(), fault2(), fault3()) {
var e1 = getError(fault1, name, 'fault1');
var e2 = getError(fault2, name, 'fault2');
@@ -94,8 +92,8 @@
return [a[HUGE], a[1], a[2]];
}
- compare('constant index on empty list with huge index',
- fault1, fault2, fault3);
+ compare(
+ 'constant index on empty list with huge index', fault1, fault2, fault3);
}
constantIndexNonempty() {
@@ -137,8 +135,8 @@
return [a[HUGE], a[1], a[2]];
}
- compare('constant index on non-empty list with huge index',
- fault1, fault2, fault3);
+ compare('constant index on non-empty list with huge index', fault1, fault2,
+ fault3);
}
constantIndexSetEmpty() {
@@ -195,7 +193,6 @@
compare('constant index-set on non-empty list', fault1, fault2, fault3);
}
-
variableIndexEmpty(index, qualifier) {
// Single dynamic receiver indexing might go via one-shot interceptor that
// might have an accelerated path.
@@ -235,8 +232,8 @@
return [a[index], a[1], a[2]];
}
- compare('variable index on non-empty list $qualifier',
- fault1, fault2, fault3);
+ compare(
+ 'variable index on non-empty list $qualifier', fault1, fault2, fault3);
}
variableIndexSetEmpty(index, qualifier) {
@@ -265,8 +262,8 @@
return a;
}
- compare('variable index-set on empty list $qualifier',
- fault1, fault2, fault3);
+ compare(
+ 'variable index-set on empty list $qualifier', fault1, fault2, fault3);
}
variableIndexSetNonempty(index, qualifier) {
@@ -295,11 +292,10 @@
return a;
}
- compare('variable index-set on non-empty list $qualifier',
- fault1, fault2, fault3);
+ compare('variable index-set on non-empty list $qualifier', fault1, fault2,
+ fault3);
}
-
main() {
indexErrorContainsIndex();
diff --git a/tests/compiler/dart2js_extra/js_array_removeLast_error_test.dart b/tests/compiler/dart2js_extra/js_array_removeLast_error_test.dart
index 6fc14dc..f58bb15 100644
--- a/tests/compiler/dart2js_extra/js_array_removeLast_error_test.dart
+++ b/tests/compiler/dart2js_extra/js_array_removeLast_error_test.dart
@@ -7,10 +7,10 @@
import 'package:expect/expect.dart';
-@NoInline() @AssumeDynamic()
+@NoInline()
+@AssumeDynamic()
confuse(x) => x;
-
Error getError(action()) {
try {
action();
diff --git a/tests/compiler/dart2js_extra/literal_string_juxtaposition_test.dart b/tests/compiler/dart2js_extra/literal_string_juxtaposition_test.dart
index 60702c4..e30bce9 100644
--- a/tests/compiler/dart2js_extra/literal_string_juxtaposition_test.dart
+++ b/tests/compiler/dart2js_extra/literal_string_juxtaposition_test.dart
@@ -22,39 +22,40 @@
{
// Separating whitespace isn't necessary for the tokenizer.
var s1 = "abcdefgh";
- var s2 = "abcd""efgh";
- var s3 = "ab""cd""ef""gh";
- var s4 = "a""b""c""d""e""f""g""h";
- var s5 = "a"'b'r"c"r'd'"""e"""'''f'''r"""g"""r'''h''';
+ var s2 = "abcd" "efgh";
+ var s3 = "ab" "cd" "ef" "gh";
+ var s4 = "a" "b" "c" "d" "e" "f" "g" "h";
+ var s5 = "a" 'b' r"c" r'd' """e""" '''f''' r"""g""" r'''h''';
Expect.isTrue(identical(s1, s2));
Expect.isTrue(identical(s1, s3));
Expect.isTrue(identical(s1, s4));
Expect.isTrue(identical(s1, s5));
// "a""""""b""" should be tokenized as "a" """""b""", aka. "a" '""b'.
- Expect.isTrue(identical('a""b', "a""""""b"""));
+ Expect.isTrue(identical('a""b', "a" """""b"""));
// """a""""""""b""" is 'a' '""b'.
- Expect.isTrue(identical('a""b', """a""""""""b"""));
+ Expect.isTrue(identical('a""b', """a""" """""b"""));
// Raw strings.
- Expect.isTrue(identical('ab', "a"r"b"));
- Expect.isTrue(identical('ab', r"a""b"));
- Expect.isTrue(identical('ab', r"a"r"b"));
+ Expect.isTrue(identical('ab', "a" r"b"));
+ Expect.isTrue(identical('ab', r"a" "b"));
+ Expect.isTrue(identical('ab', r"a" r"b"));
}
// Newlines are just whitespace.
var ms1 = "abc"
- "def"
- "ghi"
- "jkl";
+ "def"
+ "ghi"
+ "jkl";
Expect.isTrue(identical("abcdefghijkl", ms1));
// Works with multiline strings too.
var ms2 = """abc
def"""
- """
+ """
ghi
jkl
""";
- Expect.isTrue(identical("abc\n def ghi\n jkl\n ", ms2), "Multiline: $ms2");
+ Expect.isTrue(
+ identical("abc\n def ghi\n jkl\n ", ms2), "Multiline: $ms2");
// Binds stronger than property access (it's considered one literal).
Expect.equals(5, "ab" "cde".length, "Associativity");
@@ -103,13 +104,13 @@
Expect.equals("$x-$y-$z", "${'$x' '-' '$y'}" "-" "$z");
- Expect.equals(r"-foo-42-true-",
- r"-" "$x" r"""-""" """$y""" r'-' '$z' r'''-''', "j");
- Expect.equals(r"-$x-42-true-",
- r"-" r"$x" r"""-""" """$y""" r'-' '$z' r'''-''', "k");
- Expect.equals(r"-foo-$y-true-",
- r"-" "$x" r"""-""" r"""$y""" r'-' '$z' r'''-''', "l");
- Expect.equals(r"-foo-42-$z-",
- r"-" "$x" r"""-""" """$y""" r'-' r'$z' r'''-''', "m");
+ Expect.equals(
+ r"-foo-42-true-", r"-" "$x" r"""-""" """$y""" r'-' '$z' r'''-''', "j");
+ Expect.equals(
+ r"-$x-42-true-", r"-" r"$x" r"""-""" """$y""" r'-' '$z' r'''-''', "k");
+ Expect.equals(
+ r"-foo-$y-true-", r"-" "$x" r"""-""" r"""$y""" r'-' '$z' r'''-''', "l");
+ Expect.equals(
+ r"-foo-42-$z-", r"-" "$x" r"""-""" """$y""" r'-' r'$z' r'''-''', "m");
}
}
diff --git a/tests/compiler/dart2js_extra/locate_single_element_1_test.dart b/tests/compiler/dart2js_extra/locate_single_element_1_test.dart
index 5fe6e85..4291fe0 100644
--- a/tests/compiler/dart2js_extra/locate_single_element_1_test.dart
+++ b/tests/compiler/dart2js_extra/locate_single_element_1_test.dart
@@ -7,23 +7,25 @@
import 'package:expect/expect.dart';
class T {
- foo() => 'T.foo'; // This is the single element.
+ foo() => 'T.foo'; // This is the single element.
}
class C implements T {
// There is a warning that C does not implement 'foo'.
}
-@NoInline() @AssumeDynamic()
-assumeT(x) { // returns inferred subtype(T).
+@NoInline()
+@AssumeDynamic()
+assumeT(x) {
+ // returns inferred subtype(T).
if (x is T) return x;
throw "Not T";
}
var log = [];
demo() {
- log.add(new T()); // T is created.
- var a = assumeT(new C()); // C is created.
+ log.add(new T()); // T is created.
+ var a = assumeT(new C()); // C is created.
// The call "a.foo()" should be a NoSuchMethodError, but a bug in
// locateSingleElement used to lead to T.foo being inlined. There is a single
diff --git a/tests/compiler/dart2js_extra/logical_or_test.dart b/tests/compiler/dart2js_extra/logical_or_test.dart
index c7848bc..b5923f0 100644
--- a/tests/compiler/dart2js_extra/logical_or_test.dart
+++ b/tests/compiler/dart2js_extra/logical_or_test.dart
@@ -29,8 +29,7 @@
}
void or5() {
- if (true || false) {
- } else {
+ if (true || false) {} else {
Expect.fail('unreachable');
}
}
diff --git a/tests/compiler/dart2js_extra/lookup_map/dead_entry_single_nested_pairs_test.dart b/tests/compiler/dart2js_extra/lookup_map/dead_entry_single_nested_pairs_test.dart
index 79446f2..1b9d21e 100644
--- a/tests/compiler/dart2js_extra/lookup_map/dead_entry_single_nested_pairs_test.dart
+++ b/tests/compiler/dart2js_extra/lookup_map/dead_entry_single_nested_pairs_test.dart
@@ -4,11 +4,14 @@
import 'package:lookup_map/lookup_map.dart';
import 'package:expect/expect.dart';
-class A{}
-class B{}
+
+class A {}
+
+class B {}
+
const map = const LookupMap(const [], const [
- const LookupMap.pair(A, "the-text-for-A"),
- const LookupMap.pair(B, "the-text-for-B"),
+ const LookupMap.pair(A, "the-text-for-A"),
+ const LookupMap.pair(B, "the-text-for-B"),
]);
main() {
diff --git a/tests/compiler/dart2js_extra/lookup_map/dead_entry_test.dart b/tests/compiler/dart2js_extra/lookup_map/dead_entry_test.dart
index c5fb956..3471351 100644
--- a/tests/compiler/dart2js_extra/lookup_map/dead_entry_test.dart
+++ b/tests/compiler/dart2js_extra/lookup_map/dead_entry_test.dart
@@ -4,11 +4,16 @@
import 'package:lookup_map/lookup_map.dart';
import 'package:expect/expect.dart';
-class A{}
-class B{}
+
+class A {}
+
+class B {}
+
const map = const LookupMap(const [
- A, "the-text-for-A",
- B, "the-text-for-B",
+ A,
+ "the-text-for-A",
+ B,
+ "the-text-for-B",
]);
main() {
diff --git a/tests/compiler/dart2js_extra/lookup_map/dead_entry_through_mirrors_test.dart b/tests/compiler/dart2js_extra/lookup_map/dead_entry_through_mirrors_test.dart
index 6de44b4..2c1f3a2 100644
--- a/tests/compiler/dart2js_extra/lookup_map/dead_entry_through_mirrors_test.dart
+++ b/tests/compiler/dart2js_extra/lookup_map/dead_entry_through_mirrors_test.dart
@@ -10,16 +10,20 @@
@MirrorsUsed(targets: const [A])
import 'dart:mirrors';
-class A{}
-class B{}
+class A {}
+
+class B {}
+
const map = const LookupMap(const [
- A, "the-text-for-A",
- B, "the-text-for-B",
+ A,
+ "the-text-for-A",
+ B,
+ "the-text-for-B",
]);
main() {
- LibraryMirror lib = currentMirrorSystem().findLibrary(
- #dead_entry_through_mirrors_test);
+ LibraryMirror lib =
+ currentMirrorSystem().findLibrary(#dead_entry_through_mirrors_test);
// `A` is included by @MirrorsUsed, so its entry is retained too.
ClassMirror aClass = lib.declarations[#A];
diff --git a/tests/compiler/dart2js_extra/lookup_map/discovered_code_test.dart b/tests/compiler/dart2js_extra/lookup_map/discovered_code_test.dart
index a20af73..745b7e3 100644
--- a/tests/compiler/dart2js_extra/lookup_map/discovered_code_test.dart
+++ b/tests/compiler/dart2js_extra/lookup_map/discovered_code_test.dart
@@ -5,17 +5,27 @@
import 'package:lookup_map/lookup_map.dart';
import 'package:expect/expect.dart';
-class A{ A(B x);}
-class B{}
-class C{}
-class D{}
-class E{}
+class A {
+ A(B x);
+}
+
+class B {}
+
+class C {}
+
+class D {}
+
+class E {}
+
createA() => new A(map[B][1]());
createB() => new B();
const map = const LookupMap(const [
- A, const ["the-text-for-A", createA],
- B, const ["the-text-for-B", createB],
- C, const ["the-text-for-C"],
+ A,
+ const ["the-text-for-A", createA],
+ B,
+ const ["the-text-for-B", createB],
+ C,
+ const ["the-text-for-C"],
]);
main() {
diff --git a/tests/compiler/dart2js_extra/lookup_map/entries_aside_test.dart b/tests/compiler/dart2js_extra/lookup_map/entries_aside_test.dart
index 6f72418..e8caff3 100644
--- a/tests/compiler/dart2js_extra/lookup_map/entries_aside_test.dart
+++ b/tests/compiler/dart2js_extra/lookup_map/entries_aside_test.dart
@@ -5,13 +5,17 @@
import 'package:lookup_map/lookup_map.dart';
import 'package:expect/expect.dart';
-class A{}
-class B{}
+class A {}
+
+class B {}
+
const entries = const [
- A, "the-text-for-A",
- B, "the-text-for-B",
+ A,
+ "the-text-for-A",
+ B,
+ "the-text-for-B",
];
-const map = const LookupMap(entries );
+const map = const LookupMap(entries);
main() {
Expect.equals(map[A], 'the-text-for-A');
diff --git a/tests/compiler/dart2js_extra/lookup_map/escaping_entries_test.dart b/tests/compiler/dart2js_extra/lookup_map/escaping_entries_test.dart
index 30fa3d3..704f448 100644
--- a/tests/compiler/dart2js_extra/lookup_map/escaping_entries_test.dart
+++ b/tests/compiler/dart2js_extra/lookup_map/escaping_entries_test.dart
@@ -4,11 +4,16 @@
import 'package:lookup_map/lookup_map.dart';
import 'package:expect/expect.dart';
-class A{}
-class B{}
+
+class A {}
+
+class B {}
+
const entries = const [
- A, "the-text-for-A",
- B, "the-text-for-B",
+ A,
+ "the-text-for-A",
+ B,
+ "the-text-for-B",
];
const map = const LookupMap(entries);
main() {
diff --git a/tests/compiler/dart2js_extra/lookup_map/generic_type_test.dart b/tests/compiler/dart2js_extra/lookup_map/generic_type_test.dart
index 1a2fd6e..2befb51 100644
--- a/tests/compiler/dart2js_extra/lookup_map/generic_type_test.dart
+++ b/tests/compiler/dart2js_extra/lookup_map/generic_type_test.dart
@@ -5,10 +5,15 @@
import 'package:lookup_map/lookup_map.dart';
import 'package:expect/expect.dart';
-class A{}
-class M<T>{ get type => T; }
+class A {}
+
+class M<T> {
+ get type => T;
+}
+
const map = const LookupMap(const [
- A, 'the-text-for-A',
+ A,
+ 'the-text-for-A',
]);
main() {
diff --git a/tests/compiler/dart2js_extra/lookup_map/live_entry_single_pair_test.dart b/tests/compiler/dart2js_extra/lookup_map/live_entry_single_pair_test.dart
index 2954e23..4b7110a 100644
--- a/tests/compiler/dart2js_extra/lookup_map/live_entry_single_pair_test.dart
+++ b/tests/compiler/dart2js_extra/lookup_map/live_entry_single_pair_test.dart
@@ -4,7 +4,9 @@
import 'package:lookup_map/lookup_map.dart';
import 'package:expect/expect.dart';
-class A{}
+
+class A {}
+
const map = const LookupMap.pair(A, "the-text-for-A");
main() {
Expect.equals(map[A], 'the-text-for-A');
diff --git a/tests/compiler/dart2js_extra/lookup_map/live_entry_test.dart b/tests/compiler/dart2js_extra/lookup_map/live_entry_test.dart
index aa835a8..a148147 100644
--- a/tests/compiler/dart2js_extra/lookup_map/live_entry_test.dart
+++ b/tests/compiler/dart2js_extra/lookup_map/live_entry_test.dart
@@ -4,9 +4,12 @@
import 'package:lookup_map/lookup_map.dart';
import 'package:expect/expect.dart';
-class A{}
+
+class A {}
+
const map = const LookupMap(const [
- A, "the-text-for-A",
+ A,
+ "the-text-for-A",
]);
main() {
Expect.equals(map[A], 'the-text-for-A');
diff --git a/tests/compiler/dart2js_extra/lookup_map/live_entry_through_mirrors_test.dart b/tests/compiler/dart2js_extra/lookup_map/live_entry_through_mirrors_test.dart
index 9ad99cf..7649246 100644
--- a/tests/compiler/dart2js_extra/lookup_map/live_entry_through_mirrors_test.dart
+++ b/tests/compiler/dart2js_extra/lookup_map/live_entry_through_mirrors_test.dart
@@ -8,11 +8,15 @@
import 'package:expect/expect.dart';
import 'dart:mirrors';
-class A{}
-class B{}
+class A {}
+
+class B {}
+
const map = const LookupMap(const [
- A, "the-text-for-A",
- B, "the-text-for-B",
+ A,
+ "the-text-for-A",
+ B,
+ "the-text-for-B",
]);
main() {
@@ -22,8 +26,8 @@
// `B` is used via mirrors. Because no @MirrorsUsed was found that's enough to
// retain the entry.
- LibraryMirror lib = currentMirrorSystem().findLibrary(
- #live_entry_through_mirrors_test);
+ LibraryMirror lib =
+ currentMirrorSystem().findLibrary(#live_entry_through_mirrors_test);
ClassMirror bClass = lib.declarations[#B];
Expect.equals(map[bClass.reflectedType], "the-text-for-B");
}
diff --git a/tests/compiler/dart2js_extra/lookup_map/live_entry_through_mirrors_used_test.dart b/tests/compiler/dart2js_extra/lookup_map/live_entry_through_mirrors_used_test.dart
index c5b752c..991934d 100644
--- a/tests/compiler/dart2js_extra/lookup_map/live_entry_through_mirrors_used_test.dart
+++ b/tests/compiler/dart2js_extra/lookup_map/live_entry_through_mirrors_used_test.dart
@@ -12,17 +12,21 @@
@MirrorsUsed(targets: const [A])
import 'dart:mirrors';
-class A{}
-class B{}
+class A {}
+
+class B {}
+
const map = const LookupMap(const [
- A, "the-text-for-A",
- B, "the-text-for-B",
+ A,
+ "the-text-for-A",
+ B,
+ "the-text-for-B",
]);
main() {
// `A` is included by @MirrorsUsed, so its entry is retained too.
- LibraryMirror lib = currentMirrorSystem().findLibrary(
- #live_entry_through_mirrors_used_test);
+ LibraryMirror lib =
+ currentMirrorSystem().findLibrary(#live_entry_through_mirrors_used_test);
ClassMirror aClass = lib.declarations[#A];
Expect.equals(map[aClass.reflectedType], "the-text-for-A");
}
diff --git a/tests/compiler/dart2js_extra/lookup_map/reachable_data2_test.dart b/tests/compiler/dart2js_extra/lookup_map/reachable_data2_test.dart
index 9c82430..d73c468 100644
--- a/tests/compiler/dart2js_extra/lookup_map/reachable_data2_test.dart
+++ b/tests/compiler/dart2js_extra/lookup_map/reachable_data2_test.dart
@@ -5,18 +5,27 @@
import 'package:lookup_map/lookup_map.dart';
import 'package:expect/expect.dart';
-class Key { final x; const Key(this.x); }
+class Key {
+ final x;
+ const Key(this.x);
+}
+
const A = const Key(1);
const B = const Key(2);
const C = const Key(3);
const D = const Key(4);
const E = const Key(5);
const map = const LookupMap(const [
- A, const ["the-text-for-A", B],
- B, const ["the-text-for-B", C],
- C, const ["the-text-for-C"],
- D, const ["the-text-for-D", E],
- E, const ["the-text-for-E"],
+ A,
+ const ["the-text-for-A", B],
+ B,
+ const ["the-text-for-B", C],
+ C,
+ const ["the-text-for-C"],
+ D,
+ const ["the-text-for-D", E],
+ E,
+ const ["the-text-for-E"],
]);
main() {
Expect.equals(map[map[A][1]][0], 'the-text-for-B');
diff --git a/tests/compiler/dart2js_extra/lookup_map/reachable_data_test.dart b/tests/compiler/dart2js_extra/lookup_map/reachable_data_test.dart
index 8e71ea7..edbcd97 100644
--- a/tests/compiler/dart2js_extra/lookup_map/reachable_data_test.dart
+++ b/tests/compiler/dart2js_extra/lookup_map/reachable_data_test.dart
@@ -5,17 +5,27 @@
import 'package:lookup_map/lookup_map.dart';
import 'package:expect/expect.dart';
-class A{}
-class B{}
-class C{}
-class D{}
-class E{}
+class A {}
+
+class B {}
+
+class C {}
+
+class D {}
+
+class E {}
+
const map = const LookupMap(const [
- A, const ["the-text-for-A", B],
- B, const ["the-text-for-B", C],
- C, const ["the-text-for-C"],
- D, const ["the-text-for-D", E],
- E, const ["the-text-for-E"],
+ A,
+ const ["the-text-for-A", B],
+ B,
+ const ["the-text-for-B", C],
+ C,
+ const ["the-text-for-C"],
+ D,
+ const ["the-text-for-D", E],
+ E,
+ const ["the-text-for-E"],
]);
main() {
Expect.equals(map[map[A][1]][0], 'the-text-for-B');
diff --git a/tests/compiler/dart2js_extra/lookup_map/subclass_lookup_map_test.dart b/tests/compiler/dart2js_extra/lookup_map/subclass_lookup_map_test.dart
index ebf7416..09bc4ac 100644
--- a/tests/compiler/dart2js_extra/lookup_map/subclass_lookup_map_test.dart
+++ b/tests/compiler/dart2js_extra/lookup_map/subclass_lookup_map_test.dart
@@ -4,14 +4,20 @@
import 'package:lookup_map/lookup_map.dart';
import 'package:expect/expect.dart';
-class A{}
-class B{}
+
+class A {}
+
+class B {}
+
class S extends LookupMap {
const S(list) : super(list);
}
+
const map = const S(const [
- A, "the-text-for-A",
- B, "the-text-for-B",
+ A,
+ "the-text-for-A",
+ B,
+ "the-text-for-B",
]);
main() {
diff --git a/tests/compiler/dart2js_extra/many_constants_test.dart b/tests/compiler/dart2js_extra/many_constants_test.dart
index 5027b50..3c8a663 100644
--- a/tests/compiler/dart2js_extra/many_constants_test.dart
+++ b/tests/compiler/dart2js_extra/many_constants_test.dart
@@ -37,10 +37,10 @@
const m6 = const {2: 2, 1: 1};
const m7 = const {2: 1, 1: 1};
const m8 = const {2: 2, 1: 2};
-const m9 = const <int,int>{1: 1, 2: 2};
-const mA = const <int,int>{1: 2, 2: 1};
-const mB = const <int,int>{1: 1, 2: 1};
-const mC = const <int,int>{1: 2, 2: 2};
+const m9 = const <int, int>{1: 1, 2: 2};
+const mA = const <int, int>{1: 2, 2: 1};
+const mB = const <int, int>{1: 1, 2: 1};
+const mC = const <int, int>{1: 2, 2: 2};
const mE1 = const {E.A: E.B};
const mE2 = const {E.A: E.C};
@@ -59,17 +59,49 @@
const z6 = const Z(d: 2);
makeAll() => {
- 'E.A': E.A, 'E.B': E.B, 'E.C': E.C, 'E.D': E.D,
- 'c1': c1, 'c2': c2, 'c3': c3, 'c4': c4,
- 'l1': l1, 'l2': l2, 'l3': l3, 'l4': l4,
- 'll1': ll1, 'll2': ll2, 'll3': ll3, 'l4': ll4,
- 'm1': m1, 'm2': m2, 'm3': m3, 'm4': m4,
- 'm5': m5, 'm6': m6, 'm7': m7, 'm8': m8,
- 'm9': m9, 'mA': mA, 'mB': mB, 'mC': mC,
- 'mE1': mE1, 'mE2': mE2, 'mE3': mE3, 'mE4': mE4,
- 'mE5': mE5, 'mE6': mE6, 'mE7': mE7, 'mE8': mE8,
- 'z1': z1, 'z2': z2, 'z3': z3, 'z4': z4, 'z5': z5, 'z6': z6,
-};
+ 'E.A': E.A,
+ 'E.B': E.B,
+ 'E.C': E.C,
+ 'E.D': E.D,
+ 'c1': c1,
+ 'c2': c2,
+ 'c3': c3,
+ 'c4': c4,
+ 'l1': l1,
+ 'l2': l2,
+ 'l3': l3,
+ 'l4': l4,
+ 'll1': ll1,
+ 'll2': ll2,
+ 'll3': ll3,
+ 'l4': ll4,
+ 'm1': m1,
+ 'm2': m2,
+ 'm3': m3,
+ 'm4': m4,
+ 'm5': m5,
+ 'm6': m6,
+ 'm7': m7,
+ 'm8': m8,
+ 'm9': m9,
+ 'mA': mA,
+ 'mB': mB,
+ 'mC': mC,
+ 'mE1': mE1,
+ 'mE2': mE2,
+ 'mE3': mE3,
+ 'mE4': mE4,
+ 'mE5': mE5,
+ 'mE6': mE6,
+ 'mE7': mE7,
+ 'mE8': mE8,
+ 'z1': z1,
+ 'z2': z2,
+ 'z3': z3,
+ 'z4': z4,
+ 'z5': z5,
+ 'z6': z6,
+ };
main() {
var all1 = makeAll();
@@ -80,8 +112,8 @@
for (var name2 in all2.keys) {
if (name1 == name2) continue;
var e2 = all2[name2];
- Expect.isFalse(identical(e1, e2),
- 'Different instances $name1: $e1 $name2: $e2');
+ Expect.isFalse(
+ identical(e1, e2), 'Different instances $name1: $e1 $name2: $e2');
}
}
}
diff --git a/tests/compiler/dart2js_extra/many_fields_test.dart b/tests/compiler/dart2js_extra/many_fields_test.dart
index 559238f..360ae34 100644
--- a/tests/compiler/dart2js_extra/many_fields_test.dart
+++ b/tests/compiler/dart2js_extra/many_fields_test.dart
@@ -25,7 +25,7 @@
var fieldD2 = 0x2000;
var fieldD3 = 0x4000;
var fieldD4 = 0x8000;
-
+
var fieldXA1 = 0x1;
var fieldXA2 = 0x2;
var fieldXA3 = 0x4;
@@ -45,7 +45,7 @@
var fieldXD2 = 0x20;
var fieldXD3 = 0x40;
var fieldXD4 = 0x80;
-
+
var fieldYA1 = 0x1;
var fieldYA2 = 0x200;
var fieldYA3 = 0x400;
@@ -135,8 +135,7 @@
}
// Mix in the mixin into the full implementation, shadowing some fields.
-class E extends A with C {
-}
+class E extends A with C {}
// Another mixin for block C.
class F {
@@ -162,29 +161,61 @@
}
// Use two mixins in a single class.
-class G extends B with C, F {
-}
+class G extends B with C, F {}
bool checkFields(cls) {
- var blockA =
- cls.fieldA1 ^ cls.fieldA2 ^ cls.fieldA3 ^ cls.fieldA4 ^
- cls.fieldB1 ^ cls.fieldB2 ^ cls.fieldB3 ^ cls.fieldB4 ^
- cls.fieldC1 ^ cls.fieldC2 ^ cls.fieldC3 ^ cls.fieldC4 ^
- cls.fieldD1 ^ cls.fieldD2 ^ cls.fieldD3 ^ cls.fieldD4;
- var blockB =
- cls.fieldXA1 ^ cls.fieldXA2 ^ cls.fieldXA3 ^ cls.fieldXA4 ^
- cls.fieldXB1 ^ cls.fieldXB2 ^ cls.fieldXB3 ^ cls.fieldXB4 ^
- cls.fieldXC1 ^ cls.fieldXC2 ^ cls.fieldXC3 ^ cls.fieldXC4 ^
- cls.fieldXD1 ^ cls.fieldXD2 ^ cls.fieldXD3 ^ cls.fieldXD4;
- var blockC =
- cls.fieldYA1 ^ cls.fieldYA2 ^ cls.fieldYA3 ^ cls.fieldYA4 ^
- cls.fieldYB1 ^ cls.fieldYB2 ^ cls.fieldYB3 ^ cls.fieldYB4 ^
- cls.fieldYC1 ^ cls.fieldYC2 ^ cls.fieldYC3 ^ cls.fieldYC4 ^
- cls.fieldYD1 ^ cls.fieldYD2 ^ cls.fieldYD3 ^ cls.fieldYD4;
+ var blockA = cls.fieldA1 ^
+ cls.fieldA2 ^
+ cls.fieldA3 ^
+ cls.fieldA4 ^
+ cls.fieldB1 ^
+ cls.fieldB2 ^
+ cls.fieldB3 ^
+ cls.fieldB4 ^
+ cls.fieldC1 ^
+ cls.fieldC2 ^
+ cls.fieldC3 ^
+ cls.fieldC4 ^
+ cls.fieldD1 ^
+ cls.fieldD2 ^
+ cls.fieldD3 ^
+ cls.fieldD4;
+ var blockB = cls.fieldXA1 ^
+ cls.fieldXA2 ^
+ cls.fieldXA3 ^
+ cls.fieldXA4 ^
+ cls.fieldXB1 ^
+ cls.fieldXB2 ^
+ cls.fieldXB3 ^
+ cls.fieldXB4 ^
+ cls.fieldXC1 ^
+ cls.fieldXC2 ^
+ cls.fieldXC3 ^
+ cls.fieldXC4 ^
+ cls.fieldXD1 ^
+ cls.fieldXD2 ^
+ cls.fieldXD3 ^
+ cls.fieldXD4;
+ var blockC = cls.fieldYA1 ^
+ cls.fieldYA2 ^
+ cls.fieldYA3 ^
+ cls.fieldYA4 ^
+ cls.fieldYB1 ^
+ cls.fieldYB2 ^
+ cls.fieldYB3 ^
+ cls.fieldYB4 ^
+ cls.fieldYC1 ^
+ cls.fieldYC2 ^
+ cls.fieldYC3 ^
+ cls.fieldYC4 ^
+ cls.fieldYD1 ^
+ cls.fieldYD2 ^
+ cls.fieldYD3 ^
+ cls.fieldYD4;
return blockA == 0xFFFF && blockB == 0x0000 && blockC == 0x1111;
}
-main () {
+main() {
var instances = [new A(), new D(), new E(), new G()];
for (var instance in instances) {
Expect.isTrue(checkFields(instance));
diff --git a/tests/compiler/dart2js_extra/math_lib_prefix_test.dart b/tests/compiler/dart2js_extra/math_lib_prefix_test.dart
index e8b63ef..318c0cf 100644
--- a/tests/compiler/dart2js_extra/math_lib_prefix_test.dart
+++ b/tests/compiler/dart2js_extra/math_lib_prefix_test.dart
@@ -3,6 +3,7 @@
// BSD-style license that can be found in the LICENSE file.
library math_lib_prefix_test;
+
import "package:expect/expect.dart";
import 'dart:math' as foo;
diff --git a/tests/compiler/dart2js_extra/math_lib_test.dart b/tests/compiler/dart2js_extra/math_lib_test.dart
index 14fd022..a8124d1 100644
--- a/tests/compiler/dart2js_extra/math_lib_test.dart
+++ b/tests/compiler/dart2js_extra/math_lib_test.dart
@@ -3,6 +3,7 @@
// BSD-style license that can be found in the LICENSE file.
library math_lib_test;
+
import "package:expect/expect.dart";
import 'dart:math';
diff --git a/tests/compiler/dart2js_extra/mirror_invalid_field_access2_test.dart b/tests/compiler/dart2js_extra/mirror_invalid_field_access2_test.dart
index e972bbb..0110cfb 100644
--- a/tests/compiler/dart2js_extra/mirror_invalid_field_access2_test.dart
+++ b/tests/compiler/dart2js_extra/mirror_invalid_field_access2_test.dart
@@ -26,8 +26,8 @@
var mirror = reflect(c);
Expect.equals(1, mirror.setField(const Symbol('foo'), 1).reflectee);
Expect.equals(1, mirror.getField(const Symbol('foo')).reflectee);
- Expect.throws(() => mirror.setField(const Symbol('bar'), 2),
- (e) => e is NoSuchMethodError);
+ Expect.throws(() => mirror.setField(const Symbol('bar'), 2),
+ (e) => e is NoSuchMethodError);
Expect.throws(() => mirror.getField(const Symbol('bar')),
- (e) => e is NoSuchMethodError);
+ (e) => e is NoSuchMethodError);
}
diff --git a/tests/compiler/dart2js_extra/mirror_invalid_field_access3_test.dart b/tests/compiler/dart2js_extra/mirror_invalid_field_access3_test.dart
index e100442..40d235f 100644
--- a/tests/compiler/dart2js_extra/mirror_invalid_field_access3_test.dart
+++ b/tests/compiler/dart2js_extra/mirror_invalid_field_access3_test.dart
@@ -23,8 +23,8 @@
var mirror = reflect(new C()).type; // Workaround bug 12799.
Expect.equals(1, mirror.setField(const Symbol('foo'), 1).reflectee);
Expect.equals(1, mirror.getField(const Symbol('foo')).reflectee);
- Expect.throws(() => mirror.setField(const Symbol('bar'), 2),
- (e) => e is NoSuchMethodError);
+ Expect.throws(() => mirror.setField(const Symbol('bar'), 2),
+ (e) => e is NoSuchMethodError);
Expect.throws(() => mirror.getField(const Symbol('bar')),
- (e) => e is NoSuchMethodError);
+ (e) => e is NoSuchMethodError);
}
diff --git a/tests/compiler/dart2js_extra/mirror_invalid_field_access4_test.dart b/tests/compiler/dart2js_extra/mirror_invalid_field_access4_test.dart
index 7c0f972..ba3b1904 100644
--- a/tests/compiler/dart2js_extra/mirror_invalid_field_access4_test.dart
+++ b/tests/compiler/dart2js_extra/mirror_invalid_field_access4_test.dart
@@ -33,8 +33,8 @@
var mirror = reflect(c);
Expect.equals(1, mirror.setField(const Symbol('foo'), 1).reflectee);
Expect.equals(1, mirror.getField(const Symbol('foo')).reflectee);
- Expect.throws(() => mirror.setField(const Symbol('bar'), 2),
- (e) => e is NoSuchMethodError);
+ Expect.throws(() => mirror.setField(const Symbol('bar'), 2),
+ (e) => e is NoSuchMethodError);
Expect.throws(() => mirror.getField(const Symbol('bar')),
- (e) => e is NoSuchMethodError);
+ (e) => e is NoSuchMethodError);
}
diff --git a/tests/compiler/dart2js_extra/mirror_invalid_field_access_test.dart b/tests/compiler/dart2js_extra/mirror_invalid_field_access_test.dart
index 63bffcd..15e7099 100644
--- a/tests/compiler/dart2js_extra/mirror_invalid_field_access_test.dart
+++ b/tests/compiler/dart2js_extra/mirror_invalid_field_access_test.dart
@@ -22,8 +22,8 @@
var mirror = currentMirrorSystem().findLibrary(const Symbol('test'));
Expect.equals(1, mirror.setField(const Symbol('foo'), 1).reflectee);
Expect.equals(1, mirror.getField(const Symbol('foo')).reflectee);
- Expect.throws(() => mirror.setField(const Symbol('bar'), 2),
- (e) => e is NoSuchMethodError);
+ Expect.throws(() => mirror.setField(const Symbol('bar'), 2),
+ (e) => e is NoSuchMethodError);
Expect.throws(() => mirror.getField(const Symbol('bar')),
- (e) => e is NoSuchMethodError);
+ (e) => e is NoSuchMethodError);
}
diff --git a/tests/compiler/dart2js_extra/mirror_invalid_invoke2_test.dart b/tests/compiler/dart2js_extra/mirror_invalid_invoke2_test.dart
index 49b74cf..774c7280 100644
--- a/tests/compiler/dart2js_extra/mirror_invalid_invoke2_test.dart
+++ b/tests/compiler/dart2js_extra/mirror_invalid_invoke2_test.dart
@@ -24,10 +24,10 @@
main() {
var c = new C();
- c.bar(); // Call bar, so it is included in the program.
+ c.bar(); // Call bar, so it is included in the program.
var mirror = reflect(c);
Expect.equals(1, mirror.invoke(const Symbol('foo'), []).reflectee);
- Expect.throws(() => mirror.invoke(const Symbol('bar'), []),
- (e) => e is NoSuchMethodError);
+ Expect.throws(() => mirror.invoke(const Symbol('bar'), []),
+ (e) => e is NoSuchMethodError);
}
diff --git a/tests/compiler/dart2js_extra/mirror_invalid_invoke3_test.dart b/tests/compiler/dart2js_extra/mirror_invalid_invoke3_test.dart
index 4236b3f..9ddd4e5 100644
--- a/tests/compiler/dart2js_extra/mirror_invalid_invoke3_test.dart
+++ b/tests/compiler/dart2js_extra/mirror_invalid_invoke3_test.dart
@@ -23,10 +23,10 @@
}
main() {
- C.bar(); // Call bar, so it is included in the program.
+ C.bar(); // Call bar, so it is included in the program.
var mirror = reflect(new C()).type; // Workaround bug 12799.
Expect.equals(1, mirror.invoke(const Symbol('foo'), []).reflectee);
- Expect.throws(() => mirror.invoke(const Symbol('bar'), []),
- (e) => e is NoSuchMethodError);
+ Expect.throws(() => mirror.invoke(const Symbol('bar'), []),
+ (e) => e is NoSuchMethodError);
}
diff --git a/tests/compiler/dart2js_extra/mirror_invalid_invoke_test.dart b/tests/compiler/dart2js_extra/mirror_invalid_invoke_test.dart
index 35df0e0..ea65a1e 100644
--- a/tests/compiler/dart2js_extra/mirror_invalid_invoke_test.dart
+++ b/tests/compiler/dart2js_extra/mirror_invalid_invoke_test.dart
@@ -21,9 +21,9 @@
bar() => () => 2;
main() {
- bar(); // Call bar, so it is included in the program.
+ bar(); // Call bar, so it is included in the program.
var lm = currentMirrorSystem().findLibrary(const Symbol('test'));
Expect.equals(1, lm.invoke(const Symbol('foo'), []).reflectee);
- Expect.throws(() => lm.invoke(const Symbol('bar'), []));
+ Expect.throws(() => lm.invoke(const Symbol('bar'), []));
}
diff --git a/tests/compiler/dart2js_extra/mirror_printer_test.dart b/tests/compiler/dart2js_extra/mirror_printer_test.dart
index 72e4878..bc40d4d 100644
--- a/tests/compiler/dart2js_extra/mirror_printer_test.dart
+++ b/tests/compiler/dart2js_extra/mirror_printer_test.dart
@@ -51,15 +51,16 @@
String stringifyInstance(InstanceMirror mirror) {
var reflectee = mirror.reflectee;
if (reflectee is String) return '"${reflectee}"';
- if (reflectee is Null || reflectee is bool || reflectee is num ||
- reflectee is List || reflectee is Map) {
+ if (reflectee is Null ||
+ reflectee is bool ||
+ reflectee is num ||
+ reflectee is List ||
+ reflectee is Map) {
return '$reflectee';
}
StringBuffer buffer = new StringBuffer();
Map<Symbol, DeclarationMirror> declarations = mirror.type.declarations;
- buffer
- ..write(n(mirror.type.simpleName))
- ..write('(');
+ buffer..write(n(mirror.type.simpleName))..write('(');
bool first = true;
declarations.forEach((Symbol name, DeclarationMirror declaration) {
if (declaration is! VariableMirror) return;
@@ -72,9 +73,9 @@
buffer.write(', ');
}
buffer
- ..write(n(name))
- ..write(': ')
- ..write(stringifyInstance(mirror.getField(name)));
+ ..write(n(name))
+ ..write(': ')
+ ..write(stringifyInstance(mirror.getField(name)));
});
buffer.write(')');
return buffer.toString();
@@ -168,7 +169,7 @@
writeLibrary(LibraryMirror library) {
w('library ${n(library.simpleName)};\n\n');
library.declarations.values
- .where((d)=> d is! TypeMirror)
+ .where((d) => d is! TypeMirror)
.forEach(writeDeclaration);
w('\n');
}
diff --git a/tests/compiler/dart2js_extra/mirrors_declarations_filtering_test.dart b/tests/compiler/dart2js_extra/mirrors_declarations_filtering_test.dart
index e77ec3b..08ec7a2 100644
--- a/tests/compiler/dart2js_extra/mirrors_declarations_filtering_test.dart
+++ b/tests/compiler/dart2js_extra/mirrors_declarations_filtering_test.dart
@@ -1,4 +1,3 @@
-
// Copyright (c) 2015, 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.
@@ -16,7 +15,7 @@
}
class A {
- @Meta()
+ @Meta()
reflectableThing(int a, [int b = 9, int c = 42]) => a + b + c;
nonReflectableThing(int a, [int b = 4, int c = 21]) => a + b + c;
}
@@ -27,7 +26,8 @@
Expect.equals(result, expected);
}
-@NoInline() @AssumeDynamic()
+@NoInline()
+@AssumeDynamic()
hide(x) => x;
main() {
@@ -44,7 +44,7 @@
Expect.throws(() => tryCall(a, #nonReflectableThing, [1], 1 + 4 + 21));
Expect.throws(() => tryCall(a, #nonReflectableThing, [1, 5], 1 + 5 + 21));
Expect.throws(() => tryCall(a, #nonReflectableThing, [1, 13, 7], 1 + 13 + 7));
- // Trigger generation of all declarations and check they only contain a
+ // Trigger generation of all declarations and check they only contain a
// a single entry.
var declarations = reflect(a).type.declarations;
Expect.equals(1, declarations.keys.length);
diff --git a/tests/compiler/dart2js_extra/mirrors_used_closure_test.dart b/tests/compiler/dart2js_extra/mirrors_used_closure_test.dart
index 12551cf..8f5dc8e 100644
--- a/tests/compiler/dart2js_extra/mirrors_used_closure_test.dart
+++ b/tests/compiler/dart2js_extra/mirrors_used_closure_test.dart
@@ -24,6 +24,6 @@
main() {
var f = [new A(), new B()][confuse(0)].bar;
- Expect.throws(() => reflect(f).invoke(#call, [], {}),
- (e) => e is UnsupportedError);
+ Expect.throws(
+ () => reflect(f).invoke(#call, [], {}), (e) => e is UnsupportedError);
}
diff --git a/tests/compiler/dart2js_extra/mirrors_used_metatargets_test.dart b/tests/compiler/dart2js_extra/mirrors_used_metatargets_test.dart
index cf8c035..54513d9 100644
--- a/tests/compiler/dart2js_extra/mirrors_used_metatargets_test.dart
+++ b/tests/compiler/dart2js_extra/mirrors_used_metatargets_test.dart
@@ -6,6 +6,7 @@
import 'dart:mirrors';
const x = const X();
+
class X {
const X();
}
diff --git a/tests/compiler/dart2js_extra/mirrors_used_native_test.dart b/tests/compiler/dart2js_extra/mirrors_used_native_test.dart
index a546682..85dbb35 100644
--- a/tests/compiler/dart2js_extra/mirrors_used_native_test.dart
+++ b/tests/compiler/dart2js_extra/mirrors_used_native_test.dart
@@ -10,5 +10,5 @@
main() {
Expect.equals(3, reflect([1, 2, 3]).getField(#length).reflectee);
Expect.throws(() => reflect({"hest": 42}).getField(#length),
- (e) => e is UnsupportedError);
+ (e) => e is UnsupportedError);
}
diff --git a/tests/compiler/dart2js_extra/mirrors_used_warning2_test.dart b/tests/compiler/dart2js_extra/mirrors_used_warning2_test.dart
index 1ac19d6..699595a 100644
--- a/tests/compiler/dart2js_extra/mirrors_used_warning2_test.dart
+++ b/tests/compiler/dart2js_extra/mirrors_used_warning2_test.dart
@@ -30,5 +30,5 @@
main() {
runZoned(runTests,
- zoneSpecification: new ZoneSpecification(print: capturePrint));
+ zoneSpecification: new ZoneSpecification(print: capturePrint));
}
diff --git a/tests/compiler/dart2js_extra/mirrors_used_warning_test.dart b/tests/compiler/dart2js_extra/mirrors_used_warning_test.dart
index 343e090..4a8a649 100644
--- a/tests/compiler/dart2js_extra/mirrors_used_warning_test.dart
+++ b/tests/compiler/dart2js_extra/mirrors_used_warning_test.dart
@@ -24,15 +24,19 @@
Expect.equals("foo", new A().foo);
Expect.isTrue(lines.isEmpty);
var barResult = new A().bar;
- Expect.equals("bar", barResult); /// minif: ok
+ Expect.equals("bar", barResult);
+
+ /// minif: ok
Expect.isTrue(lines.length == 1);
var line = lines.first;
Expect.isTrue(line.contains("Warning") &&
- line.contains("bar") && /// minif: continued
- line.contains("minif"));
+ line.contains("bar") &&
+
+ /// minif: continued
+ line.contains("minif"));
}
main() {
runZoned(runTests,
- zoneSpecification: new ZoneSpecification(print: capturePrint));
+ zoneSpecification: new ZoneSpecification(print: capturePrint));
}
diff --git a/tests/compiler/dart2js_extra/named_parameter_for_static_test.dart b/tests/compiler/dart2js_extra/named_parameter_for_static_test.dart
index 4efa524..4a4f817 100644
--- a/tests/compiler/dart2js_extra/named_parameter_for_static_test.dart
+++ b/tests/compiler/dart2js_extra/named_parameter_for_static_test.dart
@@ -65,7 +65,15 @@
B.three() : super.oneOptionalArgument(1, b: 2);
B();
- B_one() { super.twoOptArgs(a: 1, b: 2); }
- B_two() { super.twoOptArgs(b: 2, a: 1); }
- B_three() { super.oneOptArg(1, b: 2); }
+ B_one() {
+ super.twoOptArgs(a: 1, b: 2);
+ }
+
+ B_two() {
+ super.twoOptArgs(b: 2, a: 1);
+ }
+
+ B_three() {
+ super.oneOptArg(1, b: 2);
+ }
}
diff --git a/tests/compiler/dart2js_extra/no_such_method_test.dart b/tests/compiler/dart2js_extra/no_such_method_test.dart
index a139c02..38375d3 100644
--- a/tests/compiler/dart2js_extra/no_such_method_test.dart
+++ b/tests/compiler/dart2js_extra/no_such_method_test.dart
@@ -9,13 +9,15 @@
String name;
List args;
NoSuchMethodInfo(Object r, String m, List a)
- : receiver = r, name = m, args = a;
+ : receiver = r,
+ name = m,
+ args = a;
}
class A {
noSuchMethod(Invocation invocation) {
- topLevelInfo = new NoSuchMethodInfo(this, invocation.memberName,
- invocation.positionalArguments);
+ topLevelInfo = new NoSuchMethodInfo(
+ this, invocation.memberName, invocation.positionalArguments);
return topLevelInfo;
}
diff --git a/tests/compiler/dart2js_extra/null_test.dart b/tests/compiler/dart2js_extra/null_test.dart
index 317c124..2378a91 100644
--- a/tests/compiler/dart2js_extra/null_test.dart
+++ b/tests/compiler/dart2js_extra/null_test.dart
@@ -5,7 +5,7 @@
import "package:expect/expect.dart";
null1() {
- return; // implicit null;
+ return; // implicit null;
}
null2() {
@@ -13,7 +13,7 @@
}
null3() {
- var x; // Implicit null value.
+ var x; // Implicit null value.
return x;
}
diff --git a/tests/compiler/dart2js_extra/operator2_test.dart b/tests/compiler/dart2js_extra/operator2_test.dart
index 34f2a60..4adff2d 100644
--- a/tests/compiler/dart2js_extra/operator2_test.dart
+++ b/tests/compiler/dart2js_extra/operator2_test.dart
@@ -4,17 +4,49 @@
import "package:expect/expect.dart";
-int zero() { return 0; }
-int one() { return 1; }
-int minus1() { return 0 - 1; }
-int two() { return 2; }
-int three() { return 3; }
-int five() { return 5; }
-int minus5() { return 0 - 5; }
-int ninetyNine() { return 99; }
-int four99() { return 499; }
-int four99times99() { return 499 * 99; }
-int four99times99plus1() { return 499 * 99 + 1; }
+int zero() {
+ return 0;
+}
+
+int one() {
+ return 1;
+}
+
+int minus1() {
+ return 0 - 1;
+}
+
+int two() {
+ return 2;
+}
+
+int three() {
+ return 3;
+}
+
+int five() {
+ return 5;
+}
+
+int minus5() {
+ return 0 - 5;
+}
+
+int ninetyNine() {
+ return 99;
+}
+
+int four99() {
+ return 499;
+}
+
+int four99times99() {
+ return 499 * 99;
+}
+
+int four99times99plus1() {
+ return 499 * 99 + 1;
+}
void addTest() {
var m1 = 0 - 1;
diff --git a/tests/compiler/dart2js_extra/operator3_test.dart b/tests/compiler/dart2js_extra/operator3_test.dart
index 5ad4460..04ceec8 100644
--- a/tests/compiler/dart2js_extra/operator3_test.dart
+++ b/tests/compiler/dart2js_extra/operator3_test.dart
@@ -4,17 +4,49 @@
import "package:expect/expect.dart";
-int zero() { return 0; }
-int one() { return 1; }
-int minus1() { return 0 - 1; }
-int two() { return 2; }
-int three() { return 3; }
-int five() { return 5; }
-int minus5() { return 0 - 5; }
-int ninetyNine() { return 99; }
-int four99() { return 499; }
-int four99times99() { return 499 * 99; }
-int four99times99plus1() { return 499 * 99 + 1; }
+int zero() {
+ return 0;
+}
+
+int one() {
+ return 1;
+}
+
+int minus1() {
+ return 0 - 1;
+}
+
+int two() {
+ return 2;
+}
+
+int three() {
+ return 3;
+}
+
+int five() {
+ return 5;
+}
+
+int minus5() {
+ return 0 - 5;
+}
+
+int ninetyNine() {
+ return 99;
+}
+
+int four99() {
+ return 499;
+}
+
+int four99times99() {
+ return 499 * 99;
+}
+
+int four99times99plus1() {
+ return 499 * 99 + 1;
+}
void postPlusPlusTest() {
var x = zero();
diff --git a/tests/compiler/dart2js_extra/operator_test.dart b/tests/compiler/dart2js_extra/operator_test.dart
index 96ee9dc..2d5163a 100644
--- a/tests/compiler/dart2js_extra/operator_test.dart
+++ b/tests/compiler/dart2js_extra/operator_test.dart
@@ -3,7 +3,9 @@
// BSD-style license that can be found in the LICENSE file.
import "package:expect/expect.dart";
-@NoInline() @AssumeDynamic()
+
+@NoInline()
+@AssumeDynamic()
confuse(x) => x;
@NoInline()
@@ -17,7 +19,7 @@
uint31(x) {
var result = confuse(x);
if (x is int) {
- var masked = 0x7fffffff & x; // inferred uint31 type.
+ var masked = 0x7fffffff & x; // inferred uint31 type.
if (masked == x) return masked;
}
throw new ArgumentError('Not uint31: $x');
@@ -27,47 +29,71 @@
uint32(x) {
var result = confuse(x);
if (x is int) {
- var masked = 0xffffffff & x; // inferred uint32 type.
+ var masked = 0xffffffff & x; // inferred uint32 type.
if (masked == x) return masked;
}
throw new ArgumentError('Not uint32: $x');
}
@NoInline()
-int zero() { return 0; }
+int zero() {
+ return 0;
+}
@NoInline()
-int one() { return 1; }
+int one() {
+ return 1;
+}
@NoInline()
-int minus1() { return 0 - 1; }
+int minus1() {
+ return 0 - 1;
+}
@NoInline()
-int minus2() { return 0 - 2; }
+int minus2() {
+ return 0 - 2;
+}
@NoInline()
-int two() { return 2; }
+int two() {
+ return 2;
+}
@NoInline()
-int three() { return 3; }
+int three() {
+ return 3;
+}
@NoInline()
-int five() { return 5; }
+int five() {
+ return 5;
+}
@NoInline()
-int minus5() { return 0 - 5; }
+int minus5() {
+ return 0 - 5;
+}
@NoInline()
-int ninetyNine() { return 99; }
+int ninetyNine() {
+ return 99;
+}
@NoInline()
-int four99() { return 499; }
+int four99() {
+ return 499;
+}
@NoInline()
-int four99times99() { return 499 * 99; }
+int four99times99() {
+ return 499 * 99;
+}
@NoInline()
-int four99times99plus1() { return 499 * 99 + 1; }
+int four99times99plus1() {
+ return 499 * 99 + 1;
+}
@NoInline()
void addTest() {
@@ -159,42 +185,42 @@
// Signed int32 boundary is involved in optimizations.
- Expect.equals(-0x80000000, -0x80000000 ~/ 1.0);
- Expect.equals(-0x80000000, -0x80000000 ~/ 1.0000000000000001);
- Expect.equals(-0x7fffffff, -0x80000000 ~/ 1.0000000000000002);
+ Expect.equals(-0x80000000, -0x80000000 ~/ 1.0);
+ Expect.equals(-0x80000000, -0x80000000 ~/ 1.0000000000000001);
+ Expect.equals(-0x7fffffff, -0x80000000 ~/ 1.0000000000000002);
- Expect.equals(-0x80000000, asNum(-0x80000000) ~/ 1.0);
- Expect.equals(-0x80000000, asNum(-0x80000000) ~/ 1.0000000000000001);
- Expect.equals(-0x7fffffff, asNum(-0x80000000) ~/ 1.0000000000000002);
+ Expect.equals(-0x80000000, asNum(-0x80000000) ~/ 1.0);
+ Expect.equals(-0x80000000, asNum(-0x80000000) ~/ 1.0000000000000001);
+ Expect.equals(-0x7fffffff, asNum(-0x80000000) ~/ 1.0000000000000002);
- Expect.equals(-0x80000000, asNum(0x80000000) ~/ -1.0);
- Expect.equals(-0x80000000, asNum(0x80000000) ~/ -1.0000000000000001);
- Expect.equals(-0x7fffffff, asNum(0x80000000) ~/ -1.0000000000000002);
+ Expect.equals(-0x80000000, asNum(0x80000000) ~/ -1.0);
+ Expect.equals(-0x80000000, asNum(0x80000000) ~/ -1.0000000000000001);
+ Expect.equals(-0x7fffffff, asNum(0x80000000) ~/ -1.0000000000000002);
- Expect.equals(0x7fffffff, 0x10000000 ~/ .12500000000000002);
- Expect.equals(0x80000000, 0x10000000 ~/ .125);
- Expect.equals(-0x7fffffff, 0x10000000 ~/ -.12500000000000002);
- Expect.equals(-0x80000000, 0x10000000 ~/ -.125);
+ Expect.equals(0x7fffffff, 0x10000000 ~/ .12500000000000002);
+ Expect.equals(0x80000000, 0x10000000 ~/ .125);
+ Expect.equals(-0x7fffffff, 0x10000000 ~/ -.12500000000000002);
+ Expect.equals(-0x80000000, 0x10000000 ~/ -.125);
- Expect.equals(0x7fffffff, uint31(0x10000000) ~/ .12500000000000002);
- Expect.equals(0x80000000, uint31(0x10000000) ~/ .125);
- Expect.equals(-0x7fffffff, uint31(0x10000000) ~/ -.12500000000000002);
- Expect.equals(-0x80000000, uint31(0x10000000) ~/ -.125);
+ Expect.equals(0x7fffffff, uint31(0x10000000) ~/ .12500000000000002);
+ Expect.equals(0x80000000, uint31(0x10000000) ~/ .125);
+ Expect.equals(-0x7fffffff, uint31(0x10000000) ~/ -.12500000000000002);
+ Expect.equals(-0x80000000, uint31(0x10000000) ~/ -.125);
// These can be compiled to `(a / 2) | 0`.
- Expect.equals(100, uint31(200) ~/ 2);
- Expect.equals(100, uint32(200) ~/ 2);
+ Expect.equals(100, uint31(200) ~/ 2);
+ Expect.equals(100, uint32(200) ~/ 2);
- Expect.equals(100, asNum(200) ~/ 2);
- Expect.equals(100, confuse(200) ~/ 2);
- Expect.equals(-100, uint31(200) ~/ -2);
- Expect.equals(-100, uint32(200) ~/ -2);
- Expect.equals(-100, asNum(200) ~/ -2);
- Expect.equals(-100, confuse(200) ~/ -2);
+ Expect.equals(100, asNum(200) ~/ 2);
+ Expect.equals(100, confuse(200) ~/ 2);
+ Expect.equals(-100, uint31(200) ~/ -2);
+ Expect.equals(-100, uint32(200) ~/ -2);
+ Expect.equals(-100, asNum(200) ~/ -2);
+ Expect.equals(-100, confuse(200) ~/ -2);
// These can be compiled to `((a + b) / 2) | 0`.
- Expect.equals(100, (uint31(100) + uint31(100)) ~/ 2);
- Expect.equals(0x7fffffff, (uint31(0x7fffffff) + uint31(0x7fffffff)) ~/ 2);
+ Expect.equals(100, (uint31(100) + uint31(100)) ~/ 2);
+ Expect.equals(0x7fffffff, (uint31(0x7fffffff) + uint31(0x7fffffff)) ~/ 2);
// NaN and Infinity results are errors.
Expect.throws(() => -1 ~/ 0);
@@ -302,8 +328,8 @@
Expect.equals(34, four99() & 42);
Expect.equals(3, minus5() & 7);
- Expect.equals(0, uint31(0x7ffffffe) & uint31(1));
- Expect.equals(0, asNum(0x7ffffffe) & asNum(1));
+ Expect.equals(0, uint31(0x7ffffffe) & uint31(1));
+ Expect.equals(0, asNum(0x7ffffffe) & asNum(1));
}
@NoInline()
diff --git a/tests/compiler/dart2js_extra/panda_lib.dart b/tests/compiler/dart2js_extra/panda_lib.dart
index e56a8ac..1d20b03 100644
--- a/tests/compiler/dart2js_extra/panda_lib.dart
+++ b/tests/compiler/dart2js_extra/panda_lib.dart
@@ -5,6 +5,5 @@
library panda_lib;
class Panda {
- Panda() {
- }
+ Panda() {}
}
diff --git a/tests/compiler/dart2js_extra/panda_test.dart b/tests/compiler/dart2js_extra/panda_test.dart
index 793a5ab..2afaee6 100644
--- a/tests/compiler/dart2js_extra/panda_test.dart
+++ b/tests/compiler/dart2js_extra/panda_test.dart
@@ -3,6 +3,7 @@
// BSD-style license that can be found in the LICENSE file.
library panda_test;
+
import "package:expect/expect.dart";
import 'panda_lib.dart' as p;
diff --git a/tests/compiler/dart2js_extra/phi_elimination_test.dart b/tests/compiler/dart2js_extra/phi_elimination_test.dart
index ed2fb07..fe3f33f 100644
--- a/tests/compiler/dart2js_extra/phi_elimination_test.dart
+++ b/tests/compiler/dart2js_extra/phi_elimination_test.dart
@@ -8,14 +8,18 @@
var a = 0;
var c = 0;
- if (a == 0) c = a++;
- else c = a--;
+ if (a == 0)
+ c = a++;
+ else
+ c = a--;
Expect.equals(1, a);
Expect.equals(0, c);
- if (a == 0) c = a++;
- else c = a--;
+ if (a == 0)
+ c = a++;
+ else
+ c = a--;
Expect.equals(0, a);
Expect.equals(1, c);
diff --git a/tests/compiler/dart2js_extra/phi_gvn_test.dart b/tests/compiler/dart2js_extra/phi_gvn_test.dart
index 703834f..558ce8b 100644
--- a/tests/compiler/dart2js_extra/phi_gvn_test.dart
+++ b/tests/compiler/dart2js_extra/phi_gvn_test.dart
@@ -4,7 +4,7 @@
import "package:expect/expect.dart";
-foo(x) { }
+foo(x) {}
main() {
for (var i = 0; i < 1; i++) {
diff --git a/tests/compiler/dart2js_extra/regress/4434_test.dart b/tests/compiler/dart2js_extra/regress/4434_test.dart
index 0f23991..72582f7 100644
--- a/tests/compiler/dart2js_extra/regress/4434_test.dart
+++ b/tests/compiler/dart2js_extra/regress/4434_test.dart
@@ -6,7 +6,7 @@
import '4434_lib.dart';
-class B extends A { }
+class B extends A {}
main() {
B b = new B();
diff --git a/tests/compiler/dart2js_extra/regress/4515_3_test.dart b/tests/compiler/dart2js_extra/regress/4515_3_test.dart
index f224d70..23438ad 100644
--- a/tests/compiler/dart2js_extra/regress/4515_3_test.dart
+++ b/tests/compiler/dart2js_extra/regress/4515_3_test.dart
@@ -16,7 +16,7 @@
var v = null;
try {
v = f(a.a);
- } catch (e) { }
+ } catch (e) {}
Expect.equals(null, v);
}
diff --git a/tests/compiler/dart2js_extra/runtime_type_test.dart b/tests/compiler/dart2js_extra/runtime_type_test.dart
index 8f0b0f4..c307ef4 100644
--- a/tests/compiler/dart2js_extra/runtime_type_test.dart
+++ b/tests/compiler/dart2js_extra/runtime_type_test.dart
@@ -21,10 +21,10 @@
Expect.equals('C<bool>', new C<bool>().runtimeType.toString());
Expect.equals('D', new D().runtimeType.toString());
Expect.equals('D<dynamic, int, dynamic>',
- new D<dynamic, int, dynamic>().runtimeType.toString());
+ new D<dynamic, int, dynamic>().runtimeType.toString());
D d = new D<dynamic, D, D<dynamic, dynamic, int>>();
- Expect.equals('D<dynamic, D, D<dynamic, dynamic, int>>',
- d.runtimeType.toString());
+ Expect.equals(
+ 'D<dynamic, D, D<dynamic, dynamic, int>>', d.runtimeType.toString());
Expect.equals(r'C<Class$With$Dollar>',
- new C<Class$With$Dollar>().runtimeType.toString());
+ new C<Class$With$Dollar>().runtimeType.toString());
}
diff --git a/tests/compiler/dart2js_extra/source_mapping_crash_test.dart b/tests/compiler/dart2js_extra/source_mapping_crash_test.dart
index 98c6ec9..38ca4c6 100644
--- a/tests/compiler/dart2js_extra/source_mapping_crash_test.dart
+++ b/tests/compiler/dart2js_extra/source_mapping_crash_test.dart
@@ -10,7 +10,9 @@
Sub(var x) : super(x.y);
}
-class X { var y; }
+class X {
+ var y;
+}
main() {
new Sub(new X());
diff --git a/tests/compiler/dart2js_extra/string_escape_test.dart b/tests/compiler/dart2js_extra/string_escape_test.dart
index 04bd109..3bd1b99 100644
--- a/tests/compiler/dart2js_extra/string_escape_test.dart
+++ b/tests/compiler/dart2js_extra/string_escape_test.dart
@@ -55,17 +55,31 @@
}
testUEscapes() {
- List/*String*/ examples =
- ["\u0000\u0001\u0022\u0027\u005c\u007f\u0080\u00ff"
- "\u0100\u1000\ud7ff\ue000\uffff",
- '\u0000\u0001\u0022\u0027\u005c\u007f\u0080\u00ff'
- '\u0100\u1000\ud7ff\ue000\uffff',
- """\u0000\u0001\u0022\u0027\u005c\u007f\u0080\u00ff"""
- """\u0100\u1000\ud7ff\ue000\uffff""",
- '''\u0000\u0001\u0022\u0027\u005c\u007f\u0080\u00ff'''
- '''\u0100\u1000\ud7ff\ue000\uffff'''];
- List/*<int>*/ values = [0, 1, 0x22, 0x27, 0x5c, 0x7f, 0x80, 0xff,
- 0x100, 0x1000, 0xd7ff, 0xe000, 0xffff];
+ List /*String*/ examples = [
+ "\u0000\u0001\u0022\u0027\u005c\u007f\u0080\u00ff"
+ "\u0100\u1000\ud7ff\ue000\uffff",
+ '\u0000\u0001\u0022\u0027\u005c\u007f\u0080\u00ff'
+ '\u0100\u1000\ud7ff\ue000\uffff',
+ """\u0000\u0001\u0022\u0027\u005c\u007f\u0080\u00ff"""
+ """\u0100\u1000\ud7ff\ue000\uffff""",
+ '''\u0000\u0001\u0022\u0027\u005c\u007f\u0080\u00ff'''
+ '''\u0100\u1000\ud7ff\ue000\uffff'''
+ ];
+ List/*<int>*/ values = [
+ 0,
+ 1,
+ 0x22,
+ 0x27,
+ 0x5c,
+ 0x7f,
+ 0x80,
+ 0xff,
+ 0x100,
+ 0x1000,
+ 0xd7ff,
+ 0xe000,
+ 0xffff
+ ];
for (String s in examples) {
Expect.equals(values.length, s.length);
for (int i = 0; i < values.length; i++) {
@@ -73,8 +87,7 @@
}
}
// No characters above 0xffff until Leg supports that.
- var long =
- "\u{0}\u{00}\u{000}\u{0000}\u{00000}\u{000000}"
+ var long = "\u{0}\u{00}\u{000}\u{0000}\u{00000}\u{000000}"
"\u{1}\u{01}\u{001}\u{00001}"
"\u{ffff}\u{0ffff}\u{00ffff}";
var longValues = [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0xffff, 0xffff, 0xffff];
@@ -88,10 +101,10 @@
// All non-control ASCII characters escaped, except those with special
// meaning: b, f, n, r, t, u, v, and x (replaced by \x00).
var asciiLiterals =
- "\ \!\"\#\$\%\&\'\(\)\*\+\,\-\.\/\0\1\2\3\4\5\6\7\8\9\:\;\<\=\>"
- "\?\@\A\B\C\D\E\F\G\H\I\J\K\L\M\N\O\P\Q\R\S\T\U\V\W\X\Y\Z\[\\\]"
- "\^\_\`\a\x00\c\d\e\x00\g\h\i\j\k\l\m\x00\o\p\q\x00\s\x00\x00\x00"
- "\w\x00\y\z\{\|\}\~\";
+ "\ \!\"\#\$\%\&\'\(\)\*\+\,\-\.\/\0\1\2\3\4\5\6\7\8\9\:\;\<\=\>"
+ "\?\@\A\B\C\D\E\F\G\H\I\J\K\L\M\N\O\P\Q\R\S\T\U\V\W\X\Y\Z\[\\\]"
+ "\^\_\`\a\x00\c\d\e\x00\g\h\i\j\k\l\m\x00\o\p\q\x00\s\x00\x00\x00"
+ "\w\x00\y\z\{\|\}\~\";
Expect.equals(128 - 32, asciiLiterals.length);
for (int i = 32; i < 128; i++) {
@@ -102,7 +115,6 @@
}
}
-
testQuotes() {
// The string [ "' ].
String bothQuotes = ' "' "' ";
@@ -114,7 +126,6 @@
Expect.equals(bothQuotes, r''' "' ''');
}
-
testRawStrings() {
String raw1 = r'\x00';
Expect.equals(4, raw1.length);
diff --git a/tests/compiler/dart2js_extra/string_interpolation_dynamic_test.dart b/tests/compiler/dart2js_extra/string_interpolation_dynamic_test.dart
index 461bcfe..ab10b07 100644
--- a/tests/compiler/dart2js_extra/string_interpolation_dynamic_test.dart
+++ b/tests/compiler/dart2js_extra/string_interpolation_dynamic_test.dart
Binary files differ
diff --git a/tests/compiler/dart2js_extra/string_interpolation_opt1_test.dart b/tests/compiler/dart2js_extra/string_interpolation_opt1_test.dart
index 329d633..60e92d4 100644
--- a/tests/compiler/dart2js_extra/string_interpolation_opt1_test.dart
+++ b/tests/compiler/dart2js_extra/string_interpolation_opt1_test.dart
@@ -27,7 +27,7 @@
}
void testString() {
- var a = new List(100); // 'null' values in here are JavaScript undefined.
+ var a = new List(100); // 'null' values in here are JavaScript undefined.
spoil(a);
var s = returnsNullOrString('hi');
var x = a[2];
@@ -39,7 +39,7 @@
}
void testInt() {
- var a = new List(100); // 'null' values in here are JavaScript undefined.
+ var a = new List(100); // 'null' values in here are JavaScript undefined.
spoil(a);
var s = returnsNullOrInt(123);
var x = a[2];
diff --git a/tests/compiler/dart2js_extra/string_interpolation_test.dart b/tests/compiler/dart2js_extra/string_interpolation_test.dart
index b8350e1..3407260 100644
--- a/tests/compiler/dart2js_extra/string_interpolation_test.dart
+++ b/tests/compiler/dart2js_extra/string_interpolation_test.dart
Binary files differ
diff --git a/tests/compiler/dart2js_extra/super_constructor1_test.dart b/tests/compiler/dart2js_extra/super_constructor1_test.dart
index c6fcb01..b570312 100644
--- a/tests/compiler/dart2js_extra/super_constructor1_test.dart
+++ b/tests/compiler/dart2js_extra/super_constructor1_test.dart
@@ -15,14 +15,18 @@
class B extends A {
int y;
- B(i) : y = i++, super(i + 5) {
+ B(i)
+ : y = i++,
+ super(i + 5) {
message = '${message}B($i)';
}
}
class C extends B {
var z;
- C(i) : super(i * 3), z = i {
+ C(i)
+ : super(i * 3),
+ z = i {
message = '${message}C($i)';
}
}
diff --git a/tests/compiler/dart2js_extra/this_redirecting_constructor_test.dart b/tests/compiler/dart2js_extra/this_redirecting_constructor_test.dart
index 101aa1c..feeedd4 100644
--- a/tests/compiler/dart2js_extra/this_redirecting_constructor_test.dart
+++ b/tests/compiler/dart2js_extra/this_redirecting_constructor_test.dart
@@ -10,9 +10,13 @@
class C {
var x;
- C() { x = 1; }
- C.C() { x = 2; }
- C.redirecting(): this.C();
+ C() {
+ x = 1;
+ }
+ C.C() {
+ x = 2;
+ }
+ C.redirecting() : this.C();
}
main() {
diff --git a/tests/compiler/dart2js_extra/this_test.dart b/tests/compiler/dart2js_extra/this_test.dart
index 18cf323..e0804e7 100644
--- a/tests/compiler/dart2js_extra/this_test.dart
+++ b/tests/compiler/dart2js_extra/this_test.dart
@@ -7,7 +7,9 @@
class A {
int x;
getX() => this.x;
- setX(val) { this.x = val; }
+ setX(val) {
+ this.x = val;
+ }
}
main() {
diff --git a/tests/compiler/dart2js_extra/to_string_test.dart b/tests/compiler/dart2js_extra/to_string_test.dart
index 6324a78..7157548 100644
--- a/tests/compiler/dart2js_extra/to_string_test.dart
+++ b/tests/compiler/dart2js_extra/to_string_test.dart
@@ -4,13 +4,14 @@
import "package:expect/expect.dart";
-class A extends Object {
-}
+class A extends Object {}
class Concater {
final x;
final y;
- Concater(x, y) : this.x = x, this.y = y;
+ Concater(x, y)
+ : this.x = x,
+ this.y = y;
add() => x + y.toString();
}
diff --git a/tests/compiler/dart2js_extra/truncation_errors_test.dart b/tests/compiler/dart2js_extra/truncation_errors_test.dart
index 1e3767c..18105d8 100644
--- a/tests/compiler/dart2js_extra/truncation_errors_test.dart
+++ b/tests/compiler/dart2js_extra/truncation_errors_test.dart
@@ -7,7 +7,8 @@
import 'package:expect/expect.dart';
-@NoInline() @AssumeDynamic()
+@NoInline()
+@AssumeDynamic()
confuse(x) => x;
void find1(expected, thunk) {
@@ -19,11 +20,10 @@
exceptionText = '$e';
}
if (exceptionText == null) {
- Expect.fail(
- 'Expected exception containing "$expected", returned: $returned');
+ Expect
+ .fail('Expected exception containing "$expected", returned: $returned');
}
- Expect.isTrue(
- exceptionText.contains(expected),
+ Expect.isTrue(exceptionText.contains(expected),
'Expected "$expected" in "$exceptionText"');
}
@@ -35,85 +35,58 @@
}
main() {
-
var NaN = double.NAN;
var Infinity = double.INFINITY;
- find(' Infinity: 123 ~/ 0',
- () => confuse(123) ~/ confuse(0),
- () => confuse(123) ~/ 0,
- () => 123 ~/ confuse(0),
- () => 123 ~/ 0);
+ find(' Infinity: 123 ~/ 0', () => confuse(123) ~/ confuse(0),
+ () => confuse(123) ~/ 0, () => 123 ~/ confuse(0), () => 123 ~/ 0);
- find('-Infinity: 123 ~/ -0.0',
- () => confuse(123) ~/ confuse(-0.0),
- () => confuse(123) ~/ -0.0,
- () => 123 ~/ confuse(-0.0),
- () => 123 ~/ -0.0);
+ find(
+ '-Infinity: 123 ~/ -0.0',
+ () => confuse(123) ~/ confuse(-0.0),
+ () => confuse(123) ~/ -0.0,
+ () => 123 ~/ confuse(-0.0),
+ () => 123 ~/ -0.0);
- find(' NaN: NaN ~/ 123',
- () => confuse(NaN) ~/ confuse(123),
- () => confuse(NaN) ~/ 123,
- () => NaN ~/ confuse(123),
- () => NaN ~/ 123);
+ find(' NaN: NaN ~/ 123', () => confuse(NaN) ~/ confuse(123),
+ () => confuse(NaN) ~/ 123, () => NaN ~/ confuse(123), () => NaN ~/ 123);
- find(' Infinity: 1e+200 ~/ 1e-200',
- () => confuse(1e200) ~/ confuse(1e-200),
- () => confuse(1e200) ~/ 1e-200,
- () => 1e200 ~/ confuse(1e-200),
- () => 1e200 ~/ 1e-200);
+ find(
+ ' Infinity: 1e+200 ~/ 1e-200',
+ () => confuse(1e200) ~/ confuse(1e-200),
+ () => confuse(1e200) ~/ 1e-200,
+ () => 1e200 ~/ confuse(1e-200),
+ () => 1e200 ~/ 1e-200);
- find('NaN.toInt()',
- () => confuse(NaN).toInt(),
- () => NaN.toInt());
- find(' Infinity.toInt()',
- () => confuse(Infinity).toInt(),
- () => Infinity.toInt());
- find('-Infinity.toInt()',
- () => confuse(-Infinity).toInt(),
- () => (-Infinity).toInt());
+ find('NaN.toInt()', () => confuse(NaN).toInt(), () => NaN.toInt());
+ find(' Infinity.toInt()', () => confuse(Infinity).toInt(),
+ () => Infinity.toInt());
+ find('-Infinity.toInt()', () => confuse(-Infinity).toInt(),
+ () => (-Infinity).toInt());
- find('NaN.ceil()',
- () => confuse(NaN).ceil(),
- () => NaN.ceil());
- find(' Infinity.ceil()',
- () => confuse(Infinity).ceil(),
- () => Infinity.ceil());
- find('-Infinity.ceil()',
- () => confuse(-Infinity).ceil(),
- () => (-Infinity).ceil());
+ find('NaN.ceil()', () => confuse(NaN).ceil(), () => NaN.ceil());
+ find(' Infinity.ceil()', () => confuse(Infinity).ceil(),
+ () => Infinity.ceil());
+ find('-Infinity.ceil()', () => confuse(-Infinity).ceil(),
+ () => (-Infinity).ceil());
- find('NaN.floor()',
- () => confuse(NaN).floor(),
- () => NaN.floor());
- find(' Infinity.floor()',
- () => confuse(Infinity).floor(),
- () => Infinity.floor());
- find('-Infinity.floor()',
- () => confuse(-Infinity).floor(),
- () => (-Infinity).floor());
+ find('NaN.floor()', () => confuse(NaN).floor(), () => NaN.floor());
+ find(' Infinity.floor()', () => confuse(Infinity).floor(),
+ () => Infinity.floor());
+ find('-Infinity.floor()', () => confuse(-Infinity).floor(),
+ () => (-Infinity).floor());
- find('NaN.round()',
- () => confuse(NaN).round(),
- () => NaN.round());
- find(' Infinity.round()',
- () => confuse(Infinity).round(),
- () => Infinity.round());
- find('-Infinity.round()',
- () => confuse(-Infinity).round(),
- () => (-Infinity).round());
+ find('NaN.round()', () => confuse(NaN).round(), () => NaN.round());
+ find(' Infinity.round()', () => confuse(Infinity).round(),
+ () => Infinity.round());
+ find('-Infinity.round()', () => confuse(-Infinity).round(),
+ () => (-Infinity).round());
// `truncate()` is the same as `toInt()`.
// We could change the runtime so that `truncate` is reported.
- find('NaN.toInt()',
- () => confuse(NaN).truncate(),
- () => NaN.truncate());
- find(' Infinity.toInt()',
- () => confuse(Infinity).truncate(),
- () => Infinity.truncate());
- find('-Infinity.toInt()',
- () => confuse(-Infinity).truncate(),
- () => (-Infinity).truncate());
-
+ find('NaN.toInt()', () => confuse(NaN).truncate(), () => NaN.truncate());
+ find(' Infinity.toInt()', () => confuse(Infinity).truncate(),
+ () => Infinity.truncate());
+ find('-Infinity.toInt()', () => confuse(-Infinity).truncate(),
+ () => (-Infinity).truncate());
}
-
diff --git a/tests/compiler/dart2js_extra/type_argument_factory_crash_test.dart b/tests/compiler/dart2js_extra/type_argument_factory_crash_test.dart
index 2ed0db6..36dd8eb 100644
--- a/tests/compiler/dart2js_extra/type_argument_factory_crash_test.dart
+++ b/tests/compiler/dart2js_extra/type_argument_factory_crash_test.dart
@@ -4,6 +4,7 @@
// A regression test for a dart2js crash.
library type.argument.factory.crash.test;
+
import "package:expect/expect.dart";
import 'dart:collection' show LinkedHashMap;
diff --git a/tests/compiler/dart2js_extra/type_argument_factory_nocrash_test.dart b/tests/compiler/dart2js_extra/type_argument_factory_nocrash_test.dart
index 7ddb90c..1708b04 100644
--- a/tests/compiler/dart2js_extra/type_argument_factory_nocrash_test.dart
+++ b/tests/compiler/dart2js_extra/type_argument_factory_nocrash_test.dart
@@ -4,6 +4,7 @@
// A regression test for a dart2js crash.
library type.argument.factory.nocrash.test;
+
import "package:expect/expect.dart";
import 'dart:collection' show LinkedHashMap;
diff --git a/tests/compiler/dart2js_extra/type_error_message_test.dart b/tests/compiler/dart2js_extra/type_error_message_test.dart
index 1f44f6f..e3f3f90 100644
--- a/tests/compiler/dart2js_extra/type_error_message_test.dart
+++ b/tests/compiler/dart2js_extra/type_error_message_test.dart
@@ -27,9 +27,10 @@
String nameOfC = (C).toString();
String nameOfInt = (int).toString();
String nameOfString = (String).toString();
- String expected = '$nameOfC<$nameOfC<$nameOfInt, $nameOfString>, $nameOfString>';
+ String expected =
+ '$nameOfC<$nameOfC<$nameOfInt, $nameOfString>, $nameOfString>';
Expect.isTrue(e.toString().contains(expected),
- 'Expected "$expected" in the message');
+ 'Expected "$expected" in the message');
caught = true;
}
Expect.isTrue(caught);
diff --git a/tests/compiler/dart2js_extra/useful_error_message_1_test.dart b/tests/compiler/dart2js_extra/useful_error_message_1_test.dart
index 07a6de0..111a145 100644
--- a/tests/compiler/dart2js_extra/useful_error_message_1_test.dart
+++ b/tests/compiler/dart2js_extra/useful_error_message_1_test.dart
@@ -33,8 +33,7 @@
Expect.fail('"$message" should contain "$tag"');
}
// When minified we will accept quoted names up to 3 characters.
- Expect.isTrue(
- message.contains(new RegExp("'..?.?'")),
+ Expect.isTrue(message.contains(new RegExp("'..?.?'")),
'"$message" should contain minified name');
}
}
diff --git a/tests/compiler/dart2js_native/abstract_class_test.dart b/tests/compiler/dart2js_native/abstract_class_test.dart
index df5738c..18e0af3 100644
--- a/tests/compiler/dart2js_native/abstract_class_test.dart
+++ b/tests/compiler/dart2js_native/abstract_class_test.dart
@@ -10,18 +10,17 @@
// abstract native classes can appear to have instances.
@Native("A")
-abstract class A {
-}
+abstract class A {}
@Native("B")
abstract class B {
- foo() native;
+ foo() native ;
}
class C {}
-makeA() native;
-makeB() native;
+makeA() native ;
+makeB() native ;
void setup() native """
// This code is all inside 'setup' and so not accesible from the global scope.
diff --git a/tests/compiler/dart2js_native/bound_closure_super_test.dart b/tests/compiler/dart2js_native/bound_closure_super_test.dart
index 345cafa..35b19e0 100644
--- a/tests/compiler/dart2js_native/bound_closure_super_test.dart
+++ b/tests/compiler/dart2js_native/bound_closure_super_test.dart
@@ -9,9 +9,7 @@
import 'bound_closure_test.dart' as bound_closure_test;
-import 'bound_closure_test.dart' show
- inscrutable,
- makeCC;
+import 'bound_closure_test.dart' show inscrutable, makeCC;
main() {
// Calling main from bound_closure_test.dart to set up native code.
diff --git a/tests/compiler/dart2js_native/bound_closure_test.dart b/tests/compiler/dart2js_native/bound_closure_test.dart
index afbecce..a637121 100644
--- a/tests/compiler/dart2js_native/bound_closure_test.dart
+++ b/tests/compiler/dart2js_native/bound_closure_test.dart
@@ -8,25 +8,25 @@
// Test calling convention of property extraction closures.
class AA {
- bar(a, [b = 'A']) => 'AA.bar($a, $b)'; // bar is plain dart convention.
- foo(a, [b = 'A']) => 'AA.foo($a, $b)'; // foo has interceptor convention.
+ bar(a, [b = 'A']) => 'AA.bar($a, $b)'; // bar is plain dart convention.
+ foo(a, [b = 'A']) => 'AA.foo($a, $b)'; // foo has interceptor convention.
}
@Native("BB")
class BB {
- foo(a, [b = 'B']) native;
+ foo(a, [b = 'B']) native ;
}
@Native("CC")
class CC extends BB {
- foo(a, [b = 'C']) native;
+ foo(a, [b = 'C']) native ;
get superfoo => super.foo;
}
-makeBB() native;
-makeCC() native;
-inscrutable(a) native;
+makeBB() native ;
+makeCC() native ;
+inscrutable(a) native ;
void setup() native r"""
function BB() {}
@@ -44,7 +44,6 @@
inscrutable = function(a){return a;};
""";
-
main() {
setup();
var a = inscrutable(new AA());
diff --git a/tests/compiler/dart2js_native/browser_compat_1_prepatched_test.dart b/tests/compiler/dart2js_native/browser_compat_1_prepatched_test.dart
index 36b7f9b..40662d8 100644
--- a/tests/compiler/dart2js_native/browser_compat_1_prepatched_test.dart
+++ b/tests/compiler/dart2js_native/browser_compat_1_prepatched_test.dart
@@ -10,22 +10,19 @@
// Test for dartNativeDispatchHooksTransformer, getTag hook.
@Native("T1A")
-class T1A {
-}
+class T1A {}
@Native("T1B")
-class T1B {
-}
+class T1B {}
@Native("T1C")
-class T1C {
-}
+class T1C {}
-makeT1A() native;
-makeT1B() native;
-makeT1C() native;
+makeT1A() native ;
+makeT1B() native ;
+makeT1C() native ;
-int getTagCallCount() native;
+int getTagCallCount() native ;
void setup() native r'''
function T1A() { } // Normal native class.
diff --git a/tests/compiler/dart2js_native/browser_compat_1_unpatched_test.dart b/tests/compiler/dart2js_native/browser_compat_1_unpatched_test.dart
index 56c9fb8..5e494d4 100644
--- a/tests/compiler/dart2js_native/browser_compat_1_unpatched_test.dart
+++ b/tests/compiler/dart2js_native/browser_compat_1_unpatched_test.dart
@@ -11,22 +11,19 @@
// Same as browser_compat_1_prepatched_test but with prepatching disabled.
@Native("T1A")
-class T1A {
-}
+class T1A {}
@Native("T1B")
-class T1B {
-}
+class T1B {}
@Native("T1C")
-class T1C {
-}
+class T1C {}
-makeT1A() native;
-makeT1B() native;
-makeT1C() native;
+makeT1A() native ;
+makeT1B() native ;
+makeT1C() native ;
-int getTagCallCount() native;
+int getTagCallCount() native ;
void setup() native r'''
function T1A() { } // Normal native class.
diff --git a/tests/compiler/dart2js_native/browser_compat_2_test.dart b/tests/compiler/dart2js_native/browser_compat_2_test.dart
index 858a067..eeb87fa 100644
--- a/tests/compiler/dart2js_native/browser_compat_2_test.dart
+++ b/tests/compiler/dart2js_native/browser_compat_2_test.dart
@@ -11,31 +11,31 @@
@Native("T1A")
class T1A {
- foo() native;
+ foo() native ;
}
@Native("T1B")
class T1B {
- foo() native;
+ foo() native ;
}
@Native("T1C")
class T1C {
- foo() native;
+ foo() native ;
}
@Native("T1D")
class T1D {
- foo() native;
+ foo() native ;
}
-makeT1A() native;
-makeT1B() native;
-makeT1C() native;
-makeT1D() native;
+makeT1A() native ;
+makeT1B() native ;
+makeT1C() native ;
+makeT1D() native ;
-int getTagCallCount() native;
-void clearTagCallCount() native;
+int getTagCallCount() native ;
+void clearTagCallCount() native ;
void setup() native r'''
function T1A() { this.v = "a"; }
diff --git a/tests/compiler/dart2js_native/compiler_test_internals.dart b/tests/compiler/dart2js_native/compiler_test_internals.dart
index be2c4b6..db3e31f 100644
--- a/tests/compiler/dart2js_native/compiler_test_internals.dart
+++ b/tests/compiler/dart2js_native/compiler_test_internals.dart
@@ -4,7 +4,7 @@
library compiler_test_internals;
-export 'dart:_js_helper' show
- NoSideEffects, NoThrows, NoInline, IrRepresentation;
+export 'dart:_js_helper'
+ show NoSideEffects, NoThrows, NoInline, IrRepresentation;
export 'dart:_foreign_helper' show JS;
diff --git a/tests/compiler/dart2js_native/core_type_check_native_test.dart b/tests/compiler/dart2js_native/core_type_check_native_test.dart
index 41a4109..261acf7 100644
--- a/tests/compiler/dart2js_native/core_type_check_native_test.dart
+++ b/tests/compiler/dart2js_native/core_type_check_native_test.dart
@@ -8,25 +8,21 @@
var inscrutable = (int x) => x == 0 ? 0 : x | inscrutable(x & (x - 1));
@Native("A")
-class A {
-}
+class A {}
@Native("B")
-class B implements Comparable {
-}
+class B implements Comparable {}
@Native("C")
-class C implements Pattern {
-}
+class C implements Pattern {}
@Native("D")
-class D implements Pattern, Comparable {
-}
+class D implements Pattern, Comparable {}
-makeA() native;
-makeB() native;
-makeC() native;
-makeD() native;
+makeA() native ;
+makeB() native ;
+makeC() native ;
+makeD() native ;
void setup() native """
function A() {};
@@ -39,7 +35,6 @@
makeD = function() { return new D; }
""";
-
checkTest(value, expectComparable, expectPattern) {
Expect.equals(expectComparable, value is Comparable);
Expect.equals(expectPattern, value is Pattern);
@@ -59,19 +54,28 @@
}
checkAll(check) {
- var things =
- [[], 4, 4.2, 'foo', new Object(), makeA(), makeB(), makeC(), makeD()];
+ var things = [
+ [],
+ 4,
+ 4.2,
+ 'foo',
+ new Object(),
+ makeA(),
+ makeB(),
+ makeC(),
+ makeD()
+ ];
value(i) => things[inscrutable(i)];
- check(value(0), false, false); // List
- check(value(1), true, false); // int
- check(value(2), true, false); // num
- check(value(3), true, true); // String
- check(value(4), false, false); // Object
- check(value(5), false, false); // A
- check(value(6), true, false); // B
- check(value(7), false, true); // C
- check(value(8), true, true); // D
+ check(value(0), false, false); // List
+ check(value(1), true, false); // int
+ check(value(2), true, false); // num
+ check(value(3), true, true); // String
+ check(value(4), false, false); // Object
+ check(value(5), false, false); // A
+ check(value(6), true, false); // B
+ check(value(7), false, true); // C
+ check(value(8), true, true); // D
}
main() {
diff --git a/tests/compiler/dart2js_native/downcast_test.dart b/tests/compiler/dart2js_native/downcast_test.dart
index 6810a612..f993388 100644
--- a/tests/compiler/dart2js_native/downcast_test.dart
+++ b/tests/compiler/dart2js_native/downcast_test.dart
@@ -7,8 +7,7 @@
import "dart:_js_helper";
import "package:expect/expect.dart";
-abstract class J {
-}
+abstract class J {}
abstract class I extends J {
I read();
@@ -20,16 +19,15 @@
@Native("A")
class A implements I {
// The native class accepts only other native instances.
- A read() native;
- write(A x) native;
+ A read() native ;
+ write(A x) native ;
}
@Native("B")
-class B extends A {
-}
+class B extends A {}
-makeA() native;
-makeB() native;
+makeA() native ;
+makeB() native ;
void setup() native """
// This code is all inside 'setup' and so not accesible from the global scope.
diff --git a/tests/compiler/dart2js_native/error_safeToString_test.dart b/tests/compiler/dart2js_native/error_safeToString_test.dart
index 3322560..fa022d9 100644
--- a/tests/compiler/dart2js_native/error_safeToString_test.dart
+++ b/tests/compiler/dart2js_native/error_safeToString_test.dart
@@ -5,11 +5,12 @@
import "package:expect/expect.dart";
import 'dart:_foreign_helper' show JS_INTERCEPTOR_CONSTANT, JS;
import 'dart:_js_helper' show Native, Creates;
-import 'dart:_interceptors' show
- Interceptor,
- JavaScriptObject,
- PlainJavaScriptObject,
- UnknownJavaScriptObject;
+import 'dart:_interceptors'
+ show
+ Interceptor,
+ JavaScriptObject,
+ PlainJavaScriptObject,
+ UnknownJavaScriptObject;
// Test for safe formatting of JavaScript objects by Error.safeToString.
@@ -24,14 +25,14 @@
toString() => 'RRRRRRRR';
}
-makeA() native;
-makeB() native;
-makeC() native;
-makeD() native;
-makeE() native;
-makeP() native;
-makeQ() native;
-makeR() native;
+makeA() native ;
+makeB() native ;
+makeC() native ;
+makeD() native ;
+makeE() native ;
+makeP() native ;
+makeQ() native ;
+makeR() native ;
void setup() native r"""
makeA = function(){return {hello: 123};};
@@ -71,7 +72,6 @@
""";
-
expectTypeName(expectedName, s) {
var m = new RegExp(r"Instance of '(.*)'").firstMatch(s);
Expect.isNotNull(m);
@@ -89,7 +89,6 @@
final interceptorString =
Error.safeToString(JS_INTERCEPTOR_CONSTANT(Interceptor));
-
testDistinctInterceptors() {
// Test invariants needed for the other tests.
@@ -110,7 +109,6 @@
Expect.equals(unknownJsString, unk2);
}
-
testExternal() {
var x = makeA();
Expect.equals(plainJsString, Error.safeToString(x));
@@ -131,7 +129,7 @@
testNative() {
var x = makeP();
- Expect.isTrue(x is Purple); // This test forces Purple to be distinguished.
+ Expect.isTrue(x is Purple); // This test forces Purple to be distinguished.
Expect.notEquals(plainJsString, Error.safeToString(x));
Expect.notEquals(unknownJsString, Error.safeToString(x));
Expect.notEquals(interceptorString, Error.safeToString(x));
@@ -143,8 +141,7 @@
print('Q: $x ${Error.safeToString(x)}');
// We are going to get either the general interceptor or the JavaScript
// constructor.
- Expect.isTrue(
- "Instance of 'QQQQ'" == Error.safeToString(x) ||
+ Expect.isTrue("Instance of 'QQQQ'" == Error.safeToString(x) ||
interceptorString == Error.safeToString(x));
x = makeR();
diff --git a/tests/compiler/dart2js_native/event_loop_test.dart b/tests/compiler/dart2js_native/event_loop_test.dart
index d7ae5f4..18d2068 100644
--- a/tests/compiler/dart2js_native/event_loop_test.dart
+++ b/tests/compiler/dart2js_native/event_loop_test.dart
@@ -11,10 +11,10 @@
@Native("A")
class A {
- foo(Callback0 f) native;
+ foo(Callback0 f) native ;
}
-makeA() native;
+makeA() native ;
void setup() native r"""
function A() {}
@@ -36,8 +36,9 @@
var events = [];
asyncStart();
var a = makeA();
- new Future.microtask(() { events.add("scheduleMicrotask"); })
- .whenComplete(asyncEnd);
+ new Future.microtask(() {
+ events.add("scheduleMicrotask");
+ }).whenComplete(asyncEnd);
Expect.equals(499, a.foo(() {
events.add("closure to foo");
diff --git a/tests/compiler/dart2js_native/fake_thing_2_test.dart b/tests/compiler/dart2js_native/fake_thing_2_test.dart
index d243919..3ec92e0 100644
--- a/tests/compiler/dart2js_native/fake_thing_2_test.dart
+++ b/tests/compiler/dart2js_native/fake_thing_2_test.dart
@@ -10,16 +10,14 @@
// The difference between fake_thing_test and fake_thing_2_test is the
// presence of a used declared native class.
-class Thing {
-}
+class Thing {}
@Native("NT")
-class NativeThing {
-}
+class NativeThing {}
-make1() native;
-make2() native;
-make3() native;
+make1() native ;
+make2() native ;
+make3() native ;
void setup() native r"""
function A() {}
diff --git a/tests/compiler/dart2js_native/fake_thing_test.dart b/tests/compiler/dart2js_native/fake_thing_test.dart
index 20a84a2..8af303b 100644
--- a/tests/compiler/dart2js_native/fake_thing_test.dart
+++ b/tests/compiler/dart2js_native/fake_thing_test.dart
@@ -10,11 +10,10 @@
// This test currently fails because we do not recognize the need for
// interceptors without native *classes*.
-class Thing {
-}
+class Thing {}
-make1() native;
-make2() native;
+make1() native ;
+make2() native ;
void setup() native r"""
function A() {}
diff --git a/tests/compiler/dart2js_native/field_type2_test.dart b/tests/compiler/dart2js_native/field_type2_test.dart
index 6f8c35b..31de669 100644
--- a/tests/compiler/dart2js_native/field_type2_test.dart
+++ b/tests/compiler/dart2js_native/field_type2_test.dart
@@ -12,7 +12,7 @@
final parentNode;
}
-makeNode(parent) native;
+makeNode(parent) native ;
void setup() native """
// This code is all inside 'setup' and so not accesible from the global scope.
@@ -20,7 +20,6 @@
makeNode = function(p){return new Node(p);};
""";
-
main() {
setup();
var node = makeNode(null);
diff --git a/tests/compiler/dart2js_native/field_type_test.dart b/tests/compiler/dart2js_native/field_type_test.dart
index 75297ad..ebb83c6 100644
--- a/tests/compiler/dart2js_native/field_type_test.dart
+++ b/tests/compiler/dart2js_native/field_type_test.dart
@@ -11,10 +11,9 @@
@Native("Node")
class Node {
-
final Node parentNode;
- ModelSource _modelSource; // If null, inherited from parent.
+ ModelSource _modelSource; // If null, inherited from parent.
ModelSource get modelSource {
for (Node node = this; node != null; node = node.parentNode) {
@@ -26,7 +25,7 @@
// Copy of above code renamed with suffix '2'.
- ModelSource _modelSource2; // If null, inherited from parent.
+ ModelSource _modelSource2; // If null, inherited from parent.
ModelSource get modelSource2 {
for (Node node = this; node != null; node = node.parentNode) {
@@ -37,7 +36,7 @@
}
}
-makeNode(parent) native;
+makeNode(parent) native ;
class ModelSource {
var name;
@@ -51,7 +50,6 @@
makeNode = function(p){return new Node(p);};
""";
-
main() {
setup();
@@ -60,13 +58,13 @@
var n3 = makeNode(n2);
var m1 = new ModelSource('1');
- n2._modelSource = null; // null write.
- n2._modelSource = m1; // Non-null write.
+ n2._modelSource = null; // null write.
+ n2._modelSource = m1; // Non-null write.
var x1 = n3.modelSource;
Expect.identical(m1, x1);
var m2 = new ModelSource('2');
- n2._modelSource2 = m2; // The only write is non-null.
+ n2._modelSource2 = m2; // The only write is non-null.
var x2 = n3.modelSource2;
Expect.identical(m2, x2);
}
diff --git a/tests/compiler/dart2js_native/fixup_get_tag_test.dart b/tests/compiler/dart2js_native/fixup_get_tag_test.dart
index 0f68986..8fc9b70 100644
--- a/tests/compiler/dart2js_native/fixup_get_tag_test.dart
+++ b/tests/compiler/dart2js_native/fixup_get_tag_test.dart
@@ -8,8 +8,9 @@
// Test for dartExperimentalFixupGetTag.
@Native("A")
-class Foo { // There is one native class with dispatch tag 'A'.
- token() native;
+class Foo {
+ // There is one native class with dispatch tag 'A'.
+ token() native ;
}
void setup() native r"""
@@ -35,8 +36,8 @@
makeB = function() { return new B; };
""";
-makeA() native;
-makeB() native;
+makeA() native ;
+makeB() native ;
main() {
setup();
diff --git a/tests/compiler/dart2js_native/hash_code_test.dart b/tests/compiler/dart2js_native/hash_code_test.dart
index 452c7aa..c909a10 100644
--- a/tests/compiler/dart2js_native/hash_code_test.dart
+++ b/tests/compiler/dart2js_native/hash_code_test.dart
@@ -7,7 +7,8 @@
@Native("A")
class A {}
-makeA() native;
+
+makeA() native ;
void setup() native """
function A() {}
diff --git a/tests/compiler/dart2js_native/issue9182_test.dart b/tests/compiler/dart2js_native/issue9182_test.dart
index 8bbee65..5e06b35 100644
--- a/tests/compiler/dart2js_native/issue9182_test.dart
+++ b/tests/compiler/dart2js_native/issue9182_test.dart
@@ -30,7 +30,7 @@
makeA = function() { return new A; };
""";
-makeA() native;
+makeA() native ;
main() {
setup();
@@ -39,7 +39,7 @@
var foo = things[0];
var bar = things[1];
- Expect.equals(123, foo.Bar()); // Ensure that Foo.Bar is used.
+ Expect.equals(123, foo.Bar()); // Ensure that Foo.Bar is used.
Expect.equals(30, bar._x);
Expect.equals(40, bar._y);
diff --git a/tests/compiler/dart2js_native/js_const_test.dart b/tests/compiler/dart2js_native/js_const_test.dart
index 710323a..d777e1e 100644
--- a/tests/compiler/dart2js_native/js_const_test.dart
+++ b/tests/compiler/dart2js_native/js_const_test.dart
@@ -8,8 +8,8 @@
test1() {
var re = const JS_CONST(r'/-([\da-z])/ig');
- var fToUpper = const JS_CONST(
- r'function(_, letter){return letter.toUpperCase()}');
+ var fToUpper =
+ const JS_CONST(r'function(_, letter){return letter.toUpperCase()}');
var s1 = '-hello-world';
var s2 = JS('String', r'#.replace(#, #)', s1, re, fToUpper);
Expect.equals('HelloWorld', s2);
diff --git a/tests/compiler/dart2js_native/js_constant_test.dart b/tests/compiler/dart2js_native/js_constant_test.dart
index 19b2e6f..7658dc0 100644
--- a/tests/compiler/dart2js_native/js_constant_test.dart
+++ b/tests/compiler/dart2js_native/js_constant_test.dart
@@ -20,8 +20,8 @@
@NoInline()
checkString(r) {
- Expect.isTrue(r is String,
- 'Expected string, found ${r} of type ${r.runtimeType}');
+ Expect.isTrue(
+ r is String, 'Expected string, found ${r} of type ${r.runtimeType}');
}
test1() {
@@ -36,7 +36,6 @@
checkString(JS('', '#.toString()', -0.0));
}
-
main() {
test1();
test2();
diff --git a/tests/compiler/dart2js_native/jsobject_test.dart b/tests/compiler/dart2js_native/jsobject_test.dart
index 45fac7a..f7a92f9 100644
--- a/tests/compiler/dart2js_native/jsobject_test.dart
+++ b/tests/compiler/dart2js_native/jsobject_test.dart
@@ -4,13 +4,14 @@
import "package:expect/expect.dart";
import 'dart:_js_helper' show Native, Creates, setNativeSubclassDispatchRecord;
-import 'dart:_interceptors' show
- JSObject, // The interface, which may be re-exported by a
- // js-interop library.
- JavaScriptObject, // The interceptor abstract class.
- PlainJavaScriptObject, // The interceptor concrete class.
- UnknownJavaScriptObject, // The interceptor concrete class.
- Interceptor;
+import 'dart:_interceptors'
+ show
+ JSObject, // The interface, which may be re-exported by a
+ // js-interop library.
+ JavaScriptObject, // The interceptor abstract class.
+ PlainJavaScriptObject, // The interceptor concrete class.
+ UnknownJavaScriptObject, // The interceptor concrete class.
+ Interceptor;
// Test for JavaScript objects from outside the Dart program. Although we only
// export the interface [JSObject] to user level code, this test makes sure we
@@ -19,9 +20,9 @@
@Native('QQ')
class Q {}
-makeA() native;
-makeB() native;
-makeQ() native;
+makeA() native ;
+makeB() native ;
+makeQ() native ;
void setup() native r"""
makeA = function(){return {hello: 123};};
@@ -42,13 +43,13 @@
Expect.isTrue(x is JSObject);
Expect.isTrue(x is JavaScriptObject);
Expect.isTrue(x is PlainJavaScriptObject);
- Expect.isTrue(x is !UnknownJavaScriptObject);
+ Expect.isTrue(x is! UnknownJavaScriptObject);
Expect.equals(JSObject, x.runtimeType);
x = makeB();
Expect.isTrue(x is JSObject);
Expect.isTrue(x is JavaScriptObject);
- Expect.isTrue(x is !PlainJavaScriptObject);
+ Expect.isTrue(x is! PlainJavaScriptObject);
Expect.isTrue(x is UnknownJavaScriptObject);
Expect.equals(JSObject, x.runtimeType);
diff --git a/tests/compiler/dart2js_native/native_call_arity1_frog_test.dart b/tests/compiler/dart2js_native/native_call_arity1_frog_test.dart
index 624ffb5..ed3d131 100644
--- a/tests/compiler/dart2js_native/native_call_arity1_frog_test.dart
+++ b/tests/compiler/dart2js_native/native_call_arity1_frog_test.dart
@@ -15,19 +15,19 @@
@Native("A")
class A {
- int foo(int x) native;
+ int foo(int x) native ;
}
@Native("B")
class B {
- int foo([x, y, z]) native;
+ int foo([x, y, z]) native ;
}
// TODO(sra): Add a case where the parameters have default values. Wait until
// dart:html need non-null default values.
-A makeA() native;
-B makeB() native;
+A makeA() native ;
+B makeB() native ;
void setup() native """
function A() {}
@@ -40,7 +40,6 @@
makeB = function(){return new B;};
""";
-
testDynamicContext() {
var things = [makeA(), makeB()];
var a = things[0];
diff --git a/tests/compiler/dart2js_native/native_call_arity2_frog_test.dart b/tests/compiler/dart2js_native/native_call_arity2_frog_test.dart
index 245c03c..b99e07b 100644
--- a/tests/compiler/dart2js_native/native_call_arity2_frog_test.dart
+++ b/tests/compiler/dart2js_native/native_call_arity2_frog_test.dart
@@ -10,16 +10,16 @@
@Native("A")
class A {
- int foo([x, y]) native;
+ int foo([x, y]) native ;
}
@Native("B")
class B extends A {
- int foo([x, y]) native;
+ int foo([x, y]) native ;
}
-makeA() native;
-makeB() native;
+makeA() native ;
+makeB() native ;
void setup() native """
function inherits(child, parent) {
diff --git a/tests/compiler/dart2js_native/native_call_arity3_frog_test.dart b/tests/compiler/dart2js_native/native_call_arity3_frog_test.dart
index 0adb955..1b4048e 100644
--- a/tests/compiler/dart2js_native/native_call_arity3_frog_test.dart
+++ b/tests/compiler/dart2js_native/native_call_arity3_frog_test.dart
@@ -11,19 +11,19 @@
@Native("A")
class A {
- int foo(int x) native;
+ int foo(int x) native ;
}
@Native("B")
class B {
- int foo([x = null, y, z = null]) native;
+ int foo([x = null, y, z = null]) native ;
}
// TODO(sra): Add a case where the parameters have default values. Wait until
// dart:html need non-null default values.
-A makeA() native;
-B makeB() native;
+A makeA() native ;
+B makeB() native ;
void setup() native """
function A() {}
@@ -36,7 +36,6 @@
makeB = function(){return new B;};
""";
-
testDynamicContext() {
var things = [makeA(), makeB()];
var a = things[0];
diff --git a/tests/compiler/dart2js_native/native_checked_arguments1_frog_test.dart b/tests/compiler/dart2js_native/native_checked_arguments1_frog_test.dart
index bef06b4..9a64a3d 100644
--- a/tests/compiler/dart2js_native/native_checked_arguments1_frog_test.dart
+++ b/tests/compiler/dart2js_native/native_checked_arguments1_frog_test.dart
@@ -9,18 +9,18 @@
@Native("A")
class A {
- int foo(int x) native;
- int cmp(A other) native;
+ int foo(int x) native ;
+ int cmp(A other) native ;
}
@Native("B")
class B {
- String foo(String x) native;
- int cmp(B other) native;
+ String foo(String x) native ;
+ int cmp(B other) native ;
}
-A makeA() native;
-B makeB() native;
+A makeA() native ;
+B makeB() native ;
void setup() native """
function A() {}
diff --git a/tests/compiler/dart2js_native/native_checked_fields_frog_test.dart b/tests/compiler/dart2js_native/native_checked_fields_frog_test.dart
index 8992dc0..3ae79bf 100644
--- a/tests/compiler/dart2js_native/native_checked_fields_frog_test.dart
+++ b/tests/compiler/dart2js_native/native_checked_fields_frog_test.dart
@@ -17,8 +17,8 @@
String foo;
}
-A makeA() native;
-B makeB() native;
+A makeA() native ;
+B makeB() native ;
void setup() native """
function A() {}
diff --git a/tests/compiler/dart2js_native/native_class_avoids_hidden_name_frog_test.dart b/tests/compiler/dart2js_native/native_class_avoids_hidden_name_frog_test.dart
index e78544a..8690e4b 100644
--- a/tests/compiler/dart2js_native/native_class_avoids_hidden_name_frog_test.dart
+++ b/tests/compiler/dart2js_native/native_class_avoids_hidden_name_frog_test.dart
@@ -19,13 +19,14 @@
static BB create() => makeB();
}
-class CC { // Ordinary class with name clashing with native class.
+class CC {
+ // Ordinary class with name clashing with native class.
get name => 'CC';
static CC create() => new CC();
}
-makeA() native;
-makeB() native;
+makeA() native ;
+makeB() native ;
void setup1() native """
// Poison hidden native names 'BB' and 'CC' to prove the compiler didn't place
diff --git a/tests/compiler/dart2js_native/native_class_fields_2_test.dart b/tests/compiler/dart2js_native/native_class_fields_2_test.dart
index 4e67b81..419d82f 100644
--- a/tests/compiler/dart2js_native/native_class_fields_2_test.dart
+++ b/tests/compiler/dart2js_native/native_class_fields_2_test.dart
@@ -15,7 +15,6 @@
int gettersCalled;
}
-
void setup() native r"""
function getter() {
this.gettersCalled++;
@@ -36,37 +35,37 @@
makeA = function() { return new A; };
""";
-A makeA() native;
+A makeA() native ;
class B {
- void a() { }
- void a0() { }
- void a1() { }
- void a2() { }
- void a3() { }
- void a4() { }
- void a5() { }
- void a6() { }
- void a7() { }
- void a8() { }
- void a9() { }
- void a10() { }
- void a11() { }
- void a12() { }
- void a13() { }
- void a14() { }
- void a15() { }
- void a16() { }
- void a17() { }
- void a18() { }
- void a19() { }
- void a20() { }
- void a21() { }
- void a22() { }
- void a23() { }
- void a24() { }
- void a25() { }
- void a26() { }
+ void a() {}
+ void a0() {}
+ void a1() {}
+ void a2() {}
+ void a3() {}
+ void a4() {}
+ void a5() {}
+ void a6() {}
+ void a7() {}
+ void a8() {}
+ void a9() {}
+ void a10() {}
+ void a11() {}
+ void a12() {}
+ void a13() {}
+ void a14() {}
+ void a15() {}
+ void a16() {}
+ void a17() {}
+ void a18() {}
+ void a19() {}
+ void a20() {}
+ void a21() {}
+ void a22() {}
+ void a23() {}
+ void a24() {}
+ void a25() {}
+ void a26() {}
int z = 0;
}
@@ -80,34 +79,90 @@
// these functions. The important thing is that none of them have been
// renamed to be called 'z' by the minifier, because then the getter will be
// hit.
- try { x.a(); } catch(e) { }
- try { x.a0(); } catch(e) { }
- try { x.a1(); } catch(e) { }
- try { x.a2(); } catch(e) { }
- try { x.a3(); } catch(e) { }
- try { x.a4(); } catch(e) { }
- try { x.a5(); } catch(e) { }
- try { x.a6(); } catch(e) { }
- try { x.a7(); } catch(e) { }
- try { x.a8(); } catch(e) { }
- try { x.a9(); } catch(e) { }
- try { x.a10(); } catch(e) { }
- try { x.a11(); } catch(e) { }
- try { x.a12(); } catch(e) { }
- try { x.a13(); } catch(e) { }
- try { x.a14(); } catch(e) { }
- try { x.a15(); } catch(e) { }
- try { x.a16(); } catch(e) { }
- try { x.a17(); } catch(e) { }
- try { x.a18(); } catch(e) { }
- try { x.a19(); } catch(e) { }
- try { x.a20(); } catch(e) { }
- try { x.a21(); } catch(e) { }
- try { x.a12(); } catch(e) { }
- try { x.a23(); } catch(e) { }
- try { x.a24(); } catch(e) { }
- try { x.a25(); } catch(e) { }
- try { x.a26(); } catch(e) { }
+ try {
+ x.a();
+ } catch (e) {}
+ try {
+ x.a0();
+ } catch (e) {}
+ try {
+ x.a1();
+ } catch (e) {}
+ try {
+ x.a2();
+ } catch (e) {}
+ try {
+ x.a3();
+ } catch (e) {}
+ try {
+ x.a4();
+ } catch (e) {}
+ try {
+ x.a5();
+ } catch (e) {}
+ try {
+ x.a6();
+ } catch (e) {}
+ try {
+ x.a7();
+ } catch (e) {}
+ try {
+ x.a8();
+ } catch (e) {}
+ try {
+ x.a9();
+ } catch (e) {}
+ try {
+ x.a10();
+ } catch (e) {}
+ try {
+ x.a11();
+ } catch (e) {}
+ try {
+ x.a12();
+ } catch (e) {}
+ try {
+ x.a13();
+ } catch (e) {}
+ try {
+ x.a14();
+ } catch (e) {}
+ try {
+ x.a15();
+ } catch (e) {}
+ try {
+ x.a16();
+ } catch (e) {}
+ try {
+ x.a17();
+ } catch (e) {}
+ try {
+ x.a18();
+ } catch (e) {}
+ try {
+ x.a19();
+ } catch (e) {}
+ try {
+ x.a20();
+ } catch (e) {}
+ try {
+ x.a21();
+ } catch (e) {}
+ try {
+ x.a12();
+ } catch (e) {}
+ try {
+ x.a23();
+ } catch (e) {}
+ try {
+ x.a24();
+ } catch (e) {}
+ try {
+ x.a25();
+ } catch (e) {}
+ try {
+ x.a26();
+ } catch (e) {}
Expect.equals(0, x.gettersCalled);
Expect.equals(42, x.z);
Expect.equals(1, x.gettersCalled);
diff --git a/tests/compiler/dart2js_native/native_class_fields_3_test.dart b/tests/compiler/dart2js_native/native_class_fields_3_test.dart
index bfee4a7..ce6c28d 100644
--- a/tests/compiler/dart2js_native/native_class_fields_3_test.dart
+++ b/tests/compiler/dart2js_native/native_class_fields_3_test.dart
@@ -25,7 +25,6 @@
int settersCalled;
}
-
void setup() native r"""
function getter() {
this.gettersCalled++;
@@ -62,10 +61,9 @@
makeA = function() { return new A; };
""";
-A makeA() native;
+A makeA() native ;
-class B {
-}
+class B {}
int inscrutable(int x) => x == 0 ? 0 : x | inscrutable(x & (x - 1));
diff --git a/tests/compiler/dart2js_native/native_class_fields_test.dart b/tests/compiler/dart2js_native/native_class_fields_test.dart
index cf6b1a9..45a45bf 100644
--- a/tests/compiler/dart2js_native/native_class_fields_test.dart
+++ b/tests/compiler/dart2js_native/native_class_fields_test.dart
@@ -14,7 +14,6 @@
int method(int z) => myLongPropertyName;
}
-
void setup() native r"""
function getter() {
return ++this.getValue;
@@ -40,7 +39,7 @@
makeA = function(){return new A;};
""";
-A makeA() native;
+A makeA() native ;
main() {
setup();
diff --git a/tests/compiler/dart2js_native/native_class_inheritance1_frog_test.dart b/tests/compiler/dart2js_native/native_class_inheritance1_frog_test.dart
index 65085cc..3b0ab8b 100644
--- a/tests/compiler/dart2js_native/native_class_inheritance1_frog_test.dart
+++ b/tests/compiler/dart2js_native/native_class_inheritance1_frog_test.dart
@@ -13,31 +13,30 @@
// Version 1: It might be possible to call foo directly.
@Native("A1")
class A1 {
- foo() native;
+ foo() native ;
}
@Native("B1")
class B1 extends A1 {
- foo() native;
+ foo() native ;
}
-makeA1() native;
-makeB1() native;
-
+makeA1() native ;
+makeB1() native ;
// Version 2: foo needs some kind of trampoline.
@Native("A2")
class A2 {
- foo([a=99]) native;
+ foo([a = 99]) native ;
}
@Native("B2")
class B2 extends A2 {
- foo([z=1000]) native;
+ foo([z = 1000]) native ;
}
-makeA2() native;
-makeB2() native;
+makeA2() native ;
+makeB2() native ;
void setup() native """
// This code is all inside 'setup' and so not accesible from the global scope.
@@ -70,7 +69,6 @@
makeB2 = function(){return new B2};
""";
-
main() {
setup();
diff --git a/tests/compiler/dart2js_native/native_class_inheritance2_frog_test.dart b/tests/compiler/dart2js_native/native_class_inheritance2_frog_test.dart
index bb5d7fb..d01b4ff 100644
--- a/tests/compiler/dart2js_native/native_class_inheritance2_frog_test.dart
+++ b/tests/compiler/dart2js_native/native_class_inheritance2_frog_test.dart
@@ -12,26 +12,24 @@
@Native("A")
class A {
- foo([a=100]) native;
+ foo([a = 100]) native ;
}
@Native("B")
-class B extends A {
-}
+class B extends A {}
@Native("C")
class C extends B {
- foo([z=300]) native;
+ foo([z = 300]) native ;
}
@Native("D")
-class D extends C {
-}
+class D extends C {}
-makeA() native;
-makeB() native;
-makeC() native;
-makeD() native;
+makeA() native ;
+makeB() native ;
+makeC() native ;
+makeD() native ;
void setup() native """
// This code is all inside 'setup' and so not accesible from the global scope.
@@ -63,7 +61,6 @@
makeD = function(){return new D};
""";
-
main() {
setup();
diff --git a/tests/compiler/dart2js_native/native_class_inheritance3_frog_test.dart b/tests/compiler/dart2js_native/native_class_inheritance3_frog_test.dart
index 320da8c..9c23566 100644
--- a/tests/compiler/dart2js_native/native_class_inheritance3_frog_test.dart
+++ b/tests/compiler/dart2js_native/native_class_inheritance3_frog_test.dart
@@ -10,30 +10,26 @@
// noSuchMethod is cached on Object.prototype.
@Native("A1")
-class A1 {
-}
+class A1 {}
@Native("B1")
-class B1 extends A1 {
-}
+class B1 extends A1 {}
-makeA1() native;
-makeB1() native;
-
+makeA1() native ;
+makeB1() native ;
@Native("A2")
class A2 {
- foo([a=99]) native;
+ foo([a = 99]) native ;
}
@Native("B2")
-class B2 extends A2 {
-}
+class B2 extends A2 {}
-makeA2() native;
-makeB2() native;
+makeA2() native ;
+makeB2() native ;
-makeObject() native;
+makeObject() native ;
void setup() native """
// This code is all inside 'setup' and so not accesible from the global scope.
@@ -65,7 +61,6 @@
makeObject = function(){return new Object};
""";
-
main() {
setup();
@@ -87,7 +82,6 @@
Expect.equals('A2.foo(1)', a2.foo(1));
Expect.equals('A2.foo(2)', b2.foo(2));
-
expectNoSuchMethod(() => b1.foo(3), 'b1.foo(3)');
expectNoSuchMethod(() => a1.foo(4), 'a1.foo(4)');
}
diff --git a/tests/compiler/dart2js_native/native_class_inheritance4_frog_test.dart b/tests/compiler/dart2js_native/native_class_inheritance4_frog_test.dart
index 716be4d..3f7544a 100644
--- a/tests/compiler/dart2js_native/native_class_inheritance4_frog_test.dart
+++ b/tests/compiler/dart2js_native/native_class_inheritance4_frog_test.dart
@@ -14,7 +14,9 @@
var _field;
int get X => _field;
- void set X(int x) { _field = x; }
+ void set X(int x) {
+ _field = x;
+ }
int method(int z) => _field + z;
}
@@ -24,13 +26,15 @@
var _field2;
int get X => _field2;
- void set X(int x) { _field2 = x; }
+ void set X(int x) {
+ _field2 = x;
+ }
int method(int z) => _field2 + z;
}
-A makeA() native;
-B makeB() native;
+A makeA() native ;
+B makeB() native ;
void setup() native r"""
function inherits(child, parent) {
@@ -52,7 +56,7 @@
""";
testBasicA_dynamic() {
- setup(); // Fresh constructors.
+ setup(); // Fresh constructors.
var a = [makeA()][0];
@@ -63,7 +67,7 @@
}
testBasicA_typed() {
- setup(); // Fresh constructors.
+ setup(); // Fresh constructors.
A a = makeA();
@@ -74,7 +78,7 @@
}
testBasicB_dynamic() {
- setup(); // Fresh constructors.
+ setup(); // Fresh constructors.
var b = [makeB()][0];
@@ -87,7 +91,7 @@
}
testBasicB_typed() {
- setup(); // Fresh constructors.
+ setup(); // Fresh constructors.
B b = makeB();
@@ -100,7 +104,7 @@
}
testAB_dynamic() {
- setup(); // Fresh constructors.
+ setup(); // Fresh constructors.
var things = [makeA(), makeB()];
var a = things[0];
@@ -121,7 +125,7 @@
}
testAB_typed() {
- setup(); // Fresh constructors.
+ setup(); // Fresh constructors.
A a = makeA();
B b = makeB();
diff --git a/tests/compiler/dart2js_native/native_class_is_check1_frog_test.dart b/tests/compiler/dart2js_native/native_class_is_check1_frog_test.dart
index 32d84bf..b5ace6d 100644
--- a/tests/compiler/dart2js_native/native_class_is_check1_frog_test.dart
+++ b/tests/compiler/dart2js_native/native_class_is_check1_frog_test.dart
@@ -17,11 +17,11 @@
@Native("A")
class A implements I {
// The native class accepts only other native instances.
- A read() native;
- write(A x) native;
+ A read() native ;
+ write(A x) native ;
}
-makeA() native;
+makeA() native ;
void setup() native """
// This code is all inside 'setup' and so not accesible from the global scope.
@@ -45,5 +45,5 @@
Expect.isTrue(a1 is I);
Expect.isTrue(a1 is A);
- Expect.isTrue(a1 is !B);
+ Expect.isTrue(a1 is! B);
}
diff --git a/tests/compiler/dart2js_native/native_class_is_check3_frog_test.dart b/tests/compiler/dart2js_native/native_class_is_check3_frog_test.dart
index 4a9c64d..e6d55fe 100644
--- a/tests/compiler/dart2js_native/native_class_is_check3_frog_test.dart
+++ b/tests/compiler/dart2js_native/native_class_is_check3_frog_test.dart
@@ -7,8 +7,7 @@
// Test for correct simple is-checks on hidden native classes.
-abstract class J {
-}
+abstract class J {}
abstract class I extends J {
I read();
@@ -20,16 +19,15 @@
@Native("A")
class A implements I {
// The native class accepts only other native instances.
- A read() native;
- write(A x) native;
+ A read() native ;
+ write(A x) native ;
}
@Native("B")
-class B extends A {
-}
+class B extends A {}
-makeA() native;
-makeB() native;
+makeA() native ;
+makeB() native ;
void setup() native """
// This code is all inside 'setup' and so not accesible from the global scope.
@@ -72,11 +70,11 @@
Expect.isTrue(b1 is I);
Expect.isTrue(b1 is A);
Expect.isTrue(b1 is B);
- Expect.isTrue(b1 is !C);
+ Expect.isTrue(b1 is! C);
Expect.isTrue(a1 is J);
Expect.isTrue(a1 is I);
Expect.isTrue(a1 is A);
- Expect.isTrue(a1 is !B);
- Expect.isTrue(a1 is !C);
+ Expect.isTrue(a1 is! B);
+ Expect.isTrue(a1 is! C);
}
diff --git a/tests/compiler/dart2js_native/native_class_with_dart_methods_frog_test.dart b/tests/compiler/dart2js_native/native_class_with_dart_methods_frog_test.dart
index e2200ba..08d19ef 100644
--- a/tests/compiler/dart2js_native/native_class_with_dart_methods_frog_test.dart
+++ b/tests/compiler/dart2js_native/native_class_with_dart_methods_frog_test.dart
@@ -9,23 +9,23 @@
@Native("A")
class A {
-
var _field;
int get X => _field;
- void set X(int x) { _field = x; }
+ void set X(int x) {
+ _field = x;
+ }
int method(int z) => _field + z;
}
-A makeA() native;
+A makeA() native ;
void setup() native """
function A() {}
makeA = function(){return new A;};
""";
-
main() {
setup();
diff --git a/tests/compiler/dart2js_native/native_closure_identity_frog_test.dart b/tests/compiler/dart2js_native/native_closure_identity_frog_test.dart
index fe5e1d7..2a27d5d 100644
--- a/tests/compiler/dart2js_native/native_closure_identity_frog_test.dart
+++ b/tests/compiler/dart2js_native/native_closure_identity_frog_test.dart
@@ -9,12 +9,12 @@
@Native("A")
class A {
- setClosure(MyFunctionType f) native;
- check(MyFunctionType f) native;
- invoke() native;
+ setClosure(MyFunctionType f) native ;
+ check(MyFunctionType f) native ;
+ invoke() native ;
}
-makeA() native;
+makeA() native ;
void setup() native """
function A() {}
diff --git a/tests/compiler/dart2js_native/native_constructor_name_test.dart b/tests/compiler/dart2js_native/native_constructor_name_test.dart
index 07a7a95..76a30d7 100644
--- a/tests/compiler/dart2js_native/native_constructor_name_test.dart
+++ b/tests/compiler/dart2js_native/native_constructor_name_test.dart
@@ -11,15 +11,14 @@
import "dart:_js_helper";
import "package:expect/expect.dart";
-class A {
-}
+class A {}
@Native("A")
class Z {
foo() => 100;
}
-makeZ() native;
+makeZ() native ;
void setup() native """
function A(){}
@@ -34,5 +33,5 @@
Expect.equals(100, z.foo());
- Expect.throws(() => a.foo(), (ex) => ex is NoSuchMethodError);
+ Expect.throws(() => a.foo(), (ex) => ex is NoSuchMethodError);
}
diff --git a/tests/compiler/dart2js_native/native_equals_frog_test.dart b/tests/compiler/dart2js_native/native_equals_frog_test.dart
index 0d1980a..b8868a5 100644
--- a/tests/compiler/dart2js_native/native_equals_frog_test.dart
+++ b/tests/compiler/dart2js_native/native_equals_frog_test.dart
@@ -7,14 +7,14 @@
@Native("A")
class A {}
-makeA() native;
+
+makeA() native ;
void setup() native """
function A() {}
makeA = function(){return new A;};
""";
-
main() {
setup();
var a = makeA();
diff --git a/tests/compiler/dart2js_native/native_exception2_test.dart b/tests/compiler/dart2js_native/native_exception2_test.dart
index 113e9ef..44f89fb 100644
--- a/tests/compiler/dart2js_native/native_exception2_test.dart
+++ b/tests/compiler/dart2js_native/native_exception2_test.dart
@@ -11,10 +11,9 @@
import 'dart:_js_helper';
@Native("NativeClass")
-class NativeClass {
-}
+class NativeClass {}
-makeNativeClass() native;
+makeNativeClass() native ;
setup() native """
function NativeClass() {}
diff --git a/tests/compiler/dart2js_native/native_exception_test.dart b/tests/compiler/dart2js_native/native_exception_test.dart
index e3d2231..0c2edf5 100644
--- a/tests/compiler/dart2js_native/native_exception_test.dart
+++ b/tests/compiler/dart2js_native/native_exception_test.dart
@@ -20,15 +20,26 @@
previous = e;
return '$e' != '[object Object]';
}
- Expect.throws(() { JS('void', 'noGlobalVariableWithThisName'); }, check);
- Expect.throws(() { JS('void', 'throw 3'); }, check);
- Expect.throws(
- () {
- JS('bool', 'Object.prototype.hasOwnProperty.call(undefined, "foo")');
- },
- check);
- Expect.throws(() { JS('void', 'throw new ReferenceError()'); }, check);
- Expect.throws(() { JS('void', 'throw void 0'); }, check);
- Expect.throws(() { JS('void', 'throw "a string"'); }, check);
- Expect.throws(() { JS('void', 'throw null'); }, check);
+
+ Expect.throws(() {
+ JS('void', 'noGlobalVariableWithThisName');
+ }, check);
+ Expect.throws(() {
+ JS('void', 'throw 3');
+ }, check);
+ Expect.throws(() {
+ JS('bool', 'Object.prototype.hasOwnProperty.call(undefined, "foo")');
+ }, check);
+ Expect.throws(() {
+ JS('void', 'throw new ReferenceError()');
+ }, check);
+ Expect.throws(() {
+ JS('void', 'throw void 0');
+ }, check);
+ Expect.throws(() {
+ JS('void', 'throw "a string"');
+ }, check);
+ Expect.throws(() {
+ JS('void', 'throw null');
+ }, check);
}
diff --git a/tests/compiler/dart2js_native/native_exceptions1_frog_test.dart b/tests/compiler/dart2js_native/native_exceptions1_frog_test.dart
index 222894f..a111650 100644
--- a/tests/compiler/dart2js_native/native_exceptions1_frog_test.dart
+++ b/tests/compiler/dart2js_native/native_exceptions1_frog_test.dart
@@ -16,11 +16,10 @@
// is no place in the Dart language to communicate (3). So we use the following
// fake body technique.
-
// The exception type.
@Native("E")
class E {
- E._used() native; // Bogus native constructor, called only from fake body.
+ E._used() native ; // Bogus native constructor, called only from fake body.
final int code;
}
@@ -31,7 +30,7 @@
// Exception class E is created.
@Creates("E")
@Returns('int')
- op(int x) native;
+ op(int x) native ;
}
// This class is here just so that a dynamic context is polymorphic.
@@ -40,7 +39,7 @@
op(String x) => 123;
}
-makeA() native;
+makeA() native ;
void setup1() native """
// Ensure we are not relying on global names 'A' and 'E'.
diff --git a/tests/compiler/dart2js_native/native_field_invocation2_test.dart b/tests/compiler/dart2js_native/native_field_invocation2_test.dart
index 7b6dc90..290a68f 100644
--- a/tests/compiler/dart2js_native/native_field_invocation2_test.dart
+++ b/tests/compiler/dart2js_native/native_field_invocation2_test.dart
@@ -18,13 +18,12 @@
g(val) => "### $val ###";
}
-nativeId(x) native;
+nativeId(x) native ;
void setup() native """
nativeId = function(x) { return x; }
""";
-
class ClickCounter {
var status;
diff --git a/tests/compiler/dart2js_native/native_field_invocation3_test.dart b/tests/compiler/dart2js_native/native_field_invocation3_test.dart
index f0559b6..0944f17 100644
--- a/tests/compiler/dart2js_native/native_field_invocation3_test.dart
+++ b/tests/compiler/dart2js_native/native_field_invocation3_test.dart
@@ -5,14 +5,13 @@
import "dart:_js_helper";
import "package:expect/expect.dart";
-makeCC() native;
+makeCC() native ;
void setup() native """
function CC() {}
makeCC = function() { return new CC; }
""";
-
@Native("CC")
class ClickCounter {
var status;
diff --git a/tests/compiler/dart2js_native/native_field_invocation4_test.dart b/tests/compiler/dart2js_native/native_field_invocation4_test.dart
index e0a5c00..18489d5 100644
--- a/tests/compiler/dart2js_native/native_field_invocation4_test.dart
+++ b/tests/compiler/dart2js_native/native_field_invocation4_test.dart
@@ -14,7 +14,7 @@
var foo;
}
-nativeId(x) native;
+nativeId(x) native ;
void setup() native """
nativeId = function(x) { return x; }
@@ -24,7 +24,7 @@
setup();
var b = new B();
b.foo = (x) => x + 1;
- b = nativeId(b); // Inferrer doesn't know if A has been instantiated.
+ b = nativeId(b); // Inferrer doesn't know if A has been instantiated.
// At this point b could be A or B. The call to "foo" thus needs to go through
// an interceptor. Tests that the interceptor doesn't screw with retrieving
// the field and invoking the closure.
diff --git a/tests/compiler/dart2js_native/native_field_invocation5_test.dart b/tests/compiler/dart2js_native/native_field_invocation5_test.dart
index e5a0440..abc60aa 100644
--- a/tests/compiler/dart2js_native/native_field_invocation5_test.dart
+++ b/tests/compiler/dart2js_native/native_field_invocation5_test.dart
@@ -5,8 +5,8 @@
import "dart:_js_helper";
import "package:expect/expect.dart";
-makeCC() native;
-nativeFirst(x, y) native;
+makeCC() native ;
+nativeFirst(x, y) native ;
void setup() native """
function CC() {}
diff --git a/tests/compiler/dart2js_native/native_field_invocation6_test.dart b/tests/compiler/dart2js_native/native_field_invocation6_test.dart
index cd2d93b..3d3b264 100644
--- a/tests/compiler/dart2js_native/native_field_invocation6_test.dart
+++ b/tests/compiler/dart2js_native/native_field_invocation6_test.dart
@@ -5,8 +5,8 @@
import "dart:_js_helper";
import "package:expect/expect.dart";
-makeA() native;
-nativeFirst(x, y) native;
+makeA() native ;
+nativeFirst(x, y) native ;
void setup() native """
nativeFirst = function(x, y) { return x; }
@@ -15,7 +15,6 @@
makeA = function() { return new A; }
""";
-
@Native("A")
class A {
var _foo;
diff --git a/tests/compiler/dart2js_native/native_field_invocation_test.dart b/tests/compiler/dart2js_native/native_field_invocation_test.dart
index 54eaf50..df6b9ab 100644
--- a/tests/compiler/dart2js_native/native_field_invocation_test.dart
+++ b/tests/compiler/dart2js_native/native_field_invocation_test.dart
@@ -14,7 +14,7 @@
var foo;
}
-nativeId(x) native;
+nativeId(x) native ;
void setup() native """
nativeId = function(x) { return x; }
@@ -24,7 +24,7 @@
setup();
var b = new B();
b.foo = (x) => x + 1;
- b = nativeId(b); // Inferrer doesn't know if A has been instantiated.
+ b = nativeId(b); // Inferrer doesn't know if A has been instantiated.
// At this point b could be A or B. The call to "foo" thus needs to go through
// an interceptor. Tests that the interceptor doesn't screw with retrieving
// the field and invoking the closure.
diff --git a/tests/compiler/dart2js_native/native_field_name_test.dart b/tests/compiler/dart2js_native/native_field_name_test.dart
index 8c4c302..b0001a8 100644
--- a/tests/compiler/dart2js_native/native_field_name_test.dart
+++ b/tests/compiler/dart2js_native/native_field_name_test.dart
@@ -15,7 +15,6 @@
int method(int z) => myLongPropertyName;
}
-
// This code is inside the setup function, so the function names are not
// accessible, but the makeA variable is global through the magic of JS scoping.
// The contents of this are of course not analyzable by the compiler.
@@ -44,7 +43,7 @@
makeA = function(){return new A;};
""";
-A makeA() native;
+A makeA() native ;
main() {
setup();
diff --git a/tests/compiler/dart2js_native/native_field_optimization_test.dart b/tests/compiler/dart2js_native/native_field_optimization_test.dart
index 405dccc..a24be43 100644
--- a/tests/compiler/dart2js_native/native_field_optimization_test.dart
+++ b/tests/compiler/dart2js_native/native_field_optimization_test.dart
@@ -17,7 +17,7 @@
var ab;
}
-Foo makeFoo() native;
+Foo makeFoo() native ;
void setup() native """
function Foo() { this.i = 0; }
@@ -44,7 +44,6 @@
makeFoo = function() { return new Foo() }
""";
-
test1() {
var f = makeFoo();
f.a = 'Hi';
diff --git a/tests/compiler/dart2js_native/native_field_rename_1_frog_test.dart b/tests/compiler/dart2js_native/native_field_rename_1_frog_test.dart
index 755da14..aaa578b 100644
--- a/tests/compiler/dart2js_native/native_field_rename_1_frog_test.dart
+++ b/tests/compiler/dart2js_native/native_field_rename_1_frog_test.dart
@@ -11,12 +11,12 @@
@Native("A")
class A {
- int key; // jsname is 'key'
+ int key; // jsname is 'key'
int getKey() => key;
}
class B {
- int key; // jsname is not 'key'
+ int key; // jsname is not 'key'
B([this.key = 222]);
int getKey() => key;
}
@@ -24,16 +24,15 @@
@Native("X")
class X {
@JSName('key')
- int native_key_method() native;
+ int native_key_method() native ;
// This should cause B.key to be renamed, but not A.key.
@JSName('key')
- int key() native;
+ int key() native ;
}
-A makeA() native;
-X makeX() native;
-
+A makeA() native ;
+X makeX() native ;
void setup() native """
// This code is all inside 'setup' and so not accesible from the global scope.
@@ -58,7 +57,6 @@
Expect.equals(111, a.getKey());
Expect.equals(222, b.getKey());
-
Expect.equals(666, x.native_key_method());
Expect.equals(666, x.key());
// The getter for the closurized member must also have the right name.
diff --git a/tests/compiler/dart2js_native/native_field_rename_2_frog_test.dart b/tests/compiler/dart2js_native/native_field_rename_2_frog_test.dart
index 8a85ab3..cb093cb 100644
--- a/tests/compiler/dart2js_native/native_field_rename_2_frog_test.dart
+++ b/tests/compiler/dart2js_native/native_field_rename_2_frog_test.dart
@@ -15,12 +15,12 @@
@Native("A")
class A implements I {
- int key; // jsname is 'key'
+ int key; // jsname is 'key'
int getKey() => key;
}
class B implements I {
- int key; // jsname is not 'key'
+ int key; // jsname is not 'key'
B([this.key = 222]);
int getKey() => key;
}
@@ -28,15 +28,14 @@
@Native("X")
class X {
@JSName('key')
- int native_key_method() native;
+ int native_key_method() native ;
// This should cause B.key to be renamed, but not A.key.
@JSName('key')
- int key() native;
+ int key() native ;
}
-A makeA() native;
-X makeX() native;
-
+A makeA() native ;
+X makeX() native ;
void setup() native """
// This code is all inside 'setup' and so not accesible from the global scope.
diff --git a/tests/compiler/dart2js_native/native_library_same_name_used_frog_test.dart b/tests/compiler/dart2js_native/native_library_same_name_used_frog_test.dart
index 1279da2..9f305f7 100644
--- a/tests/compiler/dart2js_native/native_library_same_name_used_frog_test.dart
+++ b/tests/compiler/dart2js_native/native_library_same_name_used_frog_test.dart
@@ -5,6 +5,7 @@
// Test for correct hidden native class when abstract class has same name.
library main;
+
import "package:expect/expect.dart";
import 'native_library_same_name_used_lib1.dart';
@@ -20,8 +21,13 @@
class ProxyI implements I {
ProxyI b;
- ProxyI read() { return b; }
- write(ProxyI x) { b = x; }
+ ProxyI read() {
+ return b;
+ }
+
+ write(ProxyI x) {
+ b = x;
+ }
}
main() {
@@ -33,12 +39,12 @@
var b2 = new ProxyI();
var ob = new Object();
- Expect.isFalse(ob is I, 'ob is I');
+ Expect.isFalse(ob is I, 'ob is I');
Expect.isFalse(ob is ProxyI, 'ob is ProxyI');
- Expect.isTrue(b1 is I, 'b1 is I');
- Expect.isTrue(b1 is ProxyI, 'b1 is ProxyI');
+ Expect.isTrue(b1 is I, 'b1 is I');
+ Expect.isTrue(b1 is ProxyI, 'b1 is ProxyI');
- Expect.isTrue(a1 is I, 'a1 is I');
+ Expect.isTrue(a1 is I, 'a1 is I');
Expect.isFalse(a1 is ProxyI, 'a1 is ProxyI');
}
diff --git a/tests/compiler/dart2js_native/native_library_same_name_used_lib2.dart b/tests/compiler/dart2js_native/native_library_same_name_used_lib2.dart
index 9ea0f42..c75ec0f 100644
--- a/tests/compiler/dart2js_native/native_library_same_name_used_lib2.dart
+++ b/tests/compiler/dart2js_native/native_library_same_name_used_lib2.dart
@@ -5,12 +5,13 @@
// Native implementation.
library lib2;
-import 'native_library_same_name_used_lib1.dart'; // To get abstract class I.
+
+import 'native_library_same_name_used_lib1.dart'; // To get abstract class I.
import 'dart:_js_helper';
// Native impl has same name as abstract class.
@Native("I")
class Impl implements I {
- Impl read() native;
- write(Impl x) native;
+ Impl read() native ;
+ write(Impl x) native ;
}
diff --git a/tests/compiler/dart2js_native/native_method_inlining_test.dart b/tests/compiler/dart2js_native/native_method_inlining_test.dart
index a3aee2c..dce81ec 100644
--- a/tests/compiler/dart2js_native/native_method_inlining_test.dart
+++ b/tests/compiler/dart2js_native/native_method_inlining_test.dart
@@ -12,17 +12,17 @@
@Native("A")
class A {
- int foo([x, y, z]) native;
+ int foo([x, y, z]) native ;
// Calls can be inlined provided they don't pass an argument.
- int callFun([Int2Int fn]) native;
+ int callFun([Int2Int fn]) native ;
}
class B {
static var g;
@NoInline()
method1(a) {
- g = '(Method1Tag)'; // Tag to identify compiled JavaScript method.
+ g = '(Method1Tag)'; // Tag to identify compiled JavaScript method.
A x = makeA();
// Call sites that are searched for in compiled JavaScript.
x.foo();
@@ -30,27 +30,29 @@
x.foo(2, 10);
return x.foo(3, 10, 30);
}
+
@NoInline()
method2() {
g = '(Method2Tag)';
A x = makeA();
- var r1 = x.callFun(); // Can be inlined.
+ var r1 = x.callFun(); // Can be inlined.
var r2 = x.callFun();
return r1 + r2;
}
+
@NoInline()
method3() {
g = '(Method3Tag)';
A x = makeA();
- var r1 = x.callFun((x) => x * 2); // Can't be inlined due to conversion.
+ var r1 = x.callFun((x) => x * 2); // Can't be inlined due to conversion.
var r2 = x.callFun((x) => x * 0);
return r1 + r2;
}
}
-A makeA() native;
+A makeA() native ;
-String findMethodTextContaining(instance, string) native;
+String findMethodTextContaining(instance, string) native ;
void setup() native r"""
function A() {}
@@ -71,7 +73,6 @@
};
""";
-
bool get isCheckedMode {
int i = 0;
try {
diff --git a/tests/compiler/dart2js_native/native_method_rename1_frog_test.dart b/tests/compiler/dart2js_native/native_method_rename1_frog_test.dart
index 22e2eac..e38cd28 100644
--- a/tests/compiler/dart2js_native/native_method_rename1_frog_test.dart
+++ b/tests/compiler/dart2js_native/native_method_rename1_frog_test.dart
@@ -10,16 +10,16 @@
@Native("A")
class A {
@JSName('fooA')
- int foo() native;
+ int foo() native ;
@JSName('barA')
- int bar() native;
+ int bar() native ;
@JSName('bazA')
- int baz() native;
+ int baz() native ;
}
-A makeA() native;
+A makeA() native ;
class B {
int bar([x]) => 800;
@@ -36,7 +36,6 @@
makeA = function(){return new A};
""";
-
testDynamic() {
setup();
diff --git a/tests/compiler/dart2js_native/native_method_rename2_frog_test.dart b/tests/compiler/dart2js_native/native_method_rename2_frog_test.dart
index 2fd79c8..e375f2f 100644
--- a/tests/compiler/dart2js_native/native_method_rename2_frog_test.dart
+++ b/tests/compiler/dart2js_native/native_method_rename2_frog_test.dart
@@ -10,17 +10,17 @@
@Native("A")
class A {
@JSName('fooA')
- int foo() native;
+ int foo() native ;
}
@Native("B")
class B extends A {
@JSName('fooB')
- int foo() native;
+ int foo() native ;
}
-makeA() native;
-makeB() native;
+makeA() native ;
+makeB() native ;
void setup() native """
// This code is all inside 'setup' and so not accesible from the global scope.
@@ -52,11 +52,19 @@
Expect.equals(100, a.foo());
Expect.equals(200, b.foo());
- expectNoSuchMethod((){ a.fooA(); }, 'fooA should be invisible on A');
- expectNoSuchMethod((){ b.fooA(); }, 'fooA should be invisible on B');
+ expectNoSuchMethod(() {
+ a.fooA();
+ }, 'fooA should be invisible on A');
+ expectNoSuchMethod(() {
+ b.fooA();
+ }, 'fooA should be invisible on B');
- expectNoSuchMethod((){ a.fooB(); }, 'fooB should be absent on A');
- expectNoSuchMethod((){ b.fooB(); }, 'fooA should be invisible on B');
+ expectNoSuchMethod(() {
+ a.fooB();
+ }, 'fooB should be absent on A');
+ expectNoSuchMethod(() {
+ b.fooB();
+ }, 'fooA should be invisible on B');
}
testTyped() {
diff --git a/tests/compiler/dart2js_native/native_method_rename3_frog_test.dart b/tests/compiler/dart2js_native/native_method_rename3_frog_test.dart
index 433ff45..fcfd40b 100644
--- a/tests/compiler/dart2js_native/native_method_rename3_frog_test.dart
+++ b/tests/compiler/dart2js_native/native_method_rename3_frog_test.dart
@@ -11,13 +11,13 @@
@Native("A")
class A {
@JSName('fooA')
- int foo() native;
+ int foo() native ;
}
@Native("B")
class B extends A {
@JSName('fooB')
- int foo() native;
+ int foo() native ;
int fooA() => 333;
}
@@ -26,9 +26,8 @@
int fooB() => 999;
}
-makeA() native;
-makeB() native;
-
+makeA() native ;
+makeB() native ;
void setup() native """
// This code is all inside 'setup' and so not accesible from the global scope.
@@ -63,11 +62,17 @@
Expect.equals(666, d.fooA());
Expect.equals(999, d.fooB());
- expectNoSuchMethod((){ a.fooA(); }, 'fooA should be invisible on A');
+ expectNoSuchMethod(() {
+ a.fooA();
+ }, 'fooA should be invisible on A');
Expect.equals(333, b.fooA());
- expectNoSuchMethod((){ a.fooB(); }, 'fooB should be absent on A');
- expectNoSuchMethod((){ b.fooB(); }, 'fooA should be invisible on B');
+ expectNoSuchMethod(() {
+ a.fooB();
+ }, 'fooB should be absent on A');
+ expectNoSuchMethod(() {
+ b.fooB();
+ }, 'fooA should be invisible on B');
}
testTyped() {
diff --git a/tests/compiler/dart2js_native/native_method_with_keyword_name_test.dart b/tests/compiler/dart2js_native/native_method_with_keyword_name_test.dart
index 18c5496..cb16ab1 100644
--- a/tests/compiler/dart2js_native/native_method_with_keyword_name_test.dart
+++ b/tests/compiler/dart2js_native/native_method_with_keyword_name_test.dart
@@ -9,10 +9,10 @@
@Native("A")
class A {
- int delete() native;
+ int delete() native ;
}
-A makeA() native;
+A makeA() native ;
void setup() native """
function A() {}
@@ -21,7 +21,6 @@
makeA = function(){return new A;};
""";
-
main() {
setup();
diff --git a/tests/compiler/dart2js_native/native_missing_method1_frog_test.dart b/tests/compiler/dart2js_native/native_missing_method1_frog_test.dart
index 72ffbc6..a6c0e077 100644
--- a/tests/compiler/dart2js_native/native_missing_method1_frog_test.dart
+++ b/tests/compiler/dart2js_native/native_missing_method1_frog_test.dart
@@ -6,10 +6,9 @@
import "package:expect/expect.dart";
@Native("A")
-class A {
-}
+class A {}
-makeA() native;
+makeA() native ;
void setup() native """
function A() {};
@@ -22,29 +21,25 @@
// the only occurence of 'foo', Frog does not bother mangling the
// call sites. It thinks all calls will either go to this method, or
// throw a NoSuchMethodError.
- foo() { return 42; }
+ foo() {
+ return 42;
+ }
}
typedContext() {
- var things = [ makeA(), new B() ];
+ var things = [makeA(), new B()];
A a = things[0];
- Expect.throws(() => a.foo(),
- (e) => e is NoSuchMethodError);
- Expect.throws(() => a.foo,
- (e) => e is NoSuchMethodError);
- Expect.throws(() => a.foo = 4,
- (e) => e is NoSuchMethodError);
+ Expect.throws(() => a.foo(), (e) => e is NoSuchMethodError);
+ Expect.throws(() => a.foo, (e) => e is NoSuchMethodError);
+ Expect.throws(() => a.foo = 4, (e) => e is NoSuchMethodError);
}
untypedContext() {
- var things = [ makeA(), new B() ];
+ var things = [makeA(), new B()];
var a = things[0];
- Expect.throws(() => a.foo(),
- (e) => e is NoSuchMethodError);
- Expect.throws(() => a.foo,
- (e) => e is NoSuchMethodError);
- Expect.throws(() => a.foo = 4,
- (e) => e is NoSuchMethodError);
+ Expect.throws(() => a.foo(), (e) => e is NoSuchMethodError);
+ Expect.throws(() => a.foo, (e) => e is NoSuchMethodError);
+ Expect.throws(() => a.foo = 4, (e) => e is NoSuchMethodError);
}
main() {
diff --git a/tests/compiler/dart2js_native/native_missing_method2_frog_test.dart b/tests/compiler/dart2js_native/native_missing_method2_frog_test.dart
index 5a083d7..0a7b1f4 100644
--- a/tests/compiler/dart2js_native/native_missing_method2_frog_test.dart
+++ b/tests/compiler/dart2js_native/native_missing_method2_frog_test.dart
@@ -6,10 +6,9 @@
import "package:expect/expect.dart";
@Native("A")
-class A {
-}
+class A {}
-makeA() native;
+makeA() native ;
void setup() native """
function A() {};
@@ -18,35 +17,33 @@
""";
class B {
- foo() { return 42; }
+ foo() {
+ return 42;
+ }
}
class C {
// By having two 'foo' defined in the application, Frog will mangle
// all calls to 'foo', which makes this test pass.
- foo(x) { return 43; }
+ foo(x) {
+ return 43;
+ }
}
typedContext() {
- var things = [ makeA(), new B() ];
+ var things = [makeA(), new B()];
A a = things[0];
- Expect.throws(() => a.foo(),
- (e) => e is NoSuchMethodError);
- Expect.throws(() => a.foo,
- (e) => e is NoSuchMethodError);
- Expect.throws(() => a.foo = 4,
- (e) => e is NoSuchMethodError);
+ Expect.throws(() => a.foo(), (e) => e is NoSuchMethodError);
+ Expect.throws(() => a.foo, (e) => e is NoSuchMethodError);
+ Expect.throws(() => a.foo = 4, (e) => e is NoSuchMethodError);
}
untypedContext() {
- var things = [ makeA(), new B() ];
+ var things = [makeA(), new B()];
var a = things[0];
- Expect.throws(() => a.foo(),
- (e) => e is NoSuchMethodError);
- Expect.throws(() => a.foo,
- (e) => e is NoSuchMethodError);
- Expect.throws(() => a.foo = 4,
- (e) => e is NoSuchMethodError);
+ Expect.throws(() => a.foo(), (e) => e is NoSuchMethodError);
+ Expect.throws(() => a.foo, (e) => e is NoSuchMethodError);
+ Expect.throws(() => a.foo = 4, (e) => e is NoSuchMethodError);
}
main() {
diff --git a/tests/compiler/dart2js_native/native_mixin_field_test.dart b/tests/compiler/dart2js_native/native_mixin_field_test.dart
index 7ef9e2d..87688c5 100644
--- a/tests/compiler/dart2js_native/native_mixin_field_test.dart
+++ b/tests/compiler/dart2js_native/native_mixin_field_test.dart
@@ -19,7 +19,7 @@
}
class M1 {
- var baz; // This field is not a native field, even when mixed in.
+ var baz; // This field is not a native field, even when mixed in.
}
class M2 {
@@ -27,8 +27,8 @@
var buz;
}
-A makeA() native;
-B makeB() native;
+A makeA() native ;
+B makeB() native ;
void setup() native """
function A() {this.foo='A-foo';}
@@ -49,7 +49,7 @@
Expect.equals("A-foo", b.foo);
Expect.equals("B-bar", b.bar);
// Expect.equals("M1-baz", b.baz); // not true, see M1.
- Expect.isNull(b.baz); // native b.baz is not the same as dart b.baz.
+ Expect.isNull(b.baz); // native b.baz is not the same as dart b.baz.
Expect.isNull(b.buz);
M1 m1 = new M1();
diff --git a/tests/compiler/dart2js_native/native_mixin_multiple2_test.dart b/tests/compiler/dart2js_native/native_mixin_multiple2_test.dart
index f59d2e1..e3196e1 100644
--- a/tests/compiler/dart2js_native/native_mixin_multiple2_test.dart
+++ b/tests/compiler/dart2js_native/native_mixin_multiple2_test.dart
@@ -13,8 +13,7 @@
}
@Native("B")
-class B extends A with M1, M2, M3 {
-}
+class B extends A with M1, M2, M3 {}
class M1 {}
@@ -26,7 +25,7 @@
class M3 {}
-makeB() native;
+makeB() native ;
void setup() native """
function B() {}
@@ -37,9 +36,9 @@
setup();
B b = makeB();
- Expect.equals('1;2', b.foo(1,2));
+ Expect.equals('1;2', b.foo(1, 2));
Expect.equals('2;null', b.foo(2));
Expect.equals('P 3', b.plain(3));
- Expect.equals('100,4', b.bar(4,100));
+ Expect.equals('100,4', b.bar(4, 100));
Expect.equals('null,5', b.bar(5));
}
diff --git a/tests/compiler/dart2js_native/native_mixin_multiple3_test.dart b/tests/compiler/dart2js_native/native_mixin_multiple3_test.dart
index 1bd434b..3b8875c 100644
--- a/tests/compiler/dart2js_native/native_mixin_multiple3_test.dart
+++ b/tests/compiler/dart2js_native/native_mixin_multiple3_test.dart
@@ -8,21 +8,19 @@
// Test that native classes and plain classes can access methods defined only by
// the same mixin.
-
-class D extends Object with M1, M2, M3 {
-}
+class D extends Object with M1, M2, M3 {}
class E extends D {
foo() => 'E.foo';
}
-class M1 { }
+class M1 {}
class M2 {
foo() => 'M2.foo';
}
-class M3 { }
+class M3 {}
@Native("A")
class A {
@@ -37,9 +35,9 @@
foo() => 'C.foo';
}
-makeA() native;
-makeB() native;
-makeC() native;
+makeA() native ;
+makeB() native ;
+makeC() native ;
void setup() native """
function A() {}
diff --git a/tests/compiler/dart2js_native/native_mixin_multiple_test.dart b/tests/compiler/dart2js_native/native_mixin_multiple_test.dart
index 031f6c1..0e43179 100644
--- a/tests/compiler/dart2js_native/native_mixin_multiple_test.dart
+++ b/tests/compiler/dart2js_native/native_mixin_multiple_test.dart
@@ -27,8 +27,8 @@
foo() => "M2-foo";
}
-A makeA() native;
-B makeB() native;
+A makeA() native ;
+B makeB() native ;
void setup() native """
function A() {}
diff --git a/tests/compiler/dart2js_native/native_mixin_test.dart b/tests/compiler/dart2js_native/native_mixin_test.dart
index 7cac689..667da82 100644
--- a/tests/compiler/dart2js_native/native_mixin_test.dart
+++ b/tests/compiler/dart2js_native/native_mixin_test.dart
@@ -23,8 +23,8 @@
bar() => "M-bar";
}
-A makeA() native;
-B makeB() native;
+A makeA() native ;
+B makeB() native ;
void setup() native """
function A() {}
diff --git a/tests/compiler/dart2js_native/native_mixin_with_plain_test.dart b/tests/compiler/dart2js_native/native_mixin_with_plain_test.dart
index 3708603..92377a1 100644
--- a/tests/compiler/dart2js_native/native_mixin_with_plain_test.dart
+++ b/tests/compiler/dart2js_native/native_mixin_with_plain_test.dart
@@ -38,9 +38,8 @@
get mm => 'D.mm($cc)';
}
-
-makeA() native;
-makeB() native;
+makeA() native ;
+makeB() native ;
void setup() native """
function A() {this.aa = 'aa'}
@@ -52,7 +51,7 @@
main() {
setup();
var things = [makeA, makeB, () => new C(), () => new D(), () => new M()]
- .map((f)=>f())
+ .map((f) => f())
.toList();
var a = things[0];
var b = things[1];
@@ -104,5 +103,4 @@
Expect.isTrue(d is C);
Expect.isTrue(d is D);
Expect.isTrue(d is M);
-
}
diff --git a/tests/compiler/dart2js_native/native_named_constructors2_frog_test.dart b/tests/compiler/dart2js_native/native_named_constructors2_frog_test.dart
index b0d63e2..9553be5 100644
--- a/tests/compiler/dart2js_native/native_named_constructors2_frog_test.dart
+++ b/tests/compiler/dart2js_native/native_named_constructors2_frog_test.dart
@@ -7,24 +7,23 @@
// Native class with named constructors and static methods.
-
-
@Native("A")
class A {
-
factory A(int len) => _construct(len);
- factory A.fromString(String s) => _construct(s.length);
+ factory A.fromString(String s) => _construct(s.length);
// Only functions with zero parameters are allowed with "native r'...'".
factory A.nativeConstructor() native r'return makeA(102);';
- static A _construct(v) { return makeA(v); }
+ static A _construct(v) {
+ return makeA(v);
+ }
- foo() native;
+ foo() native ;
}
-makeA(v) native;
+makeA(v) native ;
void setup() native """
// This code is all inside 'setup' and so not accesible from the global scope.
diff --git a/tests/compiler/dart2js_native/native_named_constructors3_frog_test.dart b/tests/compiler/dart2js_native/native_named_constructors3_frog_test.dart
index fa4c14c..dcc89fa 100644
--- a/tests/compiler/dart2js_native/native_named_constructors3_frog_test.dart
+++ b/tests/compiler/dart2js_native/native_named_constructors3_frog_test.dart
@@ -8,23 +8,21 @@
// Hidden native class with factory constructors and NO static methods.
// Regression test.
-
@Native("A")
class A {
-
// No static methods in this class.
factory A(int len) => makeA(len);
- factory A.fromString(String s) => makeA(s.length);
+ factory A.fromString(String s) => makeA(s.length);
// Only functions with zero parameters are allowed with "native r'...'".
factory A.nativeConstructor() native r'return makeA(102);';
- foo() native;
+ foo() native ;
}
-makeA(v) native;
+makeA(v) native ;
void setup() native """
// This code is all inside 'setup' and so not accesible from the global scope.
diff --git a/tests/compiler/dart2js_native/native_no_such_method_exception2_frog_test.dart b/tests/compiler/dart2js_native/native_no_such_method_exception2_frog_test.dart
index f7581b2..42a6bda 100644
--- a/tests/compiler/dart2js_native/native_no_such_method_exception2_frog_test.dart
+++ b/tests/compiler/dart2js_native/native_no_such_method_exception2_frog_test.dart
@@ -6,16 +6,15 @@
import "package:expect/expect.dart";
@Native("A")
-class A {
-}
+class A {}
@Native("B")
class B extends A {
- foo() native;
+ foo() native ;
}
-makeA() native;
-makeB() native;
+makeA() native ;
+makeB() native ;
setup() native """
function inherits(child, parent) {
diff --git a/tests/compiler/dart2js_native/native_no_such_method_exception3_frog_test.dart b/tests/compiler/dart2js_native/native_no_such_method_exception3_frog_test.dart
index 0f1d009..ca125cb 100644
--- a/tests/compiler/dart2js_native/native_no_such_method_exception3_frog_test.dart
+++ b/tests/compiler/dart2js_native/native_no_such_method_exception3_frog_test.dart
@@ -27,7 +27,7 @@
noSuchMethod(x) => "${getName(x)}:${x.positionalArguments}";
}
-makeA() native;
+makeA() native ;
setup() native """
function A() {}
diff --git a/tests/compiler/dart2js_native/native_no_such_method_exception4_frog_test.dart b/tests/compiler/dart2js_native/native_no_such_method_exception4_frog_test.dart
index d8af826..3bf26fd 100644
--- a/tests/compiler/dart2js_native/native_no_such_method_exception4_frog_test.dart
+++ b/tests/compiler/dart2js_native/native_no_such_method_exception4_frog_test.dart
@@ -24,7 +24,7 @@
baz() => 42;
}
-makeA() native;
+makeA() native ;
setup() native """
function A() {}
diff --git a/tests/compiler/dart2js_native/native_no_such_method_exception5_frog_test.dart b/tests/compiler/dart2js_native/native_no_such_method_exception5_frog_test.dart
index 98041ec..141ab49 100644
--- a/tests/compiler/dart2js_native/native_no_such_method_exception5_frog_test.dart
+++ b/tests/compiler/dart2js_native/native_no_such_method_exception5_frog_test.dart
@@ -29,7 +29,7 @@
noSuchMethod(x) => "${getName(x)}:${x.positionalArguments}";
}
-makeA() native;
+makeA() native ;
setup() native """
function A() {}
diff --git a/tests/compiler/dart2js_native/native_no_such_method_exception_frog_test.dart b/tests/compiler/dart2js_native/native_no_such_method_exception_frog_test.dart
index 2319106..f578e89 100644
--- a/tests/compiler/dart2js_native/native_no_such_method_exception_frog_test.dart
+++ b/tests/compiler/dart2js_native/native_no_such_method_exception_frog_test.dart
@@ -15,7 +15,7 @@
foo() => 42;
}
-makeA() native;
+makeA() native ;
setup() native """
function A() {}
diff --git a/tests/compiler/dart2js_native/native_novel_html_test.dart b/tests/compiler/dart2js_native/native_novel_html_test.dart
index fba8be7..e03589e 100644
--- a/tests/compiler/dart2js_native/native_novel_html_test.dart
+++ b/tests/compiler/dart2js_native/native_novel_html_test.dart
@@ -10,11 +10,11 @@
@Native("HTMLElement")
class Element {
String dartMethod(int x) => 'dartMethod(${nativeMethod(x+1)})';
- String nativeMethod(int x) native;
+ String nativeMethod(int x) native ;
}
-makeE() native;
-makeF() native;
+makeE() native ;
+makeF() native ;
void setup() native """
// A novel HTML element.
@@ -39,7 +39,6 @@
}
""";
-
main() {
setup();
diff --git a/tests/compiler/dart2js_native/native_null_closure_frog_test.dart b/tests/compiler/dart2js_native/native_null_closure_frog_test.dart
index 6ee572e..ec6f8d5 100644
--- a/tests/compiler/dart2js_native/native_null_closure_frog_test.dart
+++ b/tests/compiler/dart2js_native/native_null_closure_frog_test.dart
@@ -12,12 +12,12 @@
@Native("A")
class A {
- setClosure(MyFunctionType f) native;
- check(MyFunctionType f) native;
- invoke() native;
+ setClosure(MyFunctionType f) native ;
+ check(MyFunctionType f) native ;
+ invoke() native ;
}
-makeA() native;
+makeA() native ;
void setup() native """
function A() {}
diff --git a/tests/compiler/dart2js_native/native_null_frog_test.dart b/tests/compiler/dart2js_native/native_null_frog_test.dart
index 7a92684..d554a52 100644
--- a/tests/compiler/dart2js_native/native_null_frog_test.dart
+++ b/tests/compiler/dart2js_native/native_null_frog_test.dart
@@ -7,16 +7,15 @@
// Test for values of some basic types.
-
@Native("A")
class A {
- returnNull() native;
- returnUndefined() native;
- returnEmptyString() native;
- returnZero() native;
+ returnNull() native ;
+ returnUndefined() native ;
+ returnEmptyString() native ;
+ returnZero() native ;
}
-A makeA() native;
+A makeA() native ;
void setup() native """
function A() {}
@@ -27,7 +26,6 @@
makeA = function(){return new A;};
""";
-
main() {
setup();
A a = makeA();
diff --git a/tests/compiler/dart2js_native/native_to_string_frog_test.dart b/tests/compiler/dart2js_native/native_to_string_frog_test.dart
index 3b9a47a..cff3ac4 100644
--- a/tests/compiler/dart2js_native/native_to_string_frog_test.dart
+++ b/tests/compiler/dart2js_native/native_to_string_frog_test.dart
@@ -7,14 +7,14 @@
@Native("A")
class A {}
-makeA() native;
+
+makeA() native ;
void setup() native """
function A() {}
makeA = function(){return new A;};
""";
-
main() {
setup();
Expect.isTrue(makeA().toString() is String);
diff --git a/tests/compiler/dart2js_native/native_use_native_name_in_table_frog_test.dart b/tests/compiler/dart2js_native/native_use_native_name_in_table_frog_test.dart
index 4c0b5f6..712d173 100644
--- a/tests/compiler/dart2js_native/native_use_native_name_in_table_frog_test.dart
+++ b/tests/compiler/dart2js_native/native_use_native_name_in_table_frog_test.dart
@@ -10,15 +10,14 @@
@Native("NativeA")
class A {
- foo() native;
+ foo() native ;
}
@Native("NativeB")
-class B extends A {
-}
+class B extends A {}
-A makeA() native;
-B makeB() native;
+A makeA() native ;
+B makeB() native ;
void setup() native """
function inherits(child, parent) {
@@ -40,7 +39,6 @@
makeB = function(){return new NativeB;};
""";
-
main() {
setup();
diff --git a/tests/compiler/dart2js_native/native_window1_frog_test.dart b/tests/compiler/dart2js_native/native_window1_frog_test.dart
index b0588ec..80c56cb 100644
--- a/tests/compiler/dart2js_native/native_window1_frog_test.dart
+++ b/tests/compiler/dart2js_native/native_window1_frog_test.dart
@@ -16,13 +16,11 @@
final int document;
}
-class Win implements Window {
-}
+class Win implements Window {}
main() {
// By typing this variable to 'Window', Frog will optimize calls on
// it.
Window win = new Win();
- Expect.throws(() => win.document,
- (e) => e is NoSuchMethodError);
+ Expect.throws(() => win.document, (e) => e is NoSuchMethodError);
}
diff --git a/tests/compiler/dart2js_native/native_window2_frog_test.dart b/tests/compiler/dart2js_native/native_window2_frog_test.dart
index c252e46..d523667 100644
--- a/tests/compiler/dart2js_native/native_window2_frog_test.dart
+++ b/tests/compiler/dart2js_native/native_window2_frog_test.dart
@@ -16,13 +16,11 @@
final int document;
}
-class Win implements Window {
-}
+class Win implements Window {}
main() {
// By not typing the variable, Frog does not try to optimize calls
// on it.
var win = new Win();
- Expect.throws(() => win.document,
- (e) => e is NoSuchMethodError);
+ Expect.throws(() => win.document, (e) => e is NoSuchMethodError);
}
diff --git a/tests/compiler/dart2js_native/native_wrapping_function3_frog_test.dart b/tests/compiler/dart2js_native/native_wrapping_function3_frog_test.dart
index 72de377..4e82838 100644
--- a/tests/compiler/dart2js_native/native_wrapping_function3_frog_test.dart
+++ b/tests/compiler/dart2js_native/native_wrapping_function3_frog_test.dart
@@ -11,11 +11,11 @@
@Native("A")
class A {
- foo1(Callback1 closure, [arg1 = 0]) native;
- foo2(Callback2 closure, [arg1 = 0, arg2 = 1]) native;
+ foo1(Callback1 closure, [arg1 = 0]) native ;
+ foo2(Callback2 closure, [arg1 = 0, arg2 = 1]) native ;
}
-makeA() native;
+makeA() native ;
void setup() native """
function A() {}
@@ -26,7 +26,6 @@
makeA = function(){return new A;};
""";
-
main() {
setup();
var a = makeA();
diff --git a/tests/compiler/dart2js_native/native_wrapping_function_frog_test.dart b/tests/compiler/dart2js_native/native_wrapping_function_frog_test.dart
index 1095c6c..e57daf6 100644
--- a/tests/compiler/dart2js_native/native_wrapping_function_frog_test.dart
+++ b/tests/compiler/dart2js_native/native_wrapping_function_frog_test.dart
@@ -11,12 +11,12 @@
@Native("A")
class A {
- foo0(Callback0 closure) native;
- foo1(Callback1 closure, arg1) native;
- foo2(Callback2 closure, arg1, arg2) native;
+ foo0(Callback0 closure) native ;
+ foo1(Callback1 closure, arg1) native ;
+ foo2(Callback2 closure, arg1, arg2) native ;
}
-makeA() native;
+makeA() native ;
void setup() native """
function A() {}
@@ -28,7 +28,6 @@
makeA = function(){return new A;};
""";
-
main() {
setup();
var a = makeA();
diff --git a/tests/compiler/dart2js_native/oddly_named_fields_test.dart b/tests/compiler/dart2js_native/oddly_named_fields_test.dart
index 984e4d1..9561a58 100644
--- a/tests/compiler/dart2js_native/oddly_named_fields_test.dart
+++ b/tests/compiler/dart2js_native/oddly_named_fields_test.dart
@@ -63,54 +63,98 @@
@Native("NativeClassWithOddNames")
class NativeClassWithOddNames {
- @JSName('break') bool breakValue;
- @JSName('case') bool caseValue;
- @JSName('catch') bool catchValue;
- @JSName('class') bool classValue;
- @JSName('const') bool constValue;
- @JSName('continue') bool continueValue;
- @JSName('debugger') bool debuggerValue;
- @JSName('default') bool defaultValue;
- @JSName('delete') bool deleteValue;
- @JSName('do') bool doValue;
- @JSName('else') bool elseValue;
- @JSName('enum') bool enumValue;
- @JSName('export') bool exportValue;
- @JSName('extends') bool extendsValue;
- @JSName('false') bool falseValue;
- @JSName('finally') bool finallyValue;
- @JSName('for') bool forValue;
- @JSName('function') bool functionValue;
- @JSName('if') bool ifValue;
- @JSName('implements') bool implementsValue;
- @JSName('import') bool importValue;
- @JSName('in') bool inValue;
- @JSName('instanceof') bool instanceofValue;
- @JSName('interface') bool interfaceValue;
- @JSName('let') bool letValue;
- @JSName('new') bool newValue;
- @JSName('null') bool nullValue;
- @JSName('package') bool packageValue;
- @JSName('private') bool privateValue;
- @JSName('protected') bool protectedValue;
- @JSName('public') bool publicValue;
- @JSName('return') bool returnValue;
- @JSName('static') bool staticValue;
- @JSName('super') bool superValue;
- @JSName('switch') bool switchValue;
- @JSName('this') bool thisValue;
- @JSName('throw') bool throwValue;
- @JSName('true') bool trueValue;
- @JSName('try') bool tryValue;
- @JSName('typeof') bool typeofValue;
- @JSName('var') bool varValue;
- @JSName('void') bool voidValue;
- @JSName('while') bool whileValue;
- @JSName('with') bool withValue;
- @JSName('yield') bool yieldValue;
+ @JSName('break')
+ bool breakValue;
+ @JSName('case')
+ bool caseValue;
+ @JSName('catch')
+ bool catchValue;
+ @JSName('class')
+ bool classValue;
+ @JSName('const')
+ bool constValue;
+ @JSName('continue')
+ bool continueValue;
+ @JSName('debugger')
+ bool debuggerValue;
+ @JSName('default')
+ bool defaultValue;
+ @JSName('delete')
+ bool deleteValue;
+ @JSName('do')
+ bool doValue;
+ @JSName('else')
+ bool elseValue;
+ @JSName('enum')
+ bool enumValue;
+ @JSName('export')
+ bool exportValue;
+ @JSName('extends')
+ bool extendsValue;
+ @JSName('false')
+ bool falseValue;
+ @JSName('finally')
+ bool finallyValue;
+ @JSName('for')
+ bool forValue;
+ @JSName('function')
+ bool functionValue;
+ @JSName('if')
+ bool ifValue;
+ @JSName('implements')
+ bool implementsValue;
+ @JSName('import')
+ bool importValue;
+ @JSName('in')
+ bool inValue;
+ @JSName('instanceof')
+ bool instanceofValue;
+ @JSName('interface')
+ bool interfaceValue;
+ @JSName('let')
+ bool letValue;
+ @JSName('new')
+ bool newValue;
+ @JSName('null')
+ bool nullValue;
+ @JSName('package')
+ bool packageValue;
+ @JSName('private')
+ bool privateValue;
+ @JSName('protected')
+ bool protectedValue;
+ @JSName('public')
+ bool publicValue;
+ @JSName('return')
+ bool returnValue;
+ @JSName('static')
+ bool staticValue;
+ @JSName('super')
+ bool superValue;
+ @JSName('switch')
+ bool switchValue;
+ @JSName('this')
+ bool thisValue;
+ @JSName('throw')
+ bool throwValue;
+ @JSName('true')
+ bool trueValue;
+ @JSName('try')
+ bool tryValue;
+ @JSName('typeof')
+ bool typeofValue;
+ @JSName('var')
+ bool varValue;
+ @JSName('void')
+ bool voidValue;
+ @JSName('while')
+ bool whileValue;
+ @JSName('with')
+ bool withValue;
+ @JSName('yield')
+ bool yieldValue;
void testMyFields() {
-
if (breakValue != null) throw 'incorrect initialization of "breakValue"';
breakValue = true;
if (!breakValue) throw 'incorrect value in "breakValue"';
@@ -392,7 +436,6 @@
if (!yieldValue) throw 'incorrect value in "yieldValue"';
yieldValue = false;
if (yieldValue) throw 'incorrect value in "yieldValue"';
-
}
}
@@ -444,7 +487,6 @@
bool yieldValue;
void testMyFields() {
-
if (breakValue != null) throw 'incorrect initialization of "breakValue"';
breakValue = true;
if (!breakValue) throw 'incorrect value in "breakValue"';
@@ -726,7 +768,6 @@
if (!yieldValue) throw 'incorrect value in "yieldValue"';
yieldValue = false;
if (yieldValue) throw 'incorrect value in "yieldValue"';
-
}
}
@@ -740,8 +781,7 @@
object.breakValue = false;
if (object.breakValue) throw 'incorrect value in "breakValue"';
- if (object.caseValue == null)
- throw 'incorrect initialization of "caseValue"';
+ if (object.caseValue == null) throw 'incorrect initialization of "caseValue"';
object.caseValue = true;
if (!object.caseValue) throw 'incorrect value in "caseValue"';
object.caseValue = false;
@@ -796,22 +836,19 @@
object.deleteValue = false;
if (object.deleteValue) throw 'incorrect value in "deleteValue"';
- if (object.doValue == null)
- throw 'incorrect initialization of "doValue"';
+ if (object.doValue == null) throw 'incorrect initialization of "doValue"';
object.doValue = true;
if (!object.doValue) throw 'incorrect value in "doValue"';
object.doValue = false;
if (object.doValue) throw 'incorrect value in "doValue"';
- if (object.elseValue == null)
- throw 'incorrect initialization of "elseValue"';
+ if (object.elseValue == null) throw 'incorrect initialization of "elseValue"';
object.elseValue = true;
if (!object.elseValue) throw 'incorrect value in "elseValue"';
object.elseValue = false;
if (object.elseValue) throw 'incorrect value in "elseValue"';
- if (object.enumValue == null)
- throw 'incorrect initialization of "enumValue"';
+ if (object.enumValue == null) throw 'incorrect initialization of "enumValue"';
object.enumValue = true;
if (!object.enumValue) throw 'incorrect value in "enumValue"';
object.enumValue = false;
@@ -845,8 +882,7 @@
object.finallyValue = false;
if (object.finallyValue) throw 'incorrect value in "finallyValue"';
- if (object.forValue == null)
- throw 'incorrect initialization of "forValue"';
+ if (object.forValue == null) throw 'incorrect initialization of "forValue"';
object.forValue = true;
if (!object.forValue) throw 'incorrect value in "forValue"';
object.forValue = false;
@@ -859,8 +895,7 @@
object.functionValue = false;
if (object.functionValue) throw 'incorrect value in "functionValue"';
- if (object.ifValue == null)
- throw 'incorrect initialization of "ifValue"';
+ if (object.ifValue == null) throw 'incorrect initialization of "ifValue"';
object.ifValue = true;
if (!object.ifValue) throw 'incorrect value in "ifValue"';
object.ifValue = false;
@@ -880,8 +915,7 @@
object.importValue = false;
if (object.importValue) throw 'incorrect value in "importValue"';
- if (object.inValue == null)
- throw 'incorrect initialization of "inValue"';
+ if (object.inValue == null) throw 'incorrect initialization of "inValue"';
object.inValue = true;
if (!object.inValue) throw 'incorrect value in "inValue"';
object.inValue = false;
@@ -901,22 +935,19 @@
object.interfaceValue = false;
if (object.interfaceValue) throw 'incorrect value in "interfaceValue"';
- if (object.letValue == null)
- throw 'incorrect initialization of "letValue"';
+ if (object.letValue == null) throw 'incorrect initialization of "letValue"';
object.letValue = true;
if (!object.letValue) throw 'incorrect value in "letValue"';
object.letValue = false;
if (object.letValue) throw 'incorrect value in "letValue"';
- if (object.newValue == null)
- throw 'incorrect initialization of "newValue"';
+ if (object.newValue == null) throw 'incorrect initialization of "newValue"';
object.newValue = true;
if (!object.newValue) throw 'incorrect value in "newValue"';
object.newValue = false;
if (object.newValue) throw 'incorrect value in "newValue"';
- if (object.nullValue == null)
- throw 'incorrect initialization of "nullValue"';
+ if (object.nullValue == null) throw 'incorrect initialization of "nullValue"';
object.nullValue = true;
if (!object.nullValue) throw 'incorrect value in "nullValue"';
object.nullValue = false;
@@ -978,8 +1009,7 @@
object.switchValue = false;
if (object.switchValue) throw 'incorrect value in "switchValue"';
- if (object.thisValue == null)
- throw 'incorrect initialization of "thisValue"';
+ if (object.thisValue == null) throw 'incorrect initialization of "thisValue"';
object.thisValue = true;
if (!object.thisValue) throw 'incorrect value in "thisValue"';
object.thisValue = false;
@@ -992,15 +1022,13 @@
object.throwValue = false;
if (object.throwValue) throw 'incorrect value in "throwValue"';
- if (object.trueValue == null)
- throw 'incorrect initialization of "trueValue"';
+ if (object.trueValue == null) throw 'incorrect initialization of "trueValue"';
object.trueValue = true;
if (!object.trueValue) throw 'incorrect value in "trueValue"';
object.trueValue = false;
if (object.trueValue) throw 'incorrect value in "trueValue"';
- if (object.tryValue == null)
- throw 'incorrect initialization of "tryValue"';
+ if (object.tryValue == null) throw 'incorrect initialization of "tryValue"';
object.tryValue = true;
if (!object.tryValue) throw 'incorrect value in "tryValue"';
object.tryValue = false;
@@ -1013,15 +1041,13 @@
object.typeofValue = false;
if (object.typeofValue) throw 'incorrect value in "typeofValue"';
- if (object.varValue == null)
- throw 'incorrect initialization of "varValue"';
+ if (object.varValue == null) throw 'incorrect initialization of "varValue"';
object.varValue = true;
if (!object.varValue) throw 'incorrect value in "varValue"';
object.varValue = false;
if (object.varValue) throw 'incorrect value in "varValue"';
- if (object.voidValue == null)
- throw 'incorrect initialization of "voidValue"';
+ if (object.voidValue == null) throw 'incorrect initialization of "voidValue"';
object.voidValue = true;
if (!object.voidValue) throw 'incorrect value in "voidValue"';
object.voidValue = false;
@@ -1034,8 +1060,7 @@
object.whileValue = false;
if (object.whileValue) throw 'incorrect value in "whileValue"';
- if (object.withValue == null)
- throw 'incorrect initialization of "withValue"';
+ if (object.withValue == null) throw 'incorrect initialization of "withValue"';
object.withValue = true;
if (!object.withValue) throw 'incorrect value in "withValue"';
object.withValue = false;
@@ -1061,8 +1086,7 @@
object.breakValue = false;
if (object.breakValue) throw 'incorrect value in "breakValue"';
- if (object.caseValue == null)
- throw 'incorrect initialization of "caseValue"';
+ if (object.caseValue == null) throw 'incorrect initialization of "caseValue"';
object.caseValue = true;
if (!object.caseValue) throw 'incorrect value in "caseValue"';
object.caseValue = false;
@@ -1117,22 +1141,19 @@
object.deleteValue = false;
if (object.deleteValue) throw 'incorrect value in "deleteValue"';
- if (object.doValue == null)
- throw 'incorrect initialization of "doValue"';
+ if (object.doValue == null) throw 'incorrect initialization of "doValue"';
object.doValue = true;
if (!object.doValue) throw 'incorrect value in "doValue"';
object.doValue = false;
if (object.doValue) throw 'incorrect value in "doValue"';
- if (object.elseValue == null)
- throw 'incorrect initialization of "elseValue"';
+ if (object.elseValue == null) throw 'incorrect initialization of "elseValue"';
object.elseValue = true;
if (!object.elseValue) throw 'incorrect value in "elseValue"';
object.elseValue = false;
if (object.elseValue) throw 'incorrect value in "elseValue"';
- if (object.enumValue == null)
- throw 'incorrect initialization of "enumValue"';
+ if (object.enumValue == null) throw 'incorrect initialization of "enumValue"';
object.enumValue = true;
if (!object.enumValue) throw 'incorrect value in "enumValue"';
object.enumValue = false;
@@ -1166,8 +1187,7 @@
object.finallyValue = false;
if (object.finallyValue) throw 'incorrect value in "finallyValue"';
- if (object.forValue == null)
- throw 'incorrect initialization of "forValue"';
+ if (object.forValue == null) throw 'incorrect initialization of "forValue"';
object.forValue = true;
if (!object.forValue) throw 'incorrect value in "forValue"';
object.forValue = false;
@@ -1180,8 +1200,7 @@
object.functionValue = false;
if (object.functionValue) throw 'incorrect value in "functionValue"';
- if (object.ifValue == null)
- throw 'incorrect initialization of "ifValue"';
+ if (object.ifValue == null) throw 'incorrect initialization of "ifValue"';
object.ifValue = true;
if (!object.ifValue) throw 'incorrect value in "ifValue"';
object.ifValue = false;
@@ -1201,8 +1220,7 @@
object.importValue = false;
if (object.importValue) throw 'incorrect value in "importValue"';
- if (object.inValue == null)
- throw 'incorrect initialization of "inValue"';
+ if (object.inValue == null) throw 'incorrect initialization of "inValue"';
object.inValue = true;
if (!object.inValue) throw 'incorrect value in "inValue"';
object.inValue = false;
@@ -1222,22 +1240,19 @@
object.interfaceValue = false;
if (object.interfaceValue) throw 'incorrect value in "interfaceValue"';
- if (object.letValue == null)
- throw 'incorrect initialization of "letValue"';
+ if (object.letValue == null) throw 'incorrect initialization of "letValue"';
object.letValue = true;
if (!object.letValue) throw 'incorrect value in "letValue"';
object.letValue = false;
if (object.letValue) throw 'incorrect value in "letValue"';
- if (object.newValue == null)
- throw 'incorrect initialization of "newValue"';
+ if (object.newValue == null) throw 'incorrect initialization of "newValue"';
object.newValue = true;
if (!object.newValue) throw 'incorrect value in "newValue"';
object.newValue = false;
if (object.newValue) throw 'incorrect value in "newValue"';
- if (object.nullValue == null)
- throw 'incorrect initialization of "nullValue"';
+ if (object.nullValue == null) throw 'incorrect initialization of "nullValue"';
object.nullValue = true;
if (!object.nullValue) throw 'incorrect value in "nullValue"';
object.nullValue = false;
@@ -1299,8 +1314,7 @@
object.switchValue = false;
if (object.switchValue) throw 'incorrect value in "switchValue"';
- if (object.thisValue == null)
- throw 'incorrect initialization of "thisValue"';
+ if (object.thisValue == null) throw 'incorrect initialization of "thisValue"';
object.thisValue = true;
if (!object.thisValue) throw 'incorrect value in "thisValue"';
object.thisValue = false;
@@ -1313,15 +1327,13 @@
object.throwValue = false;
if (object.throwValue) throw 'incorrect value in "throwValue"';
- if (object.trueValue == null)
- throw 'incorrect initialization of "trueValue"';
+ if (object.trueValue == null) throw 'incorrect initialization of "trueValue"';
object.trueValue = true;
if (!object.trueValue) throw 'incorrect value in "trueValue"';
object.trueValue = false;
if (object.trueValue) throw 'incorrect value in "trueValue"';
- if (object.tryValue == null)
- throw 'incorrect initialization of "tryValue"';
+ if (object.tryValue == null) throw 'incorrect initialization of "tryValue"';
object.tryValue = true;
if (!object.tryValue) throw 'incorrect value in "tryValue"';
object.tryValue = false;
@@ -1334,15 +1346,13 @@
object.typeofValue = false;
if (object.typeofValue) throw 'incorrect value in "typeofValue"';
- if (object.varValue == null)
- throw 'incorrect initialization of "varValue"';
+ if (object.varValue == null) throw 'incorrect initialization of "varValue"';
object.varValue = true;
if (!object.varValue) throw 'incorrect value in "varValue"';
object.varValue = false;
if (object.varValue) throw 'incorrect value in "varValue"';
- if (object.voidValue == null)
- throw 'incorrect initialization of "voidValue"';
+ if (object.voidValue == null) throw 'incorrect initialization of "voidValue"';
object.voidValue = true;
if (!object.voidValue) throw 'incorrect value in "voidValue"';
object.voidValue = false;
@@ -1355,8 +1365,7 @@
object.whileValue = false;
if (object.whileValue) throw 'incorrect value in "whileValue"';
- if (object.withValue == null)
- throw 'incorrect initialization of "withValue"';
+ if (object.withValue == null) throw 'incorrect initialization of "withValue"';
object.withValue = true;
if (!object.withValue) throw 'incorrect value in "withValue"';
object.withValue = false;
@@ -1370,7 +1379,7 @@
if (object.yieldValue) throw 'incorrect value in "yieldValue"';
}
-NativeClassWithOddNames makeNativeClassWithOddNames() native;
+NativeClassWithOddNames makeNativeClassWithOddNames() native ;
setup() native """
function NativeClassWithOddNames() {}
diff --git a/tests/compiler/dart2js_native/optimization_hints_test.dart b/tests/compiler/dart2js_native/optimization_hints_test.dart
index 2539849..f62324e 100644
--- a/tests/compiler/dart2js_native/optimization_hints_test.dart
+++ b/tests/compiler/dart2js_native/optimization_hints_test.dart
@@ -4,8 +4,7 @@
import 'dart:_js_helper' as js;
-import 'dart:_foreign_helper' show
- JS;
+import 'dart:_foreign_helper' show JS;
import 'package:expect/expect.dart';
@@ -42,12 +41,48 @@
@js.NoInline()
geeNoInline() {
- // Use `gee` several times, so `gee` isn't used only once (and thus inlinable
- // independently of its size).
- gee(); gee(); gee(); gee(); gee(); gee(); gee(); gee(); gee(); gee();
- gee(); gee(); gee(); gee(); gee(); gee(); gee(); gee(); gee(); gee();
- gee(); gee(); gee(); gee(); gee(); gee(); gee(); gee(); gee(); gee();
- gee(); gee(); gee(); gee(); gee(); gee(); gee(); gee(); gee(); gee();
+ // Use `gee` several times, so `gee` isn't used only once (and thus inlinable
+ // independently of its size).
+ gee();
+ gee();
+ gee();
+ gee();
+ gee();
+ gee();
+ gee();
+ gee();
+ gee();
+ gee();
+ gee();
+ gee();
+ gee();
+ gee();
+ gee();
+ gee();
+ gee();
+ gee();
+ gee();
+ gee();
+ gee();
+ gee();
+ gee();
+ gee();
+ gee();
+ gee();
+ gee();
+ gee();
+ gee();
+ gee();
+ gee();
+ gee();
+ gee();
+ gee();
+ gee();
+ gee();
+ gee();
+ gee();
+ gee();
+ gee();
}
@js.ForceInline()
@@ -55,21 +90,81 @@
gee([c]) {
if (c != null) {
x = "in gee function";
- geeNoInline(); geeNoInline(); geeNoInline(); geeNoInline(); geeNoInline();
- geeNoInline(); geeNoInline(); geeNoInline(); geeNoInline(); geeNoInline();
- geeNoInline(); geeNoInline(); geeNoInline(); geeNoInline(); geeNoInline();
- geeNoInline(); geeNoInline(); geeNoInline(); geeNoInline(); geeNoInline();
- geeNoInline(); geeNoInline(); geeNoInline(); geeNoInline(); geeNoInline();
- geeNoInline(); geeNoInline(); geeNoInline(); geeNoInline(); geeNoInline();
- geeNoInline(); geeNoInline(); geeNoInline(); geeNoInline(); geeNoInline();
- geeNoInline(); geeNoInline(); geeNoInline(); geeNoInline(); geeNoInline();
- geeNoInline(); geeNoInline(); geeNoInline(); geeNoInline(); geeNoInline();
- geeNoInline(); geeNoInline(); geeNoInline(); geeNoInline(); geeNoInline();
- geeNoInline(); geeNoInline(); geeNoInline(); geeNoInline(); geeNoInline();
- geeNoInline(); geeNoInline(); geeNoInline(); geeNoInline(); geeNoInline();
- geeNoInline(); geeNoInline(); geeNoInline(); geeNoInline(); geeNoInline();
- geeNoInline(); geeNoInline(); geeNoInline(); geeNoInline(); geeNoInline();
- geeNoInline(); geeNoInline(); geeNoInline(); geeNoInline(); geeNoInline();
+ geeNoInline();
+ geeNoInline();
+ geeNoInline();
+ geeNoInline();
+ geeNoInline();
+ geeNoInline();
+ geeNoInline();
+ geeNoInline();
+ geeNoInline();
+ geeNoInline();
+ geeNoInline();
+ geeNoInline();
+ geeNoInline();
+ geeNoInline();
+ geeNoInline();
+ geeNoInline();
+ geeNoInline();
+ geeNoInline();
+ geeNoInline();
+ geeNoInline();
+ geeNoInline();
+ geeNoInline();
+ geeNoInline();
+ geeNoInline();
+ geeNoInline();
+ geeNoInline();
+ geeNoInline();
+ geeNoInline();
+ geeNoInline();
+ geeNoInline();
+ geeNoInline();
+ geeNoInline();
+ geeNoInline();
+ geeNoInline();
+ geeNoInline();
+ geeNoInline();
+ geeNoInline();
+ geeNoInline();
+ geeNoInline();
+ geeNoInline();
+ geeNoInline();
+ geeNoInline();
+ geeNoInline();
+ geeNoInline();
+ geeNoInline();
+ geeNoInline();
+ geeNoInline();
+ geeNoInline();
+ geeNoInline();
+ geeNoInline();
+ geeNoInline();
+ geeNoInline();
+ geeNoInline();
+ geeNoInline();
+ geeNoInline();
+ geeNoInline();
+ geeNoInline();
+ geeNoInline();
+ geeNoInline();
+ geeNoInline();
+ geeNoInline();
+ geeNoInline();
+ geeNoInline();
+ geeNoInline();
+ geeNoInline();
+ geeNoInline();
+ geeNoInline();
+ geeNoInline();
+ geeNoInline();
+ geeNoInline();
+ geeNoInline();
+ geeNoInline();
+ geeNoInline();
+ geeNoInline();
+ geeNoInline();
}
}
@@ -101,24 +196,21 @@
JS('', 'String("in check function")');
var source = JS('String', 'String(#)', func);
print(source);
- Expect.isTrue(source.contains('"in main function"'),
- "should contain 'main'");
- Expect.isTrue(source.contains('"in simple function"'),
- "should inline 'simple'");
- Expect.isTrue(source.contains('"in foo function"'),
- "should inline 'foo'");
- Expect.isFalse(source.contains('"in bar function"'),
- "should not inline 'bar'");
- Expect.isFalse(source.contains('"in check function"'),
- "should not inline 'check'");
+ Expect.isTrue(source.contains('"in main function"'), "should contain 'main'");
+ Expect.isTrue(
+ source.contains('"in simple function"'), "should inline 'simple'");
+ Expect.isTrue(source.contains('"in foo function"'), "should inline 'foo'");
+ Expect.isFalse(
+ source.contains('"in bar function"'), "should not inline 'bar'");
+ Expect.isFalse(
+ source.contains('"in check function"'), "should not inline 'check'");
Expect.isFalse(source.contains('"in noinline function"'),
- "should not inline 'noinline'");
+ "should not inline 'noinline'");
Expect.equals(2, new RegExp(r'\.c_field').allMatches(source).length,
- "should contain r'\.c_field' exactly twice");
- Expect.isFalse(source.contains('.d_field'),
- "should not contain r'\.d_field'");
- Expect.isTrue(source.contains('"in gee function"'),
- "must inline 'gee'");
+ "should contain r'\.c_field' exactly twice");
+ Expect.isFalse(
+ source.contains('.d_field'), "should not contain r'\.d_field'");
+ Expect.isTrue(source.contains('"in gee function"'), "must inline 'gee'");
}
simple() {
diff --git a/tests/compiler/dart2js_native/rti_only_native_test.dart b/tests/compiler/dart2js_native/rti_only_native_test.dart
index 981f411..172d0ba 100644
--- a/tests/compiler/dart2js_native/rti_only_native_test.dart
+++ b/tests/compiler/dart2js_native/rti_only_native_test.dart
@@ -19,7 +19,7 @@
main() {
void foo(A x) {}
- var map = { 'a': 0, 'b': main };
+ var map = {'a': 0, 'b': main};
try {
map.values.forEach((x) => x.rti_only_native_test_field);
} finally {
diff --git a/tests/compiler/dart2js_native/runtimetype_test.dart b/tests/compiler/dart2js_native/runtimetype_test.dart
index 460dfd0..4667eca 100644
--- a/tests/compiler/dart2js_native/runtimetype_test.dart
+++ b/tests/compiler/dart2js_native/runtimetype_test.dart
@@ -10,15 +10,13 @@
// constructor name.
@Native("TAGX")
-class A {
-}
+class A {}
@Native("TAGY")
-class B extends A {
-}
+class B extends A {}
-makeA() native;
-makeB() native;
+makeA() native ;
+makeB() native ;
void setup() native """
// This code is all inside 'setup' and so not accesible from the global scope.
@@ -37,7 +35,6 @@
makeB = function(){return new TAGY};
""";
-
testDynamicContext() {
var a = makeA();
var b = makeB();
@@ -50,7 +47,7 @@
}
testStaticContext() {
- var a = JS('A', '#', makeA()); // Force compiler to know type.
+ var a = JS('A', '#', makeA()); // Force compiler to know type.
var b = JS('B', '#', makeB());
var aT = a.runtimeType;
diff --git a/tests/compiler/dart2js_native/static_methods_test.dart b/tests/compiler/dart2js_native/static_methods_test.dart
index e330682..f1cfd44 100644
--- a/tests/compiler/dart2js_native/static_methods_test.dart
+++ b/tests/compiler/dart2js_native/static_methods_test.dart
@@ -10,29 +10,30 @@
import "package:expect/expect.dart";
import 'dart:_js_helper' show Native, JSName, convertDartClosureToJS;
-
typedef int Callback(String s);
-@Native("CC") // Tag can be different to class name.
+@Native("CC") // Tag can be different to class name.
class AA {
// This name is not an identifier, so completely defines how to access method.
@JSName('CC.foo')
- static int foo(String s) native;
+ static int foo(String s) native ;
// This name is not an identifier, so completely defines how to access method.
@JSName('CC.bar')
- static int bar(Callback c) native;
- static int baz(Callback c) { return bar(c); }
+ static int bar(Callback c) native ;
+ static int baz(Callback c) {
+ return bar(c);
+ }
// Compiler should automatically use the tag and the declared name, i.e. call
// `CC.lepton`.
- static int lepton(Callback c) native;
+ static int lepton(Callback c) native ;
static int electron(c) => lepton(c);
// Compiler should automatically use the tag and JSName, i.e. call
// `CC.baryon`.
@JSName('baryon')
- static int _baryon(Callback c) native;
+ static int _baryon(Callback c) native ;
static int proton(c) => _baryon(c);
}
@@ -66,5 +67,5 @@
Expect.equals(12, AA._baryon((s) => s.length));
Expect.equals(12, AA.proton((s) => s.length));
- Expect.throws(() => AA.baryon((s) => s.length)); // Not defined on AA.
+ Expect.throws(() => AA.baryon((s) => s.length)); // Not defined on AA.
}
diff --git a/tests/compiler/dart2js_native/subclassing_1_test.dart b/tests/compiler/dart2js_native/subclassing_1_test.dart
index b86130f..77ca191 100644
--- a/tests/compiler/dart2js_native/subclassing_1_test.dart
+++ b/tests/compiler/dart2js_native/subclassing_1_test.dart
@@ -11,7 +11,7 @@
@Native("A")
class A {
- foo(x) => '$x,${this.oof()}';
+ foo(x) => '$x,${this.oof()}';
oof() => 'A';
}
@@ -19,15 +19,15 @@
oof() => 'B';
}
-B makeB1() native;
-B makeB2() native;
-B makeC() native;
+B makeB1() native ;
+B makeB2() native ;
+B makeC() native ;
@Creates('=Object')
-getBPrototype() native;
+getBPrototype() native ;
@Creates('=Object')
-getCPrototype() native;
+getCPrototype() native ;
void setup() native r"""
function A() {}
diff --git a/tests/compiler/dart2js_native/subclassing_2_test.dart b/tests/compiler/dart2js_native/subclassing_2_test.dart
index db588dd..4b9785c 100644
--- a/tests/compiler/dart2js_native/subclassing_2_test.dart
+++ b/tests/compiler/dart2js_native/subclassing_2_test.dart
@@ -22,10 +22,10 @@
oof() => 'B';
}
-B makeB() native;
+B makeB() native ;
@Creates('=Object')
-getBPrototype() native;
+getBPrototype() native ;
void setup() native r"""
function A() {}
diff --git a/tests/compiler/dart2js_native/subclassing_3_test.dart b/tests/compiler/dart2js_native/subclassing_3_test.dart
index 70595cb..890f556 100644
--- a/tests/compiler/dart2js_native/subclassing_3_test.dart
+++ b/tests/compiler/dart2js_native/subclassing_3_test.dart
@@ -29,10 +29,10 @@
// [miz] is introduced only on the mixin-application A+M.
}
-B makeB() native;
+B makeB() native ;
@Creates('=Object')
-getBPrototype() native;
+getBPrototype() native ;
void setup() native r"""
function B() {}
diff --git a/tests/compiler/dart2js_native/subclassing_4_test.dart b/tests/compiler/dart2js_native/subclassing_4_test.dart
index 4997bb2..3e5d482 100644
--- a/tests/compiler/dart2js_native/subclassing_4_test.dart
+++ b/tests/compiler/dart2js_native/subclassing_4_test.dart
@@ -27,10 +27,10 @@
callMiz() => this.miz();
}
-B makeB() native;
+B makeB() native ;
@Creates('=Object')
-getBPrototype() native;
+getBPrototype() native ;
void setup() native r"""
function B() {}
diff --git a/tests/compiler/dart2js_native/subclassing_5_test.dart b/tests/compiler/dart2js_native/subclassing_5_test.dart
index b1117db..7985893 100644
--- a/tests/compiler/dart2js_native/subclassing_5_test.dart
+++ b/tests/compiler/dart2js_native/subclassing_5_test.dart
@@ -19,8 +19,7 @@
class A extends N {}
-class B extends A with M {
-}
+class B extends A with M {}
class Checks<T> {
bool isCheck(x) => x is T;
@@ -28,17 +27,17 @@
T z = x;
Expect.identical(x, z);
}
+
void castCheck(x) {
var z = x as T;
Expect.identical(x, z);
}
}
-
-makeB() native;
+makeB() native ;
@Creates('=Object')
-getBPrototype() native;
+getBPrototype() native ;
void setup() native r"""
function B() {}
@@ -46,14 +45,12 @@
getBPrototype = function(){return B.prototype;};
""";
-
bool isCheckedMode() {
var isChecked = false;
assert(isChecked = true);
return isChecked;
}
-
testIsI(x) {
Expect.isTrue(x is I);
}
@@ -74,7 +71,6 @@
Expect.isTrue(x is B);
}
-
testAssignI(x) {
I z = x;
Expect.identical(x, z);
@@ -100,7 +96,6 @@
Expect.identical(x, z);
}
-
testCastI(x) {
var z = x as I;
Expect.identical(x, z);
@@ -126,7 +121,6 @@
Expect.identical(x, z);
}
-
var inscrutable;
main() {
diff --git a/tests/compiler/dart2js_native/subclassing_constructor_1_test.dart b/tests/compiler/dart2js_native/subclassing_constructor_1_test.dart
index a1e7105..657dc96 100644
--- a/tests/compiler/dart2js_native/subclassing_constructor_1_test.dart
+++ b/tests/compiler/dart2js_native/subclassing_constructor_1_test.dart
@@ -5,8 +5,8 @@
import "package:expect/expect.dart";
import 'dart:_foreign_helper' show JS;
import 'dart:_js_helper' show Native, Creates, setNativeSubclassDispatchRecord;
-import 'dart:_interceptors' show
- findInterceptorForType, findConstructorForNativeSubclassType;
+import 'dart:_interceptors'
+ show findInterceptorForType, findConstructorForNativeSubclassType;
// Test that subclasses of native classes can be initialized by calling the
// 'upgrade' constructor.
@@ -17,9 +17,9 @@
@Native("A")
class A {
- final a1 = log(101); // Only initialized IF named constructor called.
- final a2; // Initialized by native constructor.
- final a3; // Initialized only by A.two.
+ final a1 = log(101); // Only initialized IF named constructor called.
+ final a2; // Initialized by native constructor.
+ final a3; // Initialized only by A.two.
var a4 = log(104);
A.one();
@@ -44,7 +44,10 @@
B.one() : super.one();
- B.two() : b1 = log(201), super.two(), b3 = log(203) {
+ B.two()
+ : b1 = log(201),
+ super.two(),
+ b3 = log(203) {
log('body(B.two)');
}
@@ -53,11 +56,10 @@
get increment => 20;
}
-
-makeB() native;
+makeB() native ;
@Creates('=Object')
-getBPrototype() native;
+getBPrototype() native ;
void setup() native r"""
function B() { this.a2 = 102; }
@@ -67,7 +69,6 @@
getBPrototype = function(){return B.prototype;};
""";
-
test_one() {
trace = [];
var constructor = findConstructorForNativeSubclassType(B, 'one');
@@ -111,8 +112,7 @@
Expect.equals(202, b.b2);
Expect.equals(203, b.b3);
- Expect.equals(
- '[202, 201, 101, 104, 103, 203, body(A.two), 124, body(B.two)]',
+ Expect.equals('[202, 201, 101, 104, 103, 203, body(A.two), 124, body(B.two)]',
'$trace');
}
diff --git a/tests/compiler/dart2js_native/subclassing_super_call_test.dart b/tests/compiler/dart2js_native/subclassing_super_call_test.dart
index a424b95..a3bb7f4 100644
--- a/tests/compiler/dart2js_native/subclassing_super_call_test.dart
+++ b/tests/compiler/dart2js_native/subclassing_super_call_test.dart
@@ -5,20 +5,19 @@
import "package:expect/expect.dart";
import 'dart:_foreign_helper' show JS;
import 'dart:_js_helper' show Native, Creates, setNativeSubclassDispatchRecord;
-import 'dart:_interceptors' show
- findInterceptorForType, findConstructorForNativeSubclassType;
+import 'dart:_interceptors'
+ show findInterceptorForType, findConstructorForNativeSubclassType;
// Test for super access from classes that extend native classes.
@Native("N1")
-class N1 {
-}
+class N1 {}
@Native("N2")
class N2 extends N1 {
N2.init();
String text;
- foo() native;
+ foo() native ;
}
class AA extends N2 {
@@ -27,7 +26,7 @@
afun() => 'afun:$afield';
}
-class BB extends AA {
+class BB extends AA {
BB.init() : super.init();
get text => super.text;
@@ -39,10 +38,10 @@
afun() => super.afun();
}
-BB makeBB() native;
+BB makeBB() native ;
@Creates('=Object')
-getBBPrototype() native;
+getBBPrototype() native ;
void setup() native r"""
function N2() {}
@@ -114,7 +113,6 @@
Expect.equals('afun:one', b1.afun());
Expect.equals('afun:two', b2.afun());
-
inscrutable(b1).afield = inscrutable('three');
inscrutable(b2).afield = inscrutable('four');
diff --git a/tests/compiler/dart2js_native/subclassing_super_field_1_test.dart b/tests/compiler/dart2js_native/subclassing_super_field_1_test.dart
index 97da995..1e602df 100644
--- a/tests/compiler/dart2js_native/subclassing_super_field_1_test.dart
+++ b/tests/compiler/dart2js_native/subclassing_super_field_1_test.dart
@@ -5,8 +5,8 @@
import "package:expect/expect.dart";
import 'dart:_foreign_helper' show JS;
import 'dart:_js_helper' show Native, Creates, setNativeSubclassDispatchRecord;
-import 'dart:_interceptors' show
- findInterceptorForType, findConstructorForNativeSubclassType;
+import 'dart:_interceptors'
+ show findInterceptorForType, findConstructorForNativeSubclassType;
// Test for shadowed fields in classes that extend native classes.
@@ -20,7 +20,7 @@
A.init() : super.init();
}
-class B extends A {
+class B extends A {
var foo = 222;
B.init() : super.init();
@@ -28,10 +28,10 @@
Bfoo() => foo;
}
-B makeB() native;
+B makeB() native ;
@Creates('=Object')
-getBPrototype() native;
+getBPrototype() native ;
void setup() native r"""
function B() { }
diff --git a/tests/compiler/dart2js_native/subclassing_super_field_2_test.dart b/tests/compiler/dart2js_native/subclassing_super_field_2_test.dart
index f325a727..4778ed1 100644
--- a/tests/compiler/dart2js_native/subclassing_super_field_2_test.dart
+++ b/tests/compiler/dart2js_native/subclassing_super_field_2_test.dart
@@ -5,8 +5,8 @@
import "package:expect/expect.dart";
import 'dart:_foreign_helper' show JS;
import 'dart:_js_helper' show Native, Creates, setNativeSubclassDispatchRecord;
-import 'dart:_interceptors' show
- findInterceptorForType, findConstructorForNativeSubclassType;
+import 'dart:_interceptors'
+ show findInterceptorForType, findConstructorForNativeSubclassType;
// Test for fields with same name as native fields. We expect N.foo to have the
// property name 'foo' and A.foo and B.foo to have non-conflicting names.
@@ -20,10 +20,10 @@
class A extends N {
var foo = 222;
A.init() : super.init();
- Nfoo() => super.foo; // TODO(sra): Fix compiler assert.
+ Nfoo() => super.foo; // TODO(sra): Fix compiler assert.
}
-class B extends A {
+class B extends A {
var foo = 333;
B.init() : super.init();
Afoo() => super.foo;
@@ -32,10 +32,10 @@
toString() => '[N.foo = ${Nfoo()}, A.foo = ${Afoo()}, B.foo = ${Bfoo()}]';
}
-B makeB() native;
+B makeB() native ;
@Creates('=Object')
-getBPrototype() native;
+getBPrototype() native ;
void setup() native r"""
function B() { this.foo = 111; } // N.foo
diff --git a/tests/compiler/dart2js_native/subclassing_type_test.dart b/tests/compiler/dart2js_native/subclassing_type_test.dart
index abcb629..a4e14e8 100644
--- a/tests/compiler/dart2js_native/subclassing_type_test.dart
+++ b/tests/compiler/dart2js_native/subclassing_type_test.dart
@@ -16,16 +16,18 @@
class A extends N {}
-class B extends A with M { // native mixin application.
+class B extends A with M {
+ // native mixin application.
}
-class C extends Object with M { // non-native mixin application.
+class C extends Object with M {
+ // non-native mixin application.
}
-B makeB() native;
+B makeB() native ;
@Creates('=Object')
-getBPrototype() native;
+getBPrototype() native ;
void setup() native r"""
function B() {}
@@ -55,10 +57,18 @@
asM(x) => x as M;
setM(x) => gM = x;
-checkTrue(f) => (x) { Expect.isTrue(f(x)); };
-checkFalse(f) => (x) { Expect.isFalse(f(x)); };
-checkId(f) => (x) { Expect.identical(x, f(x)); };
-checkThrows(f) => (x) { Expect.throws(() => f(x)); };
+checkTrue(f) => (x) {
+ Expect.isTrue(f(x));
+ };
+checkFalse(f) => (x) {
+ Expect.isFalse(f(x));
+ };
+checkId(f) => (x) {
+ Expect.identical(x, f(x));
+ };
+checkThrows(f) => (x) {
+ Expect.throws(() => f(x));
+ };
bool get checkedMode {
try {
@@ -78,7 +88,6 @@
B b = makeB();
C c = new C();
-
checkFalse(isA)(1);
checkFalse(isB)(1);
checkFalse(isC)(1);
@@ -94,7 +103,6 @@
checkFalse(isA)(c);
checkFalse(isB)(c);
-
checkThrows(asA)(1);
checkThrows(asB)(1);
checkThrows(asC)(1);
@@ -110,7 +118,6 @@
checkThrows(asA)(c);
checkThrows(asB)(c);
-
if (checkedMode) {
checkThrows(setA)(1);
checkThrows(setB)(1);
diff --git a/tests/compiler/dart2js_native/super_call_test.dart b/tests/compiler/dart2js_native/super_call_test.dart
index ccb6f09..b420516 100644
--- a/tests/compiler/dart2js_native/super_call_test.dart
+++ b/tests/compiler/dart2js_native/super_call_test.dart
@@ -32,10 +32,10 @@
bar() => 'D.bar';
}
-makeA() native;
-makeB() native;
-makeC() native;
-makeD() native;
+makeA() native ;
+makeB() native ;
+makeC() native ;
+makeD() native ;
void setup() native """
// This code is all inside 'setup' and so not accesible from the global scope.
@@ -64,7 +64,6 @@
makeD = function(){return new D};
""";
-
main() {
setup();
diff --git a/tests/compiler/dart2js_native/super_property_test.dart b/tests/compiler/dart2js_native/super_property_test.dart
index b2c89ea..fbe98f7 100644
--- a/tests/compiler/dart2js_native/super_property_test.dart
+++ b/tests/compiler/dart2js_native/super_property_test.dart
@@ -20,6 +20,7 @@
set foo(value) {
super.foo = value;
}
+
get foo => super.foo;
}
@@ -33,11 +34,12 @@
set foo(value) {
super.foo = value;
}
+
get foo => super.foo;
}
-makeA() native;
-makeB() native;
+makeA() native ;
+makeB() native ;
void setup() native """
// This code is all inside 'setup' and so not accesible from the global scope.
@@ -49,12 +51,12 @@
testThing(a) {
a.foo = 123;
- Expect.equals(123, a.foo);
- Expect.equals(123, a.get_foo());
+ Expect.equals(123, a.foo);
+ Expect.equals(123, a.get_foo());
a.bar = 234;
- Expect.equals(234, a.foo);
- Expect.equals(234, a.get_foo());
+ Expect.equals(234, a.foo);
+ Expect.equals(234, a.get_foo());
}
main() {
diff --git a/tests/compiler/dart2js_native/uninstantiated_type_parameter_test.dart b/tests/compiler/dart2js_native/uninstantiated_type_parameter_test.dart
index 43efdb6..730a5bb 100644
--- a/tests/compiler/dart2js_native/uninstantiated_type_parameter_test.dart
+++ b/tests/compiler/dart2js_native/uninstantiated_type_parameter_test.dart
@@ -7,15 +7,12 @@
// Test for uninstantiated native classes as type parameters.
-class UA {
-}
+class UA {}
@Native("B")
-class UB {
-}
+class UB {}
-class C<T> {
-}
+class C<T> {}
main() {
var a = new C<UA>();
diff --git a/tests/html/html.status b/tests/html/html.status
index 426bebd..e4544e8 100644
--- a/tests/html/html.status
+++ b/tests/html/html.status
@@ -9,6 +9,9 @@
mirrors_js_typed_interop_test: Fail # Missing expected failure (Issue 25044)
js_typed_interop_side_cast_exp_test: Fail, OK # tests dart2js-specific behavior.
+js_typed_interop_type1_test: Fail, OK # tests dart2js-specific behavior.
+js_typed_interop_type2_test: Fail, OK # tests dart2js-specific behavior.
+js_typed_interop_type3_test: Fail, OK # tests dart2js-specific behavior.
native_gc_test: Skip # Dartium JSInterop failure
diff --git a/tests/language/language.status b/tests/language/language.status
index 6c6ba24..001cf0e 100644
--- a/tests/language/language.status
+++ b/tests/language/language.status
@@ -44,10 +44,6 @@
async_star_regression_2238_test: CompileTimeError, RuntimeError # drt only runtime-errs.
async_star_cancel_while_paused_test: RuntimeError
-# Experimental feature: Syntactic support for generic methods.
-generic_methods_type_expression_test: RuntimeError # Issue 25869
-generic_methods_generic_function_parameter_test: CompileTimeError # Issue #27299
-
[ ($compiler == none || $compiler == precompiler || $compiler == dart2app || $compiler == dart2appjit) && $checked ]
# The generic functions tests fail in checked mode because the parsed type parameters
# are ignored.
@@ -56,6 +52,7 @@
generic_methods_new_test: RuntimeError # Issue 25869
generic_local_functions_test: RuntimeError # Issue 25869
generic_functions_test: RuntimeError # Issue 25869
+generic_methods_generic_function_parameter_test: RuntimeError # Issue 25869
[ ($compiler == none || $compiler == precompiler || $compiler == dart2app || $compiler == dart2appjit) && ($runtime == vm || $runtime == dart_precompiled || $runtime == dart_app) ]
@@ -87,6 +84,7 @@
[ $compiler == none && ($runtime == dartium || $runtime == drt) ]
issue13474_test: Pass, Fail # Issue 14651.
config_import_test: Fail # Issue 14651.
+generic_methods_generic_function_parameter_test: RuntimeError # Issue 25869
vm/optimized_guarded_field_isolates_test: RuntimeError, OK # Uses Isolate.spawn.
main_test/01: Fail # Issue 20028
main_test/02: Fail # Issue 20028
diff --git a/tests/standalone/io/addlatexhash_test.dart b/tests/standalone/io/addlatexhash_test.dart
index 582b75a..5c1c740 100755
--- a/tests/standalone/io/addlatexhash_test.dart
+++ b/tests/standalone/io/addlatexhash_test.dart
@@ -13,6 +13,16 @@
final dartRootDir = path.dirname(path.dirname(path.dirname(scriptDir)));
final dartRootPath = dartRootDir.toString();
+List<String> packageOptions() {
+ if (Platform.packageRoot != null) {
+ return <String>['--package-root=${Platform.packageRoot}'];
+ } else if (Platform.packageConfig != null) {
+ return <String>['--packages=${Platform.packageConfig}'];
+ } else {
+ return <String>[];
+ }
+}
+
// Check that the given ProcessResult indicates success; if so
// return the standard output, otherwise report the failure
checkAction(result, errorMessage) {
@@ -81,13 +91,13 @@
// actions to take
runAddHash() {
- var args = [
- '--package-root=${Platform.packageRoot}',
+ var args = packageOptions();
+ args.addAll([
path.join(dartRootPath, "tools", "addlatexhash.dart"),
tmpPar8timesPath,
hashPath,
listPath
- ];
+ ]);
return Process.runSync(dartExecutable, args);
}
@@ -154,13 +164,13 @@
Process.runSync("latex", [fileName], workingDirectory: workingDirectory);
runAddHash() {
- var args = [
- '--package-root=${Platform.packageRoot}',
+ var args = packageOptions();
+ args.addAll([
path.join(dartRootPath, "tools", "addlatexhash.dart"),
tmpSpecPath,
hashPath,
listPath
- ];
+ ]);
return Process.runSync(dartExecutable, args);
}
diff --git a/tests/standalone/io/code_collection_test.dart b/tests/standalone/io/code_collection_test.dart
index 3747399..e9ebb0f 100644
--- a/tests/standalone/io/code_collection_test.dart
+++ b/tests/standalone/io/code_collection_test.dart
@@ -44,22 +44,31 @@
});
}
+List<String> packageOptions() {
+ if (Platform.packageRoot != null) {
+ return <String>['--package-root=${Platform.packageRoot}'];
+ } else if (Platform.packageConfig != null) {
+ return <String>['--packages=${Platform.packageConfig}'];
+ } else {
+ return <String>[];
+ }
+}
main(List<String> arguments) {
if (arguments.contains("--run")) {
doTest();
} else {
// Run the test and capture stdout.
- var pr = Process.runSync(Platform.executable,
- ["--verbose-gc",
+ var args = packageOptions();
+ args.addAll(["--verbose-gc",
"--collect-code",
"--code-collection-interval-in-us=0",
"--old_gen_growth_rate=10",
"--log-code-drop",
"--optimization-counter-threshold=-1",
- "--package-root=${Platform.packageRoot}",
Platform.script.toFilePath(),
"--run"]);
+ var pr = Process.runSync(Platform.executable, args);
Expect.equals(0, pr.exitCode);
diff --git a/tests/standalone/io/http_client_stays_alive_test.dart b/tests/standalone/io/http_client_stays_alive_test.dart
index 64ced6e..7355667 100644
--- a/tests/standalone/io/http_client_stays_alive_test.dart
+++ b/tests/standalone/io/http_client_stays_alive_test.dart
@@ -11,12 +11,22 @@
//
// The main script spawns a server and a subprocess which does a connection back
// to it.
-// The subprocess is expected to shut down it's idle sockets after
+// The subprocess is expected to shut down its idle sockets after
// [HttpClient.idleTimeout] and the main script will assert that this happens
// within +/- 2 <= seconds.
const SECONDS = 4;
+List<String> packageOptions() {
+ if (Platform.packageRoot != null) {
+ return <String>['--package-root=${Platform.packageRoot}'];
+ } else if (Platform.packageConfig != null) {
+ return <String>['--packages=${Platform.packageConfig}'];
+ } else {
+ return <String>[];
+ }
+}
+
void runServerProcess() {
asyncStart();
HttpServer.bind('127.0.0.1', 0).then((server) {
@@ -29,9 +39,7 @@
});
var sw = new Stopwatch()..start();
- var arguments = ['--package-root=${Platform.packageRoot}',
- '${Platform.script}',
- url];
+ var arguments = packageOptions()..add(Platform.script.toString())..add(url);
Process.run(Platform.executable, arguments).then((res) {
subscription.cancel();
if (res.exitCode != 0) {
diff --git a/tests/standalone/io/platform_test.dart b/tests/standalone/io/platform_test.dart
index 308d5d0..dd8defd 100644
--- a/tests/standalone/io/platform_test.dart
+++ b/tests/standalone/io/platform_test.dart
@@ -49,10 +49,11 @@
// Restore dir.
Directory.current = oldDir;
var pkgRootString = Platform.packageRoot;
- Directory packageRoot = new Directory.fromUri(Uri.parse(pkgRootString));
- Expect.isTrue(packageRoot.existsSync());
- Expect.isTrue(new Directory("${packageRoot.path}/expect").existsSync());
- Expect.isTrue(Platform.executableArguments.any(
+ if (pkgRootString != null) {
+ Directory packageRoot = new Directory.fromUri(Uri.parse(pkgRootString));
+ Expect.isTrue(packageRoot.existsSync());
+ Expect.isTrue(new Directory("${packageRoot.path}/expect").existsSync());
+ Expect.isTrue(Platform.executableArguments.any(
(arg) {
if (!arg.startsWith("--package-root=")) {
return false;
@@ -60,8 +61,8 @@
// Cut out the '--package-root=' prefix.
arg = arg.substring(15);
return pkgRootString.contains(arg);
- }
- ));
+ }));
+ }
}
void f(reply) {
diff --git a/tests/standalone/io/test_runner_test.dart b/tests/standalone/io/test_runner_test.dart
index 1eaae3f..b216562 100644
--- a/tests/standalone/io/test_runner_test.dart
+++ b/tests/standalone/io/test_runner_test.dart
@@ -15,6 +15,16 @@
final DEFAULT_TIMEOUT = 10;
final LONG_TIMEOUT = 30;
+List<String> packageOptions() {
+ if (Platform.packageRoot != null) {
+ return <String>['--package-root=${Platform.packageRoot}'];
+ } else if (Platform.packageConfig != null) {
+ return <String>['--packages=${Platform.packageConfig}'];
+ } else {
+ return <String>[];
+ }
+}
+
class TestController {
static int numTests = 0;
static int numCompletedTests = 0;
@@ -84,9 +94,11 @@
}
TestCase _makeNormalTestCase(name, expectations) {
+ var args = packageOptions();
+ args.addAll([Platform.script.toFilePath(), name]);
var command = CommandBuilder.instance.getProcessCommand(
'custom', Platform.executable,
- ['--package-root=${Platform.packageRoot}', Platform.script.toFilePath(), name],
+ args,
{});
return _makeTestCase(name, DEFAULT_TIMEOUT, command, expectations);
}
diff --git a/tests/standalone/standalone.status b/tests/standalone/standalone.status
index 96dac8f..dc43ab8 100644
--- a/tests/standalone/standalone.status
+++ b/tests/standalone/standalone.status
@@ -138,6 +138,9 @@
[ $compiler == dart2js && $fast_startup ]
io/observatory_test: Fail # mirrors not supported.
+io/skipping_dart2js_compilations_test: CompileTimeError # Imports dart:mirrors
+io/test_harness_analyzer_test: CompileTimeError # Imports dart:mirrors
+io/test_runner_test: CompileTimeError # Imports dart:mirrors
[ $compiler == dart2js && $browser ]
*: Skip
@@ -275,8 +278,12 @@
io/regress_7679_test: Skip # Platform.executable
io/process_*: Skip # Most use Platform.executable
+[ $runtime == dart_precompiled || $mode == product ]
+io/skipping_dart2js_compilations_test: CompileTimeError # Imports dart:mirrors
+io/test_harness_analyzer_test: CompileTimeError # Imports dart:mirrors
+io/test_runner_test: CompileTimeError # Imports dart:mirrors
+
[ $runtime == dart_precompiled || $runtime == dart_app || $mode == product ]
-debugger/*: Skip
assert_test: SkipByDesign # Requires checked mode.
no_assert_test: SkipByDesign # Requires checked mode.
io/code_collection_test: Skip # Incompatible flags
diff --git a/third_party/.gitignore b/third_party/.gitignore
index c819c4b..f608e21 100644
--- a/third_party/.gitignore
+++ b/third_party/.gitignore
@@ -6,6 +6,7 @@
!pkg
!pkg_tested
!/boringssl
+!/tcmalloc
!drt_resources
!d8
!7zip.tar.gz.sha1
diff --git a/third_party/boringssl/boringssl_dart.gyp b/third_party/boringssl/boringssl_dart.gyp
index 1dc460f..ebb2581 100644
--- a/third_party/boringssl/boringssl_dart.gyp
+++ b/third_party/boringssl/boringssl_dart.gyp
@@ -41,6 +41,10 @@
'<@(boringssl_linux_arm_sources)',
'<@(boringssl_linux_aarch64_sources)',
],
+ 'defines': [
+ '_BSD_SOURCE',
+ '_XOPEN_SOURCE=700',
+ ],
}],
['OS == "win"', {
'defines': [ 'OPENSSL_NO_ASM', 'WIN32_LEAN_AND_MEAN' ],
diff --git a/third_party/tcmalloc/.gitignore b/third_party/tcmalloc/.gitignore
new file mode 100644
index 0000000..b5bd288
--- /dev/null
+++ b/third_party/tcmalloc/.gitignore
@@ -0,0 +1,3 @@
+*.mk
+*.Makefile
+/gperftools
diff --git a/third_party/tcmalloc/README.dart b/third_party/tcmalloc/README.dart
new file mode 100644
index 0000000..71dd619
--- /dev/null
+++ b/third_party/tcmalloc/README.dart
@@ -0,0 +1,23 @@
+Dart uses tcmalloc in the standalone VM on Linux.
+
+To roll tcmalloc forward:
+. Clone the gperftools git repo at the revision you want in a directory off
+ to the side.
+
+. Run a configure command similar to the one in the configure_command file in
+ this directory. It is up to you to determine if different flags are required
+ for the newer gperftools.
+
+. From that repo, copy src/config.h and src/gperftools/tcmalloc.h, and any other
+ generated header files to the include/ directory in this directory.
+
+. Make sure that include/config.h defines HAVE_UCONTEXT_H on Linux,
+
+. Update tcmalloc_sources.gypi, and tcmalloc.gyp if necessary. This may require
+ inspecting gperftools/Makefile.am to see any additional source files and
+ preprocessor defines (-D flags).
+
+. Update the DEPS file with the new git hash.
+
+. Build and run tests for Debug, Release, and Product builds for ia32, x64, mips
+ and arm for Linux and any other OSs that are supported.
diff --git a/third_party/tcmalloc/configure_command b/third_party/tcmalloc/configure_command
new file mode 100644
index 0000000..ea06910
--- /dev/null
+++ b/third_party/tcmalloc/configure_command
@@ -0,0 +1 @@
+./configure --enable-emergency-malloc --enable-frame-pointers --disable-cpu-profiler --disable-heap-checker --disable-debugalloc --enable-sized-delete --disable-libunwind
diff --git a/third_party/tcmalloc/include/config.h b/third_party/tcmalloc/include/config.h
new file mode 100644
index 0000000..2cd633a
--- /dev/null
+++ b/third_party/tcmalloc/include/config.h
@@ -0,0 +1,314 @@
+/* src/config.h. Generated from config.h.in by configure. */
+/* src/config.h.in. Generated from configure.ac by autoheader. */
+
+
+#ifndef GPERFTOOLS_CONFIG_H_
+#define GPERFTOOLS_CONFIG_H_
+
+
+/* Build runtime detection for sized delete */
+/* #undef ENABLE_DYNAMIC_SIZED_DELETE */
+
+/* Build sized deletion operators */
+#define ENABLE_SIZED_DELETE 1
+
+/* Define to 1 if compiler supports __builtin_expect */
+#define HAVE_BUILTIN_EXPECT 1
+
+/* Define to 1 if compiler supports __builtin_stack_pointer */
+/* #undef HAVE_BUILTIN_STACK_POINTER */
+
+/* Define to 1 if you have the <conflict-signal.h> header file. */
+/* #undef HAVE_CONFLICT_SIGNAL_H */
+
+/* Define to 1 if you have the <cygwin/signal.h> header file. */
+/* #undef HAVE_CYGWIN_SIGNAL_H */
+
+/* Define to 1 if you have the declaration of `backtrace', and to 0 if you
+ don't. */
+/* #undef HAVE_DECL_BACKTRACE */
+
+/* Define to 1 if you have the declaration of `cfree', and to 0 if you don't.
+ */
+#define HAVE_DECL_CFREE 1
+
+/* Define to 1 if you have the declaration of `memalign', and to 0 if you
+ don't. */
+#define HAVE_DECL_MEMALIGN 1
+
+/* Define to 1 if you have the declaration of `nanosleep', and to 0 if you
+ don't. */
+/* #undef HAVE_DECL_NANOSLEEP */
+
+/* Define to 1 if you have the declaration of `posix_memalign', and to 0 if
+ you don't. */
+#define HAVE_DECL_POSIX_MEMALIGN 1
+
+/* Define to 1 if you have the declaration of `pvalloc', and to 0 if you
+ don't. */
+#define HAVE_DECL_PVALLOC 1
+
+/* Define to 1 if you have the declaration of `sleep', and to 0 if you don't.
+ */
+/* #undef HAVE_DECL_SLEEP */
+
+/* Define to 1 if you have the declaration of `uname', and to 0 if you don't.
+ */
+#define HAVE_DECL_UNAME 1
+
+/* Define to 1 if you have the declaration of `valloc', and to 0 if you don't.
+ */
+#define HAVE_DECL_VALLOC 1
+
+/* Define to 1 if you have the <dlfcn.h> header file. */
+#define HAVE_DLFCN_H 1
+
+/* Define to 1 if the system has the type `Elf32_Versym'. */
+#define HAVE_ELF32_VERSYM 1
+
+/* Define to 1 if you have the <execinfo.h> header file. */
+#define HAVE_EXECINFO_H 1
+
+/* Define to 1 if you have the <fcntl.h> header file. */
+#define HAVE_FCNTL_H 1
+
+/* Define to 1 if you have the <features.h> header file. */
+#define HAVE_FEATURES_H 1
+
+/* Define to 1 if you have the `fork' function. */
+#define HAVE_FORK 1
+
+/* Define to 1 if you have the `geteuid' function. */
+#define HAVE_GETEUID 1
+
+/* Define to 1 if you have the `getpagesize' function. */
+#define HAVE_GETPAGESIZE 1
+
+/* Define to 1 if you have the <glob.h> header file. */
+#if !defined(__ANDROID__)
+#define HAVE_GLOB_H 1
+#endif
+
+/* Define to 1 if you have the <grp.h> header file. */
+#define HAVE_GRP_H 1
+
+/* Define to 1 if you have the <inttypes.h> header file. */
+#define HAVE_INTTYPES_H 1
+
+/* Define to 1 if you have the <libunwind.h> header file. */
+/* #undef HAVE_LIBUNWIND_H */
+
+/* Define to 1 if you have the <linux/ptrace.h> header file. */
+#define HAVE_LINUX_PTRACE_H 1
+
+/* Define if this is Linux that has SIGEV_THREAD_ID */
+#define HAVE_LINUX_SIGEV_THREAD_ID 1
+
+/* Define to 1 if you have the <malloc.h> header file. */
+#define HAVE_MALLOC_H 1
+
+/* Define to 1 if you have the <memory.h> header file. */
+#define HAVE_MEMORY_H 1
+
+/* Define to 1 if you have a working `mmap' system call. */
+#define HAVE_MMAP 1
+
+/* define if the compiler implements namespaces */
+#define HAVE_NAMESPACES 1
+
+/* Define to 1 if you have the <poll.h> header file. */
+#define HAVE_POLL_H 1
+
+/* define if libc has program_invocation_name */
+#define HAVE_PROGRAM_INVOCATION_NAME 1
+
+/* Define if you have POSIX threads libraries and header files. */
+#define HAVE_PTHREAD 1
+
+/* defined to 1 if pthread symbols are exposed even without include pthread.h
+ */
+/* #undef HAVE_PTHREAD_DESPITE_ASKING_FOR */
+
+/* Define to 1 if you have the <pwd.h> header file. */
+#define HAVE_PWD_H 1
+
+/* Define to 1 if you have the `sbrk' function. */
+#define HAVE_SBRK 1
+
+/* Define to 1 if you have the <sched.h> header file. */
+#define HAVE_SCHED_H 1
+
+/* Define to 1 if you have the <stdint.h> header file. */
+#define HAVE_STDINT_H 1
+
+/* Define to 1 if you have the <stdlib.h> header file. */
+#define HAVE_STDLIB_H 1
+
+/* Define to 1 if you have the <strings.h> header file. */
+#define HAVE_STRINGS_H 1
+
+/* Define to 1 if you have the <string.h> header file. */
+#define HAVE_STRING_H 1
+
+/* Define to 1 if the system has the type `struct mallinfo'. */
+#define HAVE_STRUCT_MALLINFO 1
+
+/* Define to 1 if you have the <sys/cdefs.h> header file. */
+#define HAVE_SYS_CDEFS_H 1
+
+/* Define to 1 if you have the <sys/param.h> header file. */
+#define HAVE_SYS_PARAM_H 1
+
+/* Define to 1 if you have the <sys/prctl.h> header file. */
+#define HAVE_SYS_PRCTL_H 1
+
+/* Define to 1 if you have the <sys/resource.h> header file. */
+#define HAVE_SYS_RESOURCE_H 1
+
+/* Define to 1 if you have the <sys/socket.h> header file. */
+#define HAVE_SYS_SOCKET_H 1
+
+/* Define to 1 if you have the <sys/stat.h> header file. */
+#define HAVE_SYS_STAT_H 1
+
+/* Define to 1 if you have the <sys/syscall.h> header file. */
+#if !defined(__ANDROID__)
+#define HAVE_SYS_SYSCALL_H 1
+#endif
+
+/* Define to 1 if you have the <sys/types.h> header file. */
+#define HAVE_SYS_TYPES_H 1
+
+/* Define to 1 if you have the <sys/ucontext.h> header file. */
+#undef HAVE_SYS_UCONTEXT_H
+
+/* Define to 1 if you have the <sys/wait.h> header file. */
+#define HAVE_SYS_WAIT_H 1
+
+/* Define to 1 if compiler supports __thread */
+#define HAVE_TLS 1
+
+/* Define to 1 if you have the <ucontext.h> header file. */
+#define HAVE_UCONTEXT_H 1
+
+/* Define to 1 if you have the <unistd.h> header file. */
+#define HAVE_UNISTD_H 1
+
+/* Whether <unwind.h> contains _Unwind_Backtrace */
+#define HAVE_UNWIND_BACKTRACE 1
+
+/* Define to 1 if you have the <unwind.h> header file. */
+#define HAVE_UNWIND_H 1
+
+/* Define to 1 if you have the <valgrind.h> header file. */
+/* #undef HAVE_VALGRIND_H */
+
+/* define if your compiler has __attribute__ */
+#define HAVE___ATTRIBUTE__ 1
+
+/* Define to 1 if compiler supports __environ */
+#if !defined(__ANDROID__)
+#define HAVE___ENVIRON 1
+#endif
+
+/* Define to 1 if the system has the type `__int64'. */
+/* #undef HAVE___INT64 */
+
+/* prefix where we look for installed files */
+#define INSTALL_PREFIX "/usr/local"
+
+/* Define to 1 if int32_t is equivalent to intptr_t */
+/* #undef INT32_EQUALS_INTPTR */
+
+/* Define to the sub-directory in which libtool stores uninstalled libraries.
+ */
+#define LT_OBJDIR ".libs/"
+
+/* Define to 'volatile' if __malloc_hook is declared volatile */
+#define MALLOC_HOOK_MAYBE_VOLATILE volatile
+
+/* Name of package */
+#define PACKAGE "gperftools"
+
+/* Define to the address where bug reports for this package should be sent. */
+#define PACKAGE_BUGREPORT "gperftools@googlegroups.com"
+
+/* Define to the full name of this package. */
+#define PACKAGE_NAME "gperftools"
+
+/* Define to the full name and version of this package. */
+#define PACKAGE_STRING "gperftools 2.5"
+
+/* Define to the one symbol short name of this package. */
+#define PACKAGE_TARNAME "gperftools"
+
+/* Define to the home page for this package. */
+#define PACKAGE_URL ""
+
+/* Define to the version of this package. */
+#define PACKAGE_VERSION "2.5"
+
+/* How to access the PC from a struct ucontext */
+/* #undef PC_FROM_UCONTEXT */
+
+/* Always the empty-string on non-windows systems. On windows, should be
+ "__declspec(dllexport)". This way, when we compile the dll, we export our
+ functions/classes. It's safe to define this here because config.h is only
+ used internally, to compile the DLL, and every DLL source file #includes
+ "config.h" before anything else. */
+#define PERFTOOLS_DLL_DECL /**/
+
+/* printf format code for printing a size_t and ssize_t */
+#define PRIdS "ld"
+
+/* printf format code for printing a size_t and ssize_t */
+#define PRIuS "lu"
+
+/* printf format code for printing a size_t and ssize_t */
+#define PRIxS "lx"
+
+/* Mark the systems where we know it's bad if pthreads runs too
+ early before main (before threads are initialized, presumably). */
+#ifdef __FreeBSD__
+#define PTHREADS_CRASHES_IF_RUN_TOO_EARLY 1
+#endif
+
+/* Define to necessary symbol if this constant uses a non-standard name on
+ your system. */
+/* #undef PTHREAD_CREATE_JOINABLE */
+
+/* Define to 1 if you have the ANSI C header files. */
+#define STDC_HEADERS 1
+
+/* the namespace where STL code like vector<> is defined */
+#define STL_NAMESPACE std
+
+/* Define 32K of internal pages size for tcmalloc */
+/* #undef TCMALLOC_32K_PAGES */
+
+/* Define 64K of internal pages size for tcmalloc */
+/* #undef TCMALLOC_64K_PAGES */
+
+/* Define 8 bytes of allocation alignment for tcmalloc */
+/* #undef TCMALLOC_ALIGN_8BYTES */
+
+/* Version number of package */
+#define VERSION "2.5"
+
+/* C99 says: define this to get the PRI... macros from stdint.h */
+#ifndef __STDC_FORMAT_MACROS
+# define __STDC_FORMAT_MACROS 1
+#endif
+
+/* Define to `__inline__' or `__inline' if that's what the C compiler
+ calls it, or to nothing if 'inline' is not supported under any name. */
+#ifndef __cplusplus
+/* #undef inline */
+#endif
+
+
+#ifdef __MINGW32__
+#include "windows/mingw.h"
+#endif
+
+#endif /* #ifndef GPERFTOOLS_CONFIG_H_ */
diff --git a/third_party/tcmalloc/include/gperftools/tcmalloc.h b/third_party/tcmalloc/include/gperftools/tcmalloc.h
new file mode 100644
index 0000000..138d1f9
--- /dev/null
+++ b/third_party/tcmalloc/include/gperftools/tcmalloc.h
@@ -0,0 +1,147 @@
+// -*- Mode: C; c-basic-offset: 2; indent-tabs-mode: nil -*-
+/* Copyright (c) 2003, Google Inc.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * ---
+ * Author: Sanjay Ghemawat <opensource@google.com>
+ * .h file by Craig Silverstein <opensource@google.com>
+ */
+
+#ifndef TCMALLOC_TCMALLOC_H_
+#define TCMALLOC_TCMALLOC_H_
+
+#include <stddef.h> /* for size_t */
+
+/* Define the version number so folks can check against it */
+#define TC_VERSION_MAJOR 2
+#define TC_VERSION_MINOR 5
+#define TC_VERSION_PATCH ""
+#define TC_VERSION_STRING "gperftools 2.5"
+
+/* For struct mallinfo, if it's defined. */
+#if 1
+# include <malloc.h>
+#endif
+
+#ifdef __cplusplus
+#define PERFTOOLS_THROW throw()
+#else
+# ifdef __GNUC__
+# define PERFTOOLS_THROW __attribute__((__nothrow__))
+# else
+# define PERFTOOLS_THROW
+# endif
+#endif
+
+#ifndef PERFTOOLS_DLL_DECL
+#define PERFTOOLS_DLL_DECL_DEFINED
+# ifdef _WIN32
+# define PERFTOOLS_DLL_DECL __declspec(dllimport)
+# else
+# define PERFTOOLS_DLL_DECL
+# endif
+#endif
+
+#ifdef __cplusplus
+namespace std {
+struct nothrow_t;
+}
+
+extern "C" {
+#endif
+ /*
+ * Returns a human-readable version string. If major, minor,
+ * and/or patch are not NULL, they are set to the major version,
+ * minor version, and patch-code (a string, usually "").
+ */
+ PERFTOOLS_DLL_DECL const char* tc_version(int* major, int* minor,
+ const char** patch) PERFTOOLS_THROW;
+
+ PERFTOOLS_DLL_DECL void* tc_malloc(size_t size) PERFTOOLS_THROW;
+ PERFTOOLS_DLL_DECL void* tc_malloc_skip_new_handler(size_t size) PERFTOOLS_THROW;
+ PERFTOOLS_DLL_DECL void tc_free(void* ptr) PERFTOOLS_THROW;
+ PERFTOOLS_DLL_DECL void tc_free_sized(void *ptr, size_t size) PERFTOOLS_THROW;
+ PERFTOOLS_DLL_DECL void* tc_realloc(void* ptr, size_t size) PERFTOOLS_THROW;
+ PERFTOOLS_DLL_DECL void* tc_calloc(size_t nmemb, size_t size) PERFTOOLS_THROW;
+ PERFTOOLS_DLL_DECL void tc_cfree(void* ptr) PERFTOOLS_THROW;
+
+ PERFTOOLS_DLL_DECL void* tc_memalign(size_t __alignment,
+ size_t __size) PERFTOOLS_THROW;
+ PERFTOOLS_DLL_DECL int tc_posix_memalign(void** ptr,
+ size_t align, size_t size) PERFTOOLS_THROW;
+ PERFTOOLS_DLL_DECL void* tc_valloc(size_t __size) PERFTOOLS_THROW;
+ PERFTOOLS_DLL_DECL void* tc_pvalloc(size_t __size) PERFTOOLS_THROW;
+
+ PERFTOOLS_DLL_DECL void tc_malloc_stats(void) PERFTOOLS_THROW;
+ PERFTOOLS_DLL_DECL int tc_mallopt(int cmd, int value) PERFTOOLS_THROW;
+#if 1
+ PERFTOOLS_DLL_DECL struct mallinfo tc_mallinfo(void) PERFTOOLS_THROW;
+#endif
+
+ /*
+ * This is an alias for MallocExtension::instance()->GetAllocatedSize().
+ * It is equivalent to
+ * OS X: malloc_size()
+ * glibc: malloc_usable_size()
+ * Windows: _msize()
+ */
+ PERFTOOLS_DLL_DECL size_t tc_malloc_size(void* ptr) PERFTOOLS_THROW;
+
+#ifdef __cplusplus
+ PERFTOOLS_DLL_DECL int tc_set_new_mode(int flag) PERFTOOLS_THROW;
+ PERFTOOLS_DLL_DECL void* tc_new(size_t size);
+ PERFTOOLS_DLL_DECL void* tc_new_nothrow(size_t size,
+ const std::nothrow_t&) PERFTOOLS_THROW;
+ PERFTOOLS_DLL_DECL void tc_delete(void* p) PERFTOOLS_THROW;
+ PERFTOOLS_DLL_DECL void tc_delete_sized(void* p, size_t size) throw();
+ PERFTOOLS_DLL_DECL void tc_delete_nothrow(void* p,
+ const std::nothrow_t&) PERFTOOLS_THROW;
+ PERFTOOLS_DLL_DECL void* tc_newarray(size_t size);
+ PERFTOOLS_DLL_DECL void* tc_newarray_nothrow(size_t size,
+ const std::nothrow_t&) PERFTOOLS_THROW;
+ PERFTOOLS_DLL_DECL void tc_deletearray(void* p) PERFTOOLS_THROW;
+ PERFTOOLS_DLL_DECL void tc_deletearray_sized(void* p, size_t size) throw();
+ PERFTOOLS_DLL_DECL void tc_deletearray_nothrow(void* p,
+ const std::nothrow_t&) PERFTOOLS_THROW;
+}
+#endif
+
+/* We're only un-defining those for public */
+#if !defined(GPERFTOOLS_CONFIG_H_)
+
+#undef PERFTOOLS_THROW
+
+#ifdef PERFTOOLS_DLL_DECL_DEFINED
+#undef PERFTOOLS_DLL_DECL
+#undef PERFTOOLS_DLL_DECL_DEFINED
+#endif
+
+#endif /* GPERFTOOLS_CONFIG_H_ */
+
+#endif /* #ifndef TCMALLOC_TCMALLOC_H_ */
diff --git a/third_party/tcmalloc/tcmalloc.gypi b/third_party/tcmalloc/tcmalloc.gypi
new file mode 100644
index 0000000..c8e20fe
--- /dev/null
+++ b/third_party/tcmalloc/tcmalloc.gypi
@@ -0,0 +1,109 @@
+# Copyright (c) 2016, 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.
+
+{
+ 'targets': [
+ {
+ 'target_name': 'dynamic_annotations',
+ 'type': 'static_library',
+ 'toolsets': ['host', 'target'],
+ 'include_dirs': [
+ 'include',
+ 'gperftools/src/base',
+ 'gperftools/src',
+ ],
+ 'cflags!': [
+ '-Werror',
+ '-Wnon-virtual-dtor',
+ '-Woverloaded-virtual',
+ '-fno-rtti',
+ ],
+ 'sources': [
+ 'gperftools/src/base/dynamic_annotations.c',
+ 'gperftools/src/base/dynamic_annotations.h',
+ ],
+ },
+ {
+ 'target_name': 'tcmalloc',
+ 'type': 'static_library',
+ 'toolsets': ['host', 'target'],
+ 'dependencies': [
+ 'dynamic_annotations',
+ ],
+ 'include_dirs': [
+ 'include',
+ 'gperftools/src/base',
+ 'gperftools/src',
+ ],
+ 'includes': [
+ 'tcmalloc_sources.gypi',
+ ],
+ # Disable the heap checker in tcmalloc.
+ 'defines': [
+ 'ENABLE_EMERGENCY_MALLOC',
+ 'NO_HEAP_CHECK',
+ # Disable debug even in a Dart Debug build. It is too slow.
+ 'NDEBUG',
+ ],
+ 'defines!': [
+ # Disable debug even in a Dart Debug build. It is too slow.
+ 'DEBUG',
+ ],
+ 'cflags': [
+ '-Wno-missing-field-initializers',
+ '-Wno-sign-compare',
+ '-Wno-type-limits',
+ '-Wno-unused-result',
+ '-Wno-vla',
+ '-fno-builtin-malloc',
+ '-fno-builtin-free',
+ '-fno-builtin-realloc',
+ '-fno-builtin-calloc',
+ '-fno-builtin-cfree',
+ '-fno-builtin-memalign',
+ '-fno-builtin-posix_memalign',
+ '-fno-builtin-valloc',
+ '-fno-builtin-pvalloc',
+ '-fpermissive',
+ ],
+ 'cflags!': [
+ '-Werror',
+ '-Wvla',
+ ],
+ 'link_settings': {
+ 'configurations': {
+ 'Dart_Linux_Base': {
+ 'ldflags': [
+ # Don't let linker rip this symbol out, otherwise the heap&cpu
+ # profilers will not initialize properly on startup.
+ '-Wl,-uIsHeapProfilerRunning,-uProfilerStart',
+ ],
+ },
+ },
+ },
+ 'sources!': [
+ # No debug allocator.
+ 'gperftools/src/debugallocation.cc',
+ # Not needed when using emergency malloc.
+ 'gperftools/src/fake_stacktrace_scope.cc',
+ # Not using the cpuprofiler
+ 'gperftools/src/base/thread_lister.c',
+ 'gperftools/src/base/thread_lister.h',
+ 'gperftools/src/profile-handler.cc',
+ 'gperftools/src/profile-handler.h',
+ 'gperftools/src/profiledata.cc',
+ 'gperftools/src/profiledata.h',
+ 'gperftools/src/profiler.cc',
+ ],
+ # Disable sample collection in Release and Product builds.
+ 'configurations': {
+ 'Dart_Product': {
+ 'defines': [
+ 'NO_TCMALLOC_SAMPLES',
+ ],
+ },
+ },
+ },
+ ],
+}
diff --git a/third_party/tcmalloc/tcmalloc_sources.gypi b/third_party/tcmalloc/tcmalloc_sources.gypi
new file mode 100644
index 0000000..6325fb7
--- /dev/null
+++ b/third_party/tcmalloc/tcmalloc_sources.gypi
@@ -0,0 +1,161 @@
+# Copyright (c) 2016, 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.
+
+{
+ 'sources': [
+ # gperftools/src/
+ 'gperftools/src/addressmap-inl.h',
+ 'gperftools/src/central_freelist.cc',
+ 'gperftools/src/central_freelist.h',
+ 'gperftools/src/common.cc',
+ 'gperftools/src/common.h',
+ 'gperftools/src/config_for_unittests.h',
+ 'gperftools/src/config.h',
+ 'gperftools/src/config.h.in',
+ 'gperftools/src/debugallocation.cc',
+ 'gperftools/src/emergency_malloc.cc',
+ 'gperftools/src/emergency_malloc_for_stacktrace.cc',
+ 'gperftools/src/emergency_malloc.h',
+ 'gperftools/src/fake_stacktrace_scope.cc',
+ 'gperftools/src/getenv_safe.h',
+ 'gperftools/src/getpc.h',
+ 'gperftools/src/heap-checker-bcad.cc',
+ 'gperftools/src/heap-checker.cc',
+ 'gperftools/src/heap-profiler.cc',
+ 'gperftools/src/heap-profile-stats.h',
+ 'gperftools/src/heap-profile-table.cc',
+ 'gperftools/src/heap-profile-table.h',
+ 'gperftools/src/internal_logging.cc',
+ 'gperftools/src/internal_logging.h',
+ 'gperftools/src/libc_override_gcc_and_weak.h',
+ 'gperftools/src/libc_override_glibc.h',
+ 'gperftools/src/libc_override.h',
+ 'gperftools/src/libc_override_osx.h',
+ 'gperftools/src/libc_override_redefine.h',
+ 'gperftools/src/linked_list.h',
+ 'gperftools/src/malloc_extension.cc',
+ 'gperftools/src/malloc_hook.cc',
+ 'gperftools/src/malloc_hook-inl.h',
+ 'gperftools/src/malloc_hook_mmap_freebsd.h',
+ 'gperftools/src/malloc_hook_mmap_linux.h',
+ 'gperftools/src/maybe_emergency_malloc.h',
+ 'gperftools/src/maybe_threads.cc',
+ 'gperftools/src/maybe_threads.h',
+ 'gperftools/src/memfs_malloc.cc',
+ 'gperftools/src/memory_region_map.cc',
+ 'gperftools/src/memory_region_map.h',
+ 'gperftools/src/packed-cache-inl.h',
+ 'gperftools/src/page_heap_allocator.h',
+ 'gperftools/src/page_heap.cc',
+ 'gperftools/src/page_heap.h',
+ 'gperftools/src/pagemap.h',
+ 'gperftools/src/profiledata.cc',
+ 'gperftools/src/profiledata.h',
+ 'gperftools/src/profile-handler.cc',
+ 'gperftools/src/profile-handler.h',
+ 'gperftools/src/profiler.cc',
+ 'gperftools/src/raw_printer.cc',
+ 'gperftools/src/raw_printer.h',
+ 'gperftools/src/sampler.cc',
+ 'gperftools/src/sampler.h',
+ 'gperftools/src/span.cc',
+ 'gperftools/src/span.h',
+ 'gperftools/src/stacktrace_arm-inl.h',
+ 'gperftools/src/stacktrace.cc',
+ 'gperftools/src/stacktrace_generic-inl.h',
+ 'gperftools/src/stacktrace_impl_setup-inl.h',
+ 'gperftools/src/stacktrace_instrument-inl.h',
+ 'gperftools/src/stacktrace_libgcc-inl.h',
+ 'gperftools/src/stacktrace_libunwind-inl.h',
+ 'gperftools/src/stacktrace_powerpc-darwin-inl.h',
+ 'gperftools/src/stacktrace_powerpc-inl.h',
+ 'gperftools/src/stacktrace_powerpc-linux-inl.h',
+ 'gperftools/src/stack_trace_table.cc',
+ 'gperftools/src/stack_trace_table.h',
+ 'gperftools/src/stacktrace_win32-inl.h',
+ 'gperftools/src/stacktrace_x86-inl.h',
+ 'gperftools/src/static_vars.cc',
+ 'gperftools/src/static_vars.h',
+ 'gperftools/src/symbolize.cc',
+ 'gperftools/src/symbolize.h',
+ 'gperftools/src/system-alloc.cc',
+ 'gperftools/src/system-alloc.h',
+ 'gperftools/src/tcmalloc.cc',
+ 'gperftools/src/tcmalloc_guard.h',
+ 'gperftools/src/tcmalloc.h',
+ 'gperftools/src/thread_cache.cc',
+ 'gperftools/src/thread_cache.h',
+
+ # gperftools/src/base/
+ 'gperftools/src/base/arm_instruction_set_select.h',
+ 'gperftools/src/base/atomicops.h',
+ 'gperftools/src/base/atomicops-internals-arm-generic.h',
+ 'gperftools/src/base/atomicops-internals-arm-v6plus.h',
+ 'gperftools/src/base/atomicops-internals-gcc.h',
+ 'gperftools/src/base/atomicops-internals-linuxppc.h',
+ 'gperftools/src/base/atomicops-internals-macosx.h',
+ 'gperftools/src/base/atomicops-internals-mips.h',
+ 'gperftools/src/base/atomicops-internals-windows.h',
+ 'gperftools/src/base/atomicops-internals-x86.cc',
+ 'gperftools/src/base/atomicops-internals-x86.h',
+ 'gperftools/src/base/basictypes.h',
+ 'gperftools/src/base/commandlineflags.h',
+ # This C files is compiled into a separate target.
+ # 'gperftools/src/base/dynamic_annotations.c',
+ # 'gperftools/src/base/dynamic_annotations.h',
+ 'gperftools/src/base/elfcore.h',
+ 'gperftools/src/base/elf_mem_image.cc',
+ 'gperftools/src/base/elf_mem_image.h',
+ 'gperftools/src/base/googleinit.h',
+ 'gperftools/src/base/linux_syscall_support.h',
+ 'gperftools/src/base/linuxthreads.cc',
+ 'gperftools/src/base/linuxthreads.h',
+ 'gperftools/src/base/logging.cc',
+ 'gperftools/src/base/logging.h',
+ 'gperftools/src/base/low_level_alloc.cc',
+ 'gperftools/src/base/low_level_alloc.h',
+ 'gperftools/src/base/simple_mutex.h',
+ 'gperftools/src/base/spinlock.cc',
+ 'gperftools/src/base/spinlock.h',
+ 'gperftools/src/base/spinlock_internal.cc',
+ 'gperftools/src/base/spinlock_internal.h',
+ 'gperftools/src/base/spinlock_linux-inl.h',
+ 'gperftools/src/base/spinlock_posix-inl.h',
+ 'gperftools/src/base/spinlock_win32-inl.h',
+ 'gperftools/src/base/stl_allocator.h',
+ 'gperftools/src/base/sysinfo.cc',
+ 'gperftools/src/base/sysinfo.h',
+ 'gperftools/src/base/thread_annotations.h',
+ 'gperftools/src/base/thread_lister.c',
+ 'gperftools/src/base/thread_lister.h',
+ 'gperftools/src/base/vdso_support.cc',
+ 'gperftools/src/base/vdso_support.h',
+
+ # gperftools/src/google/
+ 'gperftools/src/google/heap-checker.h',
+ 'gperftools/src/google/heap-profiler.h',
+ 'gperftools/src/google/malloc_extension_c.h',
+ 'gperftools/src/google/malloc_extension.h',
+ 'gperftools/src/google/malloc_hook_c.h',
+ 'gperftools/src/google/malloc_hook.h',
+ 'gperftools/src/google/profiler.h',
+ 'gperftools/src/google/stacktrace.h',
+ 'gperftools/src/google/tcmalloc.h',
+
+ # gperftools/src/gperftools/
+ 'gperftools/src/gperftools/heap-checker.h',
+ 'gperftools/src/gperftools/heap-profiler.h',
+ 'gperftools/src/gperftools/malloc_extension_c.h',
+ 'gperftools/src/gperftools/malloc_extension.h',
+ 'gperftools/src/gperftools/malloc_hook_c.h',
+ 'gperftools/src/gperftools/malloc_hook.h',
+ 'gperftools/src/gperftools/profiler.h',
+ 'gperftools/src/gperftools/stacktrace.h',
+ 'gperftools/src/gperftools/tcmalloc.h',
+ 'gperftools/src/gperftools/tcmalloc.h.in',
+
+ # gperftools/src/third_party/
+ 'gperftools/src/third_party/valgrind.h',
+ ],
+}
diff --git a/tools/.packages b/tools/.packages
deleted file mode 100644
index 888665a..0000000
--- a/tools/.packages
+++ /dev/null
@@ -1,9 +0,0 @@
-# The test runner logic depends on `package:yaml`, because it is not structured
-# as a pub package, we generated this file manually to contain all of yaml's
-# transitive dependencies.
-charcode:../third_party/pkg/charcode/lib/
-collection:../third_party/pkg/collection/lib/
-path:../third_party/pkg/path/lib/
-source_span:../third_party/pkg/source_span/lib/
-string_scanner:../third_party/pkg/string_scanner/lib/
-yaml:../third_party/pkg/yaml/lib/
diff --git a/tools/VERSION b/tools/VERSION
index 4da48d6..6ce3177 100644
--- a/tools/VERSION
+++ b/tools/VERSION
@@ -27,5 +27,5 @@
MAJOR 1
MINOR 20
PATCH 0
-PRERELEASE 5
+PRERELEASE 6
PRERELEASE_PATCH 0
diff --git a/tools/bots/bot.py b/tools/bots/bot.py
index b24fe74..92a4f97 100644
--- a/tools/bots/bot.py
+++ b/tools/bots/bot.py
@@ -255,7 +255,6 @@
build_root = utils.GetBuildRoot(
BUILD_OS, build_info.mode, build_info.arch)
- package_root = os.path.abspath(os.path.join(build_root, 'packages'))
dart_name = 'dart.exe' if build_info.system == 'windows' else 'dart'
dart_bin = os.path.join(sdk_bin, dart_name)
@@ -264,9 +263,7 @@
os.path.join('third_party', 'pkg', 'test', 'bin', 'test.dart'))
with utils.ChangedWorkingDirectory(path):
- args = [dart_bin, '--package-root=' + package_root, test_bin,
- '--package-root', package_root, '--reporter', 'expanded',
- '--no-color']
+ args = [dart_bin, test_bin, '--reporter', 'expanded', '--no-color']
print("Running %s" % ' '.join(args))
RunProcess(args)
diff --git a/tools/bots/dart_sdk.py b/tools/bots/dart_sdk.py
index ce8b5c9..66905de 100644
--- a/tools/bots/dart_sdk.py
+++ b/tools/bots/dart_sdk.py
@@ -51,14 +51,11 @@
dartdoc_dart = os.path.join(bot_utils.DART_DIR,
'third_party', 'pkg' , 'dartdoc' , 'bin' ,
'dartdoc.dart')
- packages_dir = os.path.join(bot_utils.DART_DIR,
- utils.GetBuildRoot(BUILD_OS, 'release', 'ia32'),
- 'packages')
footer_file = os.path.join(bot_utils.DART_DIR,
'tools', 'bots', 'dartdoc_footer.html')
url = 'https://api.dartlang.org/stable'
with bot.BuildStep('Build API docs by dartdoc'):
- bot_utils.run([dart_exe, '--package-root=' + packages_dir, dartdoc_dart,
+ bot_utils.run([dart_exe, dartdoc_dart,
'--sdk-docs','--output', dirname, '--dart-sdk', dart_sdk,
'--footer' , footer_file, '--rel-canonical-prefix=' + url])
diff --git a/tools/bots/linux_distribution_support.py b/tools/bots/linux_distribution_support.py
index 5e859e4..0014d26 100644
--- a/tools/bots/linux_distribution_support.py
+++ b/tools/bots/linux_distribution_support.py
@@ -118,12 +118,12 @@
if build_info.builder_tag == "debian_wheezy":
if not "jessie" in stdout:
print "Trying to build debian bits on a non debian system"
- print "You can't fix this, please contact ricow@ or whesse@"
+ print "You can't fix this, please contact whesse@"
sys.exit(1)
if build_info.builder_tag == "ubuntu_precise":
if not "precise" in stdout:
print "Trying to build ubuntu bits on a non ubuntu system"
- print "You can't fix this, please contact ricow@ or whesse@"
+ print "You can't fix this, please contact whesse@"
sys.exit(1)
with bot.BuildStep('Create src tarball'):
diff --git a/tools/dartium/buildbot_annotated_steps.py b/tools/dartium/buildbot_annotated_steps.py
index 0f69c1f..f8eeb23 100755
--- a/tools/dartium/buildbot_annotated_steps.py
+++ b/tools/dartium/buildbot_annotated_steps.py
@@ -116,6 +116,7 @@
# successful.
if result == 0 and info.channel == 'be':
result = upload_steps.ArchiveAndUpload(info, archive_latest=True) or result
+ return result
if __name__ == '__main__':
sys.exit(main())
diff --git a/tools/deps/dartium.deps/DEPS b/tools/deps/dartium.deps/DEPS
index 6a7b70f..99c82f4 100644
--- a/tools/deps/dartium.deps/DEPS
+++ b/tools/deps/dartium.deps/DEPS
@@ -29,7 +29,7 @@
"args_tag": "@0.13.0",
"barback_rev" : "@29ee90dbcf77cfd64632fa2797a4c8a4f29a4b51",
"charcode_tag": "@1.1.0",
- "collection_rev": "@f6135e6350c63eb3f4dd12953b8d4363faff16fc",
+ "collection_tag": "@1.9.1",
"crypto_rev" : "@2df57a1e26dd88e8d0614207d4b062c73209917d",
"csslib_tag" : "@0.12.0",
"dart2js_info_rev" : "@0a221eaf16aec3879c45719de656680ccb80d8a1",
@@ -48,6 +48,7 @@
"oauth2_rev": "@1bff41f4d54505c36f2d1a001b83b8b745c452f5",
"observatory_pub_packages_rev": "@26aad88f1c1915d39bbcbff3cad589e2402fdcf1",
"package_config_rev": "@0.1.3",
+ "package_resolver_tag": "@1.0.2",
"path_rev": "@b657c0854d1cf41c014986fa9d2321f1173df805",
"plugin_tag": "@0.1.0",
"pool_rev": "@22e12aeb16ad0b626900dbe79e4a25391ddfb28c",
@@ -94,7 +95,7 @@
"src/dart/third_party/pkg/dart2js_info":
(Var("github_mirror") % "dart2js_info") + Var("dart2js_info_rev"),
"src/dart/third_party/pkg/collection":
- (Var("github_mirror") % "collection") + Var("collection_rev"),
+ (Var("github_mirror") % "collection") + Var("collection_tag"),
"src/dart/third_party/pkg/glob":
(Var("github_mirror") % "glob") + Var("glob_rev"),
"src/dart/third_party/pkg/html":
@@ -125,8 +126,11 @@
"src/dart/third_party/observatory_pub_packages":
(Var("github_mirror") % "observatory_pub_packages") +
Var("observatory_pub_packages_rev"),
- "src/dart/third_party/pkg/package_config":
+ "src/dart/third_party/pkg_tested/package_config":
(Var("github_mirror") % "package_config") + Var("package_config_rev"),
+ "src/dart/third_party/pkg_tested/package_resolver":
+ "https://github.com/dart-lang/package_resolver.git" +
+ Var("package_resolver_tag"),
"src/dart/third_party/pkg/path":
(Var("github_mirror") % "path") + Var("path_rev"),
"src/dart/third_party/pkg/plugin":
@@ -230,3 +234,19 @@
"src/dart/tools/sdks",
],
})
+hooks.append({
+ "name": "unittest",
+ # Unittest is an early version, 0.11.6, of the package "test"
+ # Do not use it in any new tests.
+ "pattern": ".",
+ "action": [
+ "download_from_google_storage",
+ "--no_auth",
+ "--no_resume",
+ "--bucket",
+ "dart-dependencies",
+ "--extract",
+ "-s",
+ "src/dart/third_party/pkg/unittest.tar.gz.sha1",
+ ],
+})
diff --git a/tools/gyp/all.gypi b/tools/gyp/all.gypi
index 1e6b313..160c0bb 100644
--- a/tools/gyp/all.gypi
+++ b/tools/gyp/all.gypi
@@ -12,6 +12,8 @@
'target_arch': 'ia32',
# Flag that tells us whether to build native support for dart:io.
'dart_io_support': 1,
+ # Flag that tells us whether this is an ASAN build.
+ 'asan%': 0,
},
'conditions': [
[ 'OS=="linux"', {
diff --git a/tools/gyp/configurations.gypi b/tools/gyp/configurations.gypi
index cabfd6c..77d05b3 100644
--- a/tools/gyp/configurations.gypi
+++ b/tools/gyp/configurations.gypi
@@ -680,6 +680,7 @@
'Dart_Base', 'Dart_mips_Base', 'Dart_Debug',
'Dart_Linux_Base',
'Dart_Linux_xmips_Base',
+ 'Dart_Linux_xmips_Debug',
'Dart_Linux_Debug',
],
},
@@ -689,6 +690,7 @@
'Dart_Base', 'Dart_mips_Base', 'Dart_Release',
'Dart_Linux_Base',
'Dart_Linux_xmips_Base',
+ 'Dart_Linux_xmips_Release',
'Dart_Linux_Release',
],
},
diff --git a/tools/gyp/configurations_android.gypi b/tools/gyp/configurations_android.gypi
index 2aa561b..15ae2a5 100644
--- a/tools/gyp/configurations_android.gypi
+++ b/tools/gyp/configurations_android.gypi
@@ -45,6 +45,7 @@
],
'cflags': [
'-U__linux__', # Don't allow toolchain to claim -D__linux__
+ '-U__linux',
'-ffunction-sections',
'-funwind-tables',
'-fstack-protector',
diff --git a/tools/gyp/configurations_make.gypi b/tools/gyp/configurations_make.gypi
index 8b61127..b514713 100644
--- a/tools/gyp/configurations_make.gypi
+++ b/tools/gyp/configurations_make.gypi
@@ -299,6 +299,40 @@
}]]
},
+ # These flags are needed for tcmalloc to be able to collect stack traces
+ # for heap profiling on mips.
+ 'Dart_Linux_xmips_Debug': {
+ 'abstract': 1,
+ 'target_conditions': [
+ ['_toolset=="target"', {
+ 'cflags!': [
+ '-fno-exceptions',
+ ],
+ 'cflags': [
+ '-fexceptions',
+ '-funwind-tables',
+ ],
+ }],
+ ],
+ },
+
+ # These flags are needed for tcmalloc to be able to collect stack traces
+ # for heap profiling on mips.
+ 'Dart_Linux_xmips_Release': {
+ 'abstract': 1,
+ 'target_conditions': [
+ ['_toolset=="target"', {
+ 'cflags!': [
+ '-fno-exceptions',
+ ],
+ 'cflags': [
+ '-fexceptions',
+ '-funwind-tables',
+ ],
+ }],
+ ],
+ },
+
# MIPS native build
'Dart_Linux_mips_Base': {
'abstract': 1,
diff --git a/tools/make_links.py b/tools/make_links.py
index d49af30..294c9c9 100755
--- a/tools/make_links.py
+++ b/tools/make_links.py
@@ -26,6 +26,8 @@
import shutil
import subprocess
import sys
+import urllib
+import urlparse
import utils
# Useful messages when we find orphaned checkouts.
@@ -43,6 +45,15 @@
action="store_true",
dest="quiet",
default=False)
+ result.add_option("--create-links",
+ help='Create links to the package lib directories in "packages/".',
+ action='store_false',
+ default=True)
+ result.add_option("--create-package-file",
+ help='Create a ".packages" file pointing to the packages.',
+ action='store_false',
+ default=True)
+
return result.parse_args()
def make_link(quiet, source, target, orig_source):
@@ -81,12 +92,12 @@
os.mkdir(dir_name)
open(options.timestamp_file, 'w').close()
-
def main(argv):
(options, args) = get_options()
- target = os.path.relpath(args[0])
+ target_dir = os.path.relpath(args[0])
+ target = os.path.join(target_dir, 'packages')
if os.path.exists(target):
- # If the packages directory already exists, delete the current links inside
+ # If the packages directory already exists, delete the current links in
# it. This is necessary, otherwise we can end up having links in there
# pointing to directories which no longer exist (on incremental builds).
for link in os.listdir(target):
@@ -99,7 +110,12 @@
os.remove(full_link)
else:
os.makedirs(target)
+ target = os.path.join(target_dir, '.packages')
+ if os.path.exists(target):
+ os.remove(target)
+
linked_names = {};
+ package_file_contents = '# .package file created by tools/make_links.py\n'
for source in args[1:]:
# Assume the source directory is named ".../NAME/lib".
split = source.split(':')
@@ -122,14 +138,21 @@
return 1
linked_names[name] = path
orig_source = source
- if utils.GuessOS() == 'win32':
- source = os.path.relpath(source)
- else:
- source = os.path.relpath(source, start=target)
- exit_code = make_link(
- options.quiet, source, os.path.join(target, name), orig_source)
- if exit_code != 0:
- return exit_code
+ if options.create_links:
+ if utils.GuessOS() == 'win32':
+ source = os.path.relpath(source)
+ else:
+ source = os.path.relpath(source, start=target)
+ exit_code = make_link(options.quiet,
+ source, os.path.join(target, name), orig_source)
+ if exit_code != 0:
+ return exit_code
+ abs_source = os.path.abspath(orig_source)
+ source_url = urlparse.urljoin('file:', urllib.pathname2url(abs_source))
+ package_file_contents += '%s:%s\n' % (name, source_url)
+ if options.create_package_file:
+ with open(os.path.join(target_dir, '.packages'), 'w') as package_file:
+ package_file.write(package_file_contents)
create_timestamp_file(options)
return 0
diff --git a/tools/observatory_tool.py b/tools/observatory_tool.py
index 3cd09c9..f54c93d 100755
--- a/tools/observatory_tool.py
+++ b/tools/observatory_tool.py
@@ -48,7 +48,6 @@
def BuildArguments():
result = argparse.ArgumentParser(usage=usage)
- result.add_argument("--package-root", help="package root", default=None)
result.add_argument("--dart-executable", help="dart executable", default=None)
result.add_argument("--pub-executable", help="pub executable", default=None)
result.add_argument("--directory", help="observatory root", default=None)
@@ -113,9 +112,8 @@
pass
options.pub_snapshot = None
- # We need a dart executable and a package root.
- return (options.package_root is not None and
- options.dart_executable is not None)
+ # We need a dart executable.
+ return (options.dart_executable is not None)
def ChangeDirectory(directory):
os.chdir(directory);
@@ -138,7 +136,6 @@
def PubCommand(dart_executable,
pub_executable,
pub_snapshot,
- pkg_root,
command,
silent):
with open(os.devnull, 'wb') as silent_sink:
@@ -148,7 +145,7 @@
executable = [utils.CheckedInSdkExecutable(), pub_snapshot]
else:
DisplayBootstrapWarning()
- executable = [dart_executable, '--package-root=' + pkg_root, PUB_PATH]
+ executable = [dart_executable, PUB_PATH]
# Prevent the bootstrap Dart executable from running in regular
# development flow.
# REMOVE THE FOLLOWING LINE TO USE the dart_bootstrap binary.
@@ -184,14 +181,12 @@
return PubCommand(options.dart_executable,
options.pub_executable,
options.pub_snapshot,
- options.package_root,
['get', '--offline'],
options.silent)
elif (cmd == 'build'):
return PubCommand(options.dart_executable,
options.pub_executable,
options.pub_snapshot,
- options.package_root,
['build',
'-DOBS_VER=' + utils.GetVersion(),
'--output', args[0]],
@@ -212,8 +207,6 @@
parser.print_help()
return 1
# Calculate absolute paths before changing directory.
- if (options.package_root != None):
- options.package_root = os.path.abspath(options.package_root)
if (options.dart_executable != None):
options.dart_executable = os.path.abspath(options.dart_executable)
if (options.pub_executable != None):
diff --git a/tools/testing/dart/http_server.dart b/tools/testing/dart/http_server.dart
index 82f45cc..5213dae 100644
--- a/tools/testing/dart/http_server.dart
+++ b/tools/testing/dart/http_server.dart
@@ -9,13 +9,10 @@
import 'dart:convert' show HtmlEscape;
-import 'path.dart';
import 'test_suite.dart'; // For TestUtils.
-// TODO(efortuna): Rewrite to not use the args library and simply take an
-// expected number of arguments, so test.dart doesn't rely on the args library?
-// See discussion on https://codereview.chromium.org/11931025/.
import 'vendored_pkg/args/args.dart';
import 'utils.dart';
+import 'package:package_resolver/package_resolver.dart';
class DispatchingServer {
HttpServer server;
@@ -52,9 +49,10 @@
/// directory (i.e. '$DartDirectory/X').
/// /root_build/X: This will serve the corresponding file from the build
/// directory (i.e. '$BuildDirectory/X').
-/// /FOO/packages/BAR: This will serve the corresponding file from the packages
-/// directory (i.e. '$BuildDirectory/packages/BAR') or the
-/// passed-in package root
+/// /FOO/packages/PAZ/BAR: This will serve files from the packages listed in
+/// the package spec .packages. Supports a package
+/// root or custom package spec, and uses [dart_dir]/.packages
+/// as the default. This will serve file lib/BAR from the package PAZ.
/// /ws: This will upgrade the connection to a WebSocket connection and echo
/// all data back to the client.
///
@@ -64,10 +62,6 @@
const PREFIX_BUILDDIR = 'root_build';
const PREFIX_DARTDIR = 'root_dart';
-// TODO(kustermann,ricow): We could change this to the following scheme:
-// http://host:port/root_packages/X -> $BuildDir/packages/X
-// Issue: 8368
-
main(List<String> arguments) {
// This script is in [dart]/tools/testing/dart.
TestUtils.setDartDirUri(Platform.script.resolve('../../..'));
@@ -97,7 +91,7 @@
if (args['help']) {
print(parser.getUsage());
} else {
- var servers = new TestingServers(new Path(args['build-directory']),
+ var servers = new TestingServers(args['build-directory'],
args['csp'], args['runtime'], null, args['package-root'],
args['packages']);
var port = int.parse(args['port']);
@@ -129,26 +123,35 @@
];
List _serverList = [];
- Path _buildDirectory = null;
- Path _dartDirectory = null;
- Path _packageRoot;
- Path _packages;
+ Uri _buildDirectory = null;
+ Uri _dartDirectory = null;
+ Uri _packageRoot;
+ Uri _packages;
final bool useContentSecurityPolicy;
final String runtime;
DispatchingServer _server;
+ SyncPackageResolver _resolver;
- TestingServers(Path buildDirectory, this.useContentSecurityPolicy,
+ TestingServers(String buildDirectory, this.useContentSecurityPolicy,
[String this.runtime = 'none',
String dartDirectory,
String packageRoot,
String packages]) {
- _buildDirectory = TestUtils.absolutePath(buildDirectory);
- _dartDirectory =
- dartDirectory == null ? TestUtils.dartDir : new Path(dartDirectory);
- _packageRoot = packageRoot == null
- ? (packages == null ? _buildDirectory.append('packages') : null)
- : new Path(packageRoot);
- _packages = packages == null ? null : new Path(packages);
+ _buildDirectory = Uri.base.resolveUri(new Uri.directory(buildDirectory));
+ if (dartDirectory == null) {
+ _dartDirectory = TestUtils.dartDirUri;
+ } else {
+ _dartDirectory = Uri.base.resolveUri(new Uri.directory(dartDirectory));
+ }
+ if (packageRoot == null ) {
+ if (packages == null ) {
+ _packages = _dartDirectory.resolve('.packages');
+ } else {
+ _packages = new Uri.file(packages);
+ }
+ } else {
+ _packageRoot = new Uri.directory(packageRoot);
+ }
}
int get port => _serverList[0].port;
@@ -163,23 +166,37 @@
* "Access-Control-Allow-Origin: client:port1
* "Access-Control-Allow-Credentials: true"
*/
- Future startServers(String host, {int port: 0, int crossOriginPort: 0}) {
- return _startHttpServer(host, port: port).then((server) {
- _server = server;
- return _startHttpServer(host,
- port: crossOriginPort, allowedPort: _serverList[0].port);
- });
+ Future startServers(String host,
+ {int port: 0,
+ int crossOriginPort: 0}) async {
+ if (_packages != null) {
+ _resolver = await SyncPackageResolver.loadConfig(_packages);
+ } else {
+ _resolver = new SyncPackageResolver.root(_packageRoot);
+ }
+ _server = await _startHttpServer(host, port: port);
+ await _startHttpServer(host, port: crossOriginPort,
+ allowedPort: _serverList[0].port);
}
String httpServerCommandline() {
var dart = Platform.resolvedExecutable;
- var dartDir = TestUtils.dartDir;
- var script = dartDir.join(new Path("tools/testing/dart/http_server.dart"));
- var buildDirectory = _buildDirectory.toNativePath();
- var csp = useContentSecurityPolicy ? '--csp ' : '';
- return '$dart $script -p $port -c $crossOriginPort $csp'
- '--build-directory=$buildDirectory --runtime=$runtime '
- '--package-root=$_packageRoot';
+ var script = _dartDirectory.resolve('tools/testing/dart/http_server.dart');
+ var buildDirectory = _buildDirectory.toFilePath();
+ var command = [dart, script.toFilePath(),
+ '-p', port,
+ '-c', crossOriginPort,
+ '--build-directory=$buildDirectory',
+ '--runtime=$runtime'];
+ if (useContentSecurityPolicy) {
+ command.add('--csp');
+ }
+ if (_packages != null) {
+ command.add('--packages=${_packages.toFilePath()}');
+ } else if (_packageRoot != null) {
+ command.add('--package-root=${_packageRoot.toFilePath()}');
+ }
+ return command.join(' ');
}
void stopServers() {
@@ -208,30 +225,24 @@
});
}
- void _handleFileOrDirectoryRequest(HttpRequest request, int allowedPort) {
+ _handleFileOrDirectoryRequest(HttpRequest request,
+ int allowedPort) async {
// Enable browsers to cache file/directory responses.
var response = request.response;
response.headers
.set("Cache-Control", "max-age=$_CACHE_EXPIRATION_IN_SECONDS");
- var path = _getFilePathFromRequestPath(request.uri.path);
+ var path = _getFileUriFromRequestUri(request.uri);
if (path != null) {
- var file = new File(path.toNativePath());
- file.exists().then((exists) {
- if (exists) {
- _sendFileContent(request, response, allowedPort, path, file);
- } else {
- var directory = new Directory(path.toNativePath());
- directory.exists().then((exists) {
- if (exists) {
- _listDirectory(directory).then((entries) {
- _sendDirectoryListing(entries, request, response);
- });
- } else {
- _sendNotFound(request);
- }
- });
- }
- });
+ var file = new File.fromUri(path);
+ var directory = new Directory.fromUri(path);
+ if (await file.exists()){
+ _sendFileContent(request, response, allowedPort, file);
+ } else if (await directory.exists()) {
+ _sendDirectoryListing(
+ await _listDirectory(directory), request, response);
+ } else {
+ _sendNotFound(request);
+ }
} else {
if (request.uri.path == '/') {
var entries = [
@@ -277,33 +288,21 @@
});
}
- Path _getFilePathFromRequestPath(String urlRequestPath) {
+ Uri _getFileUriFromRequestUri(Uri request) {
// Go to the top of the file to see an explanation of the URL path scheme.
- var requestPath = new Path(urlRequestPath.substring(1)).canonicalize();
- var pathSegments = requestPath.segments();
- if (pathSegments.length > 0) {
- var basePath;
- var relativePath;
- if (pathSegments[0] == PREFIX_BUILDDIR) {
- basePath = _buildDirectory;
- relativePath = new Path(pathSegments.skip(1).join('/'));
- } else if (pathSegments[0] == PREFIX_DARTDIR) {
- basePath = _dartDirectory;
- relativePath = new Path(pathSegments.skip(1).join('/'));
- }
- var packagesIndex = pathSegments.indexOf('packages');
- if (packagesIndex != -1) {
- if (_packages != null) {
- // TODO(27065): Package spec file not supported by http server yet
- return null;
- }
- var start = packagesIndex + 1;
- basePath = _packageRoot;
- relativePath = new Path(pathSegments.skip(start).join('/'));
- }
- if (basePath != null && relativePath != null) {
- return basePath.join(relativePath);
- }
+ List<String> pathSegments = request.normalizePath().pathSegments;
+ if (pathSegments.length == 0) return null;
+ int packagesIndex = pathSegments.indexOf('packages');
+ if (packagesIndex != -1) {
+ var packageUri = new Uri(scheme: 'package',
+ pathSegments: pathSegments.skip(packagesIndex + 1));
+ return _resolver.resolveUri(packageUri);
+ }
+ if (pathSegments[0] == PREFIX_BUILDDIR) {
+ return _buildDirectory.resolve(pathSegments.skip(1).join('/'));
+ }
+ if (pathSegments[0] == PREFIX_DARTDIR) {
+ return _dartDirectory.resolve(pathSegments.skip(1).join('/'));
}
return null;
}
@@ -313,11 +312,13 @@
var entries = [];
directory.list().listen((FileSystemEntity fse) {
- var filename = new Path(fse.path).filename;
+ var segments = fse.uri.pathSegments;
if (fse is File) {
+ var filename = segments.last;
entries.add(new _Entry(filename, filename));
} else if (fse is Directory) {
- entries.add(new _Entry(filename, '$filename/'));
+ var dirname = segments[segments.length - 2];
+ entries.add(new _Entry(dirname, '$dirname/'));
}
}, onDone: () {
completer.complete(entries);
@@ -348,7 +349,7 @@
response.write(header);
for (var entry in entries) {
response.write(
- '<li><a href="${new Path(request.uri.path).append(entry.name)}">'
+ '<li><a href="${request.uri}/${entry.name}">'
'${entry.displayName}</a></li>');
}
response.write(footer);
@@ -360,7 +361,7 @@
}
void _sendFileContent(HttpRequest request, HttpResponse response,
- int allowedPort, Path path, File file) {
+ int allowedPort, File file) {
if (allowedPort != -1) {
var headerOrigin = request.headers.value('Origin');
var allowedOrigin;
@@ -396,15 +397,15 @@
response.headers.set("X-WebKit-CSP", content_header_value);
}
}
- if (path.filename.endsWith('.html')) {
+ if (file.path.endsWith('.html')) {
response.headers.set('Content-Type', 'text/html');
- } else if (path.filename.endsWith('.js')) {
+ } else if (file.path.endsWith('.js')) {
response.headers.set('Content-Type', 'application/javascript');
- } else if (path.filename.endsWith('.dart')) {
+ } else if (file.path.endsWith('.dart')) {
response.headers.set('Content-Type', 'application/dart');
- } else if (path.filename.endsWith('.css')) {
+ } else if (file.path.endsWith('.css')) {
response.headers.set('Content-Type', 'text/css');
- } else if (path.filename.endsWith('.xml')) {
+ } else if (file.path.endsWith('.xml')) {
response.headers.set('Content-Type', 'text/xml');
}
response.headers.removeAll("X-Frame-Options");
diff --git a/tools/testing/dart/test_configurations.dart b/tools/testing/dart/test_configurations.dart
index 47e233b..f82e62d 100644
--- a/tools/testing/dart/test_configurations.dart
+++ b/tools/testing/dart/test_configurations.dart
@@ -132,11 +132,12 @@
// server for cross-domain tests can be found by calling
// getCrossOriginPortNumber().
var servers = new TestingServers(
- new Path(TestUtils.buildDir(conf)),
+ TestUtils.buildDir(conf),
useContentSecurityPolicy,
conf['runtime'],
null,
- conf['package_root']);
+ conf['package_root'],
+ conf['packages']);
serverFutures.add(servers.startServers(conf['local_ip'],
port: conf['test_server_port'],
crossOriginPort: conf['test_server_cross_origin_port']));
diff --git a/tools/testing/dart/test_runner.dart b/tools/testing/dart/test_runner.dart
index f8570c0..b640ce3 100644
--- a/tools/testing/dart/test_runner.dart
+++ b/tools/testing/dart/test_runner.dart
@@ -135,7 +135,7 @@
String get reproductionCommand {
var env = new StringBuffer();
- environmentOverrides.forEach((key, value) =>
+ environmentOverrides?.forEach((key, value) =>
(io.Platform.operatingSystem == 'windows')
? env.write('set $key=${escapeCommandLineArgument(value)} & ')
: env.write('$key=${escapeCommandLineArgument(value)} '));
@@ -2928,7 +2928,7 @@
cancelDebugTimer();
_debugTimer = new Timer(debugTimerDuration, () {
print("The debug timer of test.dart expired. Please report this issue"
- " to ricow/whesse and provide the following information:");
+ " to whesse@ and provide the following information:");
print("");
print("Graph is sealed: ${_graph.isSealed}");
print("");
diff --git a/tools/testing/dart/test_suite.dart b/tools/testing/dart/test_suite.dart
index 183be62..f5707b8 100644
--- a/tools/testing/dart/test_suite.dart
+++ b/tools/testing/dart/test_suite.dart
@@ -956,6 +956,7 @@
// pubspec.yaml file and if so, create a custom package root for it.
List<Command> baseCommands = <Command>[];
Path packageRoot;
+ Path packages;
if (configuration['use_repository_packages'] ||
configuration['use_public_packages']) {
Path pubspecYamlFile = _findPubspecYamlFile(filePath);
@@ -995,11 +996,11 @@
multiHtmlTestExpectations[fullTestName] =
testExpectations.expectations(fullTestName);
}
- enqueueBrowserTest(baseCommands, packageRoot, info, testName,
+ enqueueBrowserTest(baseCommands, packageRoot, packages, info, testName,
multiHtmlTestExpectations);
} else {
enqueueBrowserTest(
- baseCommands, packageRoot, info, testName, expectations);
+ baseCommands, packageRoot, packages, info, testName, expectations);
}
} else {
enqueueStandardTest(baseCommands, info, testName, expectations);
@@ -1200,7 +1201,7 @@
* compilation and many browser runs).
*/
void enqueueBrowserTest(List<Command> baseCommands, Path packageRoot,
- TestInformation info, String testName, expectations) {
+ Path packages, TestInformation info, String testName, expectations) {
RegExp badChars = new RegExp('[-=/]');
List VmOptionsList = getVmOptions(info.optionsFromFile);
bool multipleOptions = VmOptionsList.length > 1;
@@ -1208,14 +1209,15 @@
String optionsName =
multipleOptions ? vmOptions.join('-').replaceAll(badChars, '') : '';
String tempDir = createOutputDirectory(info.filePath, optionsName);
- enqueueBrowserTestWithOptions(baseCommands, packageRoot, info, testName,
- expectations, vmOptions, tempDir);
+ enqueueBrowserTestWithOptions(baseCommands, packageRoot, packages,
+ info, testName, expectations, vmOptions, tempDir);
}
}
void enqueueBrowserTestWithOptions(
List<Command> baseCommands,
Path packageRoot,
+ Path packages,
TestInformation info,
String testName,
expectations,
@@ -1584,13 +1586,12 @@
String packagesArgument(String packageRootFromFile,
String packagesFromFile) {
if (packagesFromFile != null) {
- return "--packages=$packagesFromFile";
+ return '--packages=$packagesFromFile';
+ } else if (packageRootFromFile != null && packageRootFromFile != 'none') {
+ return '--package-root=$packageRootFromFile';
+ } else {
+ return null;
}
- if (packageRootFromFile == "none") {
- return null;
- }
- packageRootFromFile ??= "$buildDir/packages/";
- return "--package-root=$packageRootFromFile";
}
/**
@@ -1843,7 +1844,7 @@
recursive: true);
void enqueueBrowserTest(List<Command> baseCommands, Path packageRoot,
- TestInformation info, String testName, expectations) {
+ packages, TestInformation info, String testName, expectations) {
String runtime = configuration['runtime'];
Path filePath = info.filePath;
Path dir = filePath.directoryPath;
@@ -1852,7 +1853,7 @@
File customHtml = new File(customHtmlPath.toNativePath());
if (!customHtml.existsSync()) {
super.enqueueBrowserTest(
- baseCommands, packageRoot, info, testName, expectations);
+ baseCommands, packageRoot, packages, info, testName, expectations);
} else {
Path relativeHtml = customHtmlPath.relativeTo(TestUtils.dartDir);
List<Command> commands = []..addAll(baseCommands);
diff --git a/utils/analysis_server/analysis_server.gyp b/utils/analysis_server/analysis_server.gyp
index 1708ad7..45251b5 100644
--- a/utils/analysis_server/analysis_server.gyp
+++ b/utils/analysis_server/analysis_server.gyp
@@ -9,7 +9,6 @@
'type': 'none',
'dependencies': [
'../../runtime/dart-runtime.gyp:dart',
- '../../pkg/pkg.gyp:pkg_packages',
'../../pkg/pkg_files.gyp:pkg_files_stamp'
],
'actions': [
@@ -27,7 +26,6 @@
'action': [
'<(PRODUCT_DIR)/<(EXECUTABLE_PREFIX)dart<(EXECUTABLE_SUFFIX)',
'--snapshot=<(SHARED_INTERMEDIATE_DIR)/analysis_server.dart.snapshot',
- '--package-root=<(PRODUCT_DIR)/packages/',
'../../pkg/analysis_server/bin/server.dart',
],
},
diff --git a/utils/compiler/compiler.gyp b/utils/compiler/compiler.gyp
index f57ad90..23fa405 100644
--- a/utils/compiler/compiler.gyp
+++ b/utils/compiler/compiler.gyp
@@ -12,7 +12,6 @@
'type': 'none',
'dependencies': [
'../../runtime/dart-runtime.gyp:dart',
- '../../pkg/pkg.gyp:pkg_packages',
'dart2js_files_stamp',
],
'actions': [
@@ -36,7 +35,6 @@
'create_snapshot.dart',
'--output_dir=<(SHARED_INTERMEDIATE_DIR)',
'--dart2js_main=pkg/compiler/lib/src/dart2js.dart',
- '--package_root=<(PRODUCT_DIR)/packages/',
],
},
],
diff --git a/utils/compiler/create_snapshot.dart b/utils/compiler/create_snapshot.dart
index 1a27431..2b5b869 100644
--- a/utils/compiler/create_snapshot.dart
+++ b/utils/compiler/create_snapshot.dart
@@ -61,10 +61,9 @@
writer.close();
}
-Future createSnapshot(var dart_file, var packageRoot) {
+Future createSnapshot(var dart_file) {
return Process.run(Platform.executable,
- ["--package-root=$packageRoot",
- "--snapshot=$dart_file.snapshot",
+ ["--snapshot=$dart_file.snapshot",
dart_file])
.then((result) {
if (result.exitCode != 0) {
@@ -80,11 +79,9 @@
* Takes the following arguments:
* --output_dir=val The full path to the output_dir.
* --dart2js_main=val The path to the dart2js main script relative to root.
- * --package-root=val The package-root used to find packages for the snapshot.
*/
void main(List<String> arguments) {
- var validArguments = ["--output_dir", "--dart2js_main",
- "--package_root"];
+ var validArguments = ["--output_dir", "--dart2js_main"];
var args = {};
for (var argument in arguments) {
var argumentSplit = argument.split("=");
@@ -96,7 +93,6 @@
}
if (!args.containsKey("dart2js_main")) throw "Please specify dart2js_main";
if (!args.containsKey("output_dir")) throw "Please specify output_dir";
- if (!args.containsKey("package_root")) throw "Please specify package_root";
var scriptFile = Uri.base.resolveUri(Platform.script);
var path = scriptFile.resolve(".");
@@ -104,13 +100,13 @@
getSnapshotGenerationFile(args, rootPath).then((result) {
var wrapper = "${args['output_dir']}/utils_wrapper.dart";
writeSnapshotFile(wrapper, result);
- createSnapshot(wrapper, args["package_root"]);
+ createSnapshot(wrapper);
});
getDart2jsSnapshotGenerationFile(args, rootPath).then((result) {
var wrapper = "${args['output_dir']}/dart2js.dart";
writeSnapshotFile(wrapper, result);
- createSnapshot(wrapper, args["package_root"]);
+ createSnapshot(wrapper);
});
}
diff --git a/utils/dartanalyzer/dartanalyzer.gyp b/utils/dartanalyzer/dartanalyzer.gyp
index f23d464..0b7e8a0 100644
--- a/utils/dartanalyzer/dartanalyzer.gyp
+++ b/utils/dartanalyzer/dartanalyzer.gyp
@@ -9,7 +9,6 @@
'type': 'none',
'dependencies': [
'../../runtime/dart-runtime.gyp:dart',
- '../../pkg/pkg.gyp:pkg_packages',
],
'actions': [
{
@@ -27,12 +26,11 @@
'action': [
'<(PRODUCT_DIR)/<(EXECUTABLE_PREFIX)dart<(EXECUTABLE_SUFFIX)',
'--snapshot=<(SHARED_INTERMEDIATE_DIR)/dartanalyzer.dart.snapshot',
- '--package-root=<(PRODUCT_DIR)/packages/',
'../../pkg/analyzer_cli/bin/analyzer.dart',
],
},
{
- 'action_name': 'generate_summary_bundle',
+ 'action_name': 'generate_summary_spec',
'inputs': [
'<(PRODUCT_DIR)/<(EXECUTABLE_PREFIX)dart<(EXECUTABLE_SUFFIX)',
'<(SHARED_INTERMEDIATE_DIR)/packages.stamp',
@@ -40,47 +38,30 @@
'<!@(["python", "../../tools/list_files.py", "\\.dart$", "../../pkg/analyzer"])',
],
'outputs': [
- '<(SHARED_INTERMEDIATE_DIR)/sdk_summary_bundle.bin',
- ],
- 'action': [
- '<(PRODUCT_DIR)/<(EXECUTABLE_PREFIX)dart<(EXECUTABLE_SUFFIX)',
- '--package-root=<(PRODUCT_DIR)/packages/',
- '../../pkg/analyzer/tool/summary/build_sdk_summaries.dart',
- 'single-output',
- '<(SHARED_INTERMEDIATE_DIR)/sdk_summary_bundle.bin',
- ],
- },
- {
- 'action_name': 'extract_spec_summary',
- 'inputs': [
- '<(SHARED_INTERMEDIATE_DIR)/sdk_summary_bundle.bin',
- ],
- 'outputs': [
'<(SHARED_INTERMEDIATE_DIR)/spec.sum',
],
'action': [
'<(PRODUCT_DIR)/<(EXECUTABLE_PREFIX)dart<(EXECUTABLE_SUFFIX)',
- '--package-root=<(PRODUCT_DIR)/packages/',
'../../pkg/analyzer/tool/summary/build_sdk_summaries.dart',
- 'extract-spec-sum',
- '<(SHARED_INTERMEDIATE_DIR)/sdk_summary_bundle.bin',
+ 'build-spec',
'<(SHARED_INTERMEDIATE_DIR)/spec.sum',
],
},
{
- 'action_name': 'extract_strong_summary',
+ 'action_name': 'generate_summary_strong',
'inputs': [
- '<(SHARED_INTERMEDIATE_DIR)/sdk_summary_bundle.bin',
+ '<(PRODUCT_DIR)/<(EXECUTABLE_PREFIX)dart<(EXECUTABLE_SUFFIX)',
+ '<(SHARED_INTERMEDIATE_DIR)/packages.stamp',
+ '<!@(["python", "../../tools/list_files.py", "\\.dart$", "../../sdk/lib"])',
+ '<!@(["python", "../../tools/list_files.py", "\\.dart$", "../../pkg/analyzer"])',
],
'outputs': [
'<(SHARED_INTERMEDIATE_DIR)/strong.sum',
],
'action': [
'<(PRODUCT_DIR)/<(EXECUTABLE_PREFIX)dart<(EXECUTABLE_SUFFIX)',
- '--package-root=<(PRODUCT_DIR)/packages/',
'../../pkg/analyzer/tool/summary/build_sdk_summaries.dart',
- 'extract-strong-sum',
- '<(SHARED_INTERMEDIATE_DIR)/sdk_summary_bundle.bin',
+ 'build-strong',
'<(SHARED_INTERMEDIATE_DIR)/strong.sum',
],
},
diff --git a/utils/dartdevc/dartdevc.gyp b/utils/dartdevc/dartdevc.gyp
index c945a37..b511c65 100644
--- a/utils/dartdevc/dartdevc.gyp
+++ b/utils/dartdevc/dartdevc.gyp
@@ -9,7 +9,6 @@
'type': 'none',
'dependencies': [
'../../runtime/dart-runtime.gyp:dart',
- '../../pkg/pkg.gyp:pkg_packages',
],
'actions': [
{
@@ -27,7 +26,6 @@
'action': [
'<(PRODUCT_DIR)/<(EXECUTABLE_PREFIX)dart<(EXECUTABLE_SUFFIX)',
'--snapshot=<(SHARED_INTERMEDIATE_DIR)/dartdevc.dart.snapshot',
- '--package-root=<(PRODUCT_DIR)/packages/',
'../../pkg/dev_compiler/bin/dartdevc.dart'
],
},
diff --git a/utils/dartdoc/dartdoc.gyp b/utils/dartdoc/dartdoc.gyp
index 73c4fa4..ae1a48d 100644
--- a/utils/dartdoc/dartdoc.gyp
+++ b/utils/dartdoc/dartdoc.gyp
@@ -9,7 +9,6 @@
'type': 'none',
'dependencies': [
'../../runtime/dart-runtime.gyp:dart',
- '../../pkg/pkg.gyp:pkg_packages',
],
'actions': [
{
@@ -26,7 +25,6 @@
'action': [
'<(PRODUCT_DIR)/<(EXECUTABLE_PREFIX)dart<(EXECUTABLE_SUFFIX)',
'--snapshot=<(SHARED_INTERMEDIATE_DIR)/dartdoc.dart.snapshot',
- '--package-root=<(PRODUCT_DIR)/packages/',
'../../third_party/pkg/dartdoc/bin/dartdoc.dart',
],
},
diff --git a/utils/dartfmt/dartfmt.gyp b/utils/dartfmt/dartfmt.gyp
index 62b8906..76c83f1 100644
--- a/utils/dartfmt/dartfmt.gyp
+++ b/utils/dartfmt/dartfmt.gyp
@@ -9,7 +9,6 @@
'type': 'none',
'dependencies': [
'../../runtime/dart-runtime.gyp:dart',
- '../../pkg/pkg.gyp:pkg_packages',
],
'actions': [
{
@@ -26,7 +25,6 @@
'action': [
'<(PRODUCT_DIR)/<(EXECUTABLE_PREFIX)dart<(EXECUTABLE_SUFFIX)',
'--snapshot=<(SHARED_INTERMEDIATE_DIR)/dartfmt.dart.snapshot',
- '--package-root=<(PRODUCT_DIR)/packages/',
'../../third_party/pkg_tested/dart_style/bin/format.dart',
],
},
diff --git a/utils/pub/pub.gyp b/utils/pub/pub.gyp
index 146a505..e472be9 100644
--- a/utils/pub/pub.gyp
+++ b/utils/pub/pub.gyp
@@ -9,7 +9,6 @@
'type': 'none',
'dependencies': [
'../../runtime/dart-runtime.gyp:dart',
- '../../pkg/pkg.gyp:pkg_packages',
'../../pkg/pkg_files.gyp:pkg_files_stamp',
'../../utils/compiler/compiler.gyp:dart2js_files_stamp'
],
@@ -28,7 +27,6 @@
],
'action': [
'<(PRODUCT_DIR)/<(EXECUTABLE_PREFIX)dart<(EXECUTABLE_SUFFIX)',
- '--package-root=<(PRODUCT_DIR)/packages/',
'--snapshot=<(SHARED_INTERMEDIATE_DIR)/pub.dart.snapshot',
'../../third_party/pkg/pub/bin/pub.dart',
]