Version 2.0.0-dev.43.0
Merge commit 'bc75856e5487016fa00d42cd5dbc065b4fcc2449' into dev
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d4b346a..d4faca9 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,7 +1,31 @@
+## 2.0.0-dev.43.0
+
## 2.0.0-dev.42.0
+### Core library changes
+
+* `dart:collection`
+ * Removed `Maps` class. Extend `MapBase` or mix in `MapMixin` instead to
+ provide map method implementations for a class.
+
### Tool Changes
+#### dart2js
+
+* Fixed bug where dart2js crashed when invoked from `pub build` and `pub serve`
+ when given files that contain non-ASCII characters ([issue 32561][sdk#32561]).
+
+* Fixed `--no-frequency-based-minification`, which was not working together with
+ the common front-end ([issue 32600][sdk#32600]).
+
+* Support `--categories=Server` with the common front-end. This included also
+ fixes for the constant value `bool.fromEnvironment("*")` of
+ "dart.libraries.io", "dart.libraries.mirrors", "dart.libraries.isolate", and
+ "dart.libraries.html".
+
+[sdk#32561]: https://github.com/dart-lang/sdk/issues/32561
+[sdk#32600]: https://github.com/dart-lang/sdk/issues/32600
+
#### Pub
* Pub will now automatically retry HTTP requests that fail with an IO error
@@ -33,7 +57,7 @@
### Tool Changes
#### Pub
-* fixed bug in dart2js transformer when using the common front-end.
+* Fixed bug in dart2js transformer when using the common front-end.
## 2.0.0-dev.37.0
### Tool Changes
diff --git a/DEPS b/DEPS
index 21cf9a2..ac24008 100644
--- a/DEPS
+++ b/DEPS
@@ -84,7 +84,7 @@
# For more details, see https://github.com/dart-lang/sdk/issues/30164
"dart_style_tag": "@1.0.10", # Please see the note above before updating.
- "dartdoc_tag" : "@v0.17.1+1",
+ "dartdoc_tag" : "@v0.18.0",
"fixnum_tag": "@0.10.5",
"func_rev": "@25eec48146a58967d75330075ab376b3838b18a8",
"glob_tag": "@1.1.5",
@@ -100,7 +100,7 @@
"isolate_tag": "@1.1.0",
"jinja2_rev": "@2222b31554f03e62600cd7e383376a7c187967a1",
"json_rpc_2_tag": "@2.0.6",
- "linter_tag": "@0.1.45",
+ "linter_tag": "@0.1.46",
"logging_tag": "@0.11.3+1",
"markdown_tag": "@1.1.1",
"matcher_tag": "@0.12.1+4",
@@ -136,7 +136,7 @@
"test_descriptor_tag": "@1.0.3",
"test_process_tag": "@1.0.1",
"term_glyph_tag": "@1.0.0",
- "test_reflective_loader_tag": "@0.1.3",
+ "test_reflective_loader_tag": "@0.1.4",
"test_tag": "@0.12.30+1",
"tuple_tag": "@v1.0.1",
"typed_data_tag": "@1.1.3",
diff --git a/dartdoc_options.yaml b/dartdoc_options.yaml
new file mode 100644
index 0000000..4e73e84
--- /dev/null
+++ b/dartdoc_options.yaml
@@ -0,0 +1,2 @@
+dartdoc:
+ categoryOrder: ["VM", "Web"]
diff --git a/docs/language/dartLangSpec.tex b/docs/language/dartLangSpec.tex
index 51a6dc7..b30b562 100644
--- a/docs/language/dartLangSpec.tex
+++ b/docs/language/dartLangSpec.tex
@@ -6415,11 +6415,9 @@
\LMHash{}
The static type of an multiplicative expression is usually determined by the signature given in the declaration of the operator used.
-However, invocations of the operators \code{*}, \code{\%} and \code{\~{}/} of class \code{int} are treated specially by the typechecker.
+However, invocations of the operators \code{*} and \code{\%} of class \code{int} are treated specially by the typechecker.
The static type of an expression $e_1 * e_2$ where $e_1$ has static type \code{int} is \code{int} if the static type of $e_2$ is \code{int}, and \code{double} if the static type of $e_2$ is \code{double}.
The static type of an expression $e_1 \% e_2$ where $e_1$ has static type \code{int} is \code{int} if the static type of $e_2$ is \code{int}, and \code{double} if the static type of $e_2$ is \code{double}.
-The static type of an expression \code{$e_1$ \~{}/ $e_2$} where $e_1$ has static type \code{int} is \code{int} if the static type of $e_2$ is \code{int}.
-
\subsection{Unary Expressions}
\LMLabel{unaryExpressions}
diff --git a/pkg/analysis_server/doc/api.html b/pkg/analysis_server/doc/api.html
index 2338bbe..c6a313e 100644
--- a/pkg/analysis_server/doc/api.html
+++ b/pkg/analysis_server/doc/api.html
@@ -3920,7 +3920,7 @@
An enumeration of the kinds of refactorings that can be created.
</p>
- <dl><dt class="value">CONVERT_GETTER_TO_METHOD</dt><dt class="value">CONVERT_METHOD_TO_GETTER</dt><dt class="value">EXTRACT_LOCAL_VARIABLE</dt><dt class="value">EXTRACT_METHOD</dt><dt class="value">EXTRACT_WIDGET</dt><dt class="value">INLINE_LOCAL_VARIABLE</dt><dt class="value">INLINE_METHOD</dt><dt class="value">MOVE_FILE</dt><dt class="value">RENAME</dt><dt class="value">SORT_MEMBERS</dt></dl></dd><dt class="typeDefinition"><a name="type_RefactoringMethodParameter">RefactoringMethodParameter: object</a></dt><dd>
+ <dl><dt class="value">CONVERT_GETTER_TO_METHOD</dt><dt class="value">CONVERT_METHOD_TO_GETTER</dt><dt class="value">EXTRACT_LOCAL_VARIABLE</dt><dt class="value">EXTRACT_METHOD</dt><dt class="value">EXTRACT_WIDGET</dt><dt class="value">INLINE_LOCAL_VARIABLE</dt><dt class="value">INLINE_METHOD</dt><dt class="value">MOVE_FILE</dt><dt class="value">RENAME</dt></dl></dd><dt class="typeDefinition"><a name="type_RefactoringMethodParameter">RefactoringMethodParameter: object</a></dt><dd>
<p>
A description of a parameter in a method refactoring.
@@ -4687,9 +4687,9 @@
</p>
</dd></dl></dd><dt class="refactoring">EXTRACT_WIDGET</dt><dd>
<p>
- Create a new class that extends either StatelessWidget or StatefulWidget,
- whose build() method is the widget creation expression, or a method
- returning a Flutter widget, at the specified offset.
+ Create a new class that extends StatelessWidget, whose build() method is
+ the widget creation expression, or a method returning a Flutter widget,
+ at the specified offset.
</p>
@@ -4698,11 +4698,6 @@
<p>
The name that the widget class should be given.
</p>
- </dd><dt class="field"><b>stateful: bool</b></dt><dd>
-
- <p>
- True if a StatefulWidget should be created.
- </p>
</dd></dl></dd><dt class="refactoring">INLINE_LOCAL_VARIABLE</dt><dd>
<p>
Inline the initializer expression of a local variable in
diff --git a/pkg/analysis_server/lib/protocol/protocol_generated.dart b/pkg/analysis_server/lib/protocol/protocol_generated.dart
index 3a6949a..6bcff1b 100644
--- a/pkg/analysis_server/lib/protocol/protocol_generated.dart
+++ b/pkg/analysis_server/lib/protocol/protocol_generated.dart
@@ -10944,7 +10944,6 @@
*
* {
* "name": String
- * "stateful": bool
* }
*
* Clients may not extend, implement or mix-in this class.
@@ -10952,8 +10951,6 @@
class ExtractWidgetOptions extends RefactoringOptions {
String _name;
- bool _stateful;
-
/**
* The name that the widget class should be given.
*/
@@ -10967,22 +10964,8 @@
this._name = value;
}
- /**
- * True if a StatefulWidget should be created.
- */
- bool get stateful => _stateful;
-
- /**
- * True if a StatefulWidget should be created.
- */
- void set stateful(bool value) {
- assert(value != null);
- this._stateful = value;
- }
-
- ExtractWidgetOptions(String name, bool stateful) {
+ ExtractWidgetOptions(String name) {
this.name = name;
- this.stateful = stateful;
}
factory ExtractWidgetOptions.fromJson(
@@ -10997,14 +10980,7 @@
} else {
throw jsonDecoder.mismatch(jsonPath, "name");
}
- bool stateful;
- if (json.containsKey("stateful")) {
- stateful =
- jsonDecoder.decodeBool(jsonPath + ".stateful", json["stateful"]);
- } else {
- throw jsonDecoder.mismatch(jsonPath, "stateful");
- }
- return new ExtractWidgetOptions(name, stateful);
+ return new ExtractWidgetOptions(name);
} else {
throw jsonDecoder.mismatch(jsonPath, "extractWidget options", json);
}
@@ -11020,7 +10996,6 @@
Map<String, dynamic> toJson() {
Map<String, dynamic> result = {};
result["name"] = name;
- result["stateful"] = stateful;
return result;
}
@@ -11030,7 +11005,7 @@
@override
bool operator ==(other) {
if (other is ExtractWidgetOptions) {
- return name == other.name && stateful == other.stateful;
+ return name == other.name;
}
return false;
}
@@ -11039,7 +11014,6 @@
int get hashCode {
int hash = 0;
hash = JenkinsSmiHash.combine(hash, name.hashCode);
- hash = JenkinsSmiHash.combine(hash, stateful.hashCode);
return JenkinsSmiHash.finish(hash);
}
}
@@ -11114,7 +11088,9 @@
* "variableName": optional String
* "children": optional List<FlutterOutline>
* "id": optional int
+ * "isWidgetClass": optional bool
* "renderConstructor": optional String
+ * "stateClassName": optional String
* "stateOffset": optional int
* "stateLength": optional int
* }
@@ -11148,8 +11124,12 @@
int _id;
+ bool _isWidgetClass;
+
String _renderConstructor;
+ String _stateClassName;
+
int _stateOffset;
int _stateLength;
@@ -11342,6 +11322,22 @@
}
/**
+ * True if the node is a widget class, so it can potentially be rendered,
+ * even if it does not yet have the rendering constructor. This field is
+ * omitted if the node is not a widget class.
+ */
+ bool get isWidgetClass => _isWidgetClass;
+
+ /**
+ * True if the node is a widget class, so it can potentially be rendered,
+ * even if it does not yet have the rendering constructor. This field is
+ * omitted if the node is not a widget class.
+ */
+ void set isWidgetClass(bool value) {
+ this._isWidgetClass = value;
+ }
+
+ /**
* If the node is a widget class that can be rendered for IDE, the name of
* the constructor that should be used to instantiate the widget. Empty
* string for default constructor. Absent if the node is not a widget class
@@ -11360,15 +11356,29 @@
}
/**
- * If the node is a StatefulWidget that can be rendered, and its State class
- * is defined in the same file, the offset of the State class code in the
+ * If the node is a StatefulWidget, and its state class is defined in the
+ * same file, the name of the state class.
+ */
+ String get stateClassName => _stateClassName;
+
+ /**
+ * If the node is a StatefulWidget, and its state class is defined in the
+ * same file, the name of the state class.
+ */
+ void set stateClassName(String value) {
+ this._stateClassName = value;
+ }
+
+ /**
+ * If the node is a StatefulWidget that can be rendered, and its state class
+ * is defined in the same file, the offset of the state class code in the
* file.
*/
int get stateOffset => _stateOffset;
/**
- * If the node is a StatefulWidget that can be rendered, and its State class
- * is defined in the same file, the offset of the State class code in the
+ * If the node is a StatefulWidget that can be rendered, and its state class
+ * is defined in the same file, the offset of the state class code in the
* file.
*/
void set stateOffset(int value) {
@@ -11376,15 +11386,15 @@
}
/**
- * If the node is a StatefulWidget that can be rendered, and its State class
- * is defined in the same file, the length of the State class code in the
+ * If the node is a StatefulWidget that can be rendered, and its state class
+ * is defined in the same file, the length of the state class code in the
* file.
*/
int get stateLength => _stateLength;
/**
- * If the node is a StatefulWidget that can be rendered, and its State class
- * is defined in the same file, the length of the State class code in the
+ * If the node is a StatefulWidget that can be rendered, and its state class
+ * is defined in the same file, the length of the state class code in the
* file.
*/
void set stateLength(int value) {
@@ -11401,7 +11411,9 @@
String variableName,
List<FlutterOutline> children,
int id,
+ bool isWidgetClass,
String renderConstructor,
+ String stateClassName,
int stateOffset,
int stateLength}) {
this.kind = kind;
@@ -11417,7 +11429,9 @@
this.variableName = variableName;
this.children = children;
this.id = id;
+ this.isWidgetClass = isWidgetClass;
this.renderConstructor = renderConstructor;
+ this.stateClassName = stateClassName;
this.stateOffset = stateOffset;
this.stateLength = stateLength;
}
@@ -11507,11 +11521,21 @@
if (json.containsKey("id")) {
id = jsonDecoder.decodeInt(jsonPath + ".id", json["id"]);
}
+ bool isWidgetClass;
+ if (json.containsKey("isWidgetClass")) {
+ isWidgetClass = jsonDecoder.decodeBool(
+ jsonPath + ".isWidgetClass", json["isWidgetClass"]);
+ }
String renderConstructor;
if (json.containsKey("renderConstructor")) {
renderConstructor = jsonDecoder.decodeString(
jsonPath + ".renderConstructor", json["renderConstructor"]);
}
+ String stateClassName;
+ if (json.containsKey("stateClassName")) {
+ stateClassName = jsonDecoder.decodeString(
+ jsonPath + ".stateClassName", json["stateClassName"]);
+ }
int stateOffset;
if (json.containsKey("stateOffset")) {
stateOffset = jsonDecoder.decodeInt(
@@ -11531,7 +11555,9 @@
variableName: variableName,
children: children,
id: id,
+ isWidgetClass: isWidgetClass,
renderConstructor: renderConstructor,
+ stateClassName: stateClassName,
stateOffset: stateOffset,
stateLength: stateLength);
} else {
@@ -11574,9 +11600,15 @@
if (id != null) {
result["id"] = id;
}
+ if (isWidgetClass != null) {
+ result["isWidgetClass"] = isWidgetClass;
+ }
if (renderConstructor != null) {
result["renderConstructor"] = renderConstructor;
}
+ if (stateClassName != null) {
+ result["stateClassName"] = stateClassName;
+ }
if (stateOffset != null) {
result["stateOffset"] = stateOffset;
}
@@ -11610,7 +11642,9 @@
listEqual(children, other.children,
(FlutterOutline a, FlutterOutline b) => a == b) &&
id == other.id &&
+ isWidgetClass == other.isWidgetClass &&
renderConstructor == other.renderConstructor &&
+ stateClassName == other.stateClassName &&
stateOffset == other.stateOffset &&
stateLength == other.stateLength;
}
@@ -11633,7 +11667,9 @@
hash = JenkinsSmiHash.combine(hash, variableName.hashCode);
hash = JenkinsSmiHash.combine(hash, children.hashCode);
hash = JenkinsSmiHash.combine(hash, id.hashCode);
+ hash = JenkinsSmiHash.combine(hash, isWidgetClass.hashCode);
hash = JenkinsSmiHash.combine(hash, renderConstructor.hashCode);
+ hash = JenkinsSmiHash.combine(hash, stateClassName.hashCode);
hash = JenkinsSmiHash.combine(hash, stateOffset.hashCode);
hash = JenkinsSmiHash.combine(hash, stateLength.hashCode);
return JenkinsSmiHash.finish(hash);
diff --git a/pkg/analysis_server/lib/src/computer/computer_hover.dart b/pkg/analysis_server/lib/src/computer/computer_hover.dart
index 271e6d2..eebfb33 100644
--- a/pkg/analysis_server/lib/src/computer/computer_hover.dart
+++ b/pkg/analysis_server/lib/src/computer/computer_hover.dart
@@ -53,6 +53,10 @@
}
// description
hover.elementDescription = element.toString();
+ if (node is InstanceCreationExpression && node.keyword == null) {
+ String prefix = node.isConst ? '(const) ' : '(new) ';
+ hover.elementDescription = prefix + hover.elementDescription;
+ }
hover.elementKind = element.kind.displayName;
hover.isDeprecated = element.hasDeprecated;
// not local element
diff --git a/pkg/analysis_server/lib/src/computer/computer_outline.dart b/pkg/analysis_server/lib/src/computer/computer_outline.dart
index 3af3413..0508fa7 100644
--- a/pkg/analysis_server/lib/src/computer/computer_outline.dart
+++ b/pkg/analysis_server/lib/src/computer/computer_outline.dart
@@ -221,7 +221,9 @@
isStatic: isStatic),
location: _getLocationNode(nameNode),
parameters: parametersStr,
- returnType: returnTypeStr);
+ returnType: returnTypeStr,
+ typeParameters:
+ _getTypeParametersStr(functionExpression.typeParameters));
List<Outline> contents = _addFunctionBodyOutlines(functionExpression.body);
return _nodeOutline(function, element, contents);
}
@@ -271,7 +273,8 @@
isStatic: method.isStatic),
location: _getLocationNode(nameNode),
parameters: parametersStr,
- returnType: returnTypeStr);
+ returnType: returnTypeStr,
+ typeParameters: _getTypeParametersStr(method.typeParameters));
List<Outline> contents = _addFunctionBodyOutlines(method.body);
return _nodeOutline(method, element, contents);
}
diff --git a/pkg/analysis_server/lib/src/edit/edit_domain.dart b/pkg/analysis_server/lib/src/edit/edit_domain.dart
index 3d0f6d2..d38ee8b 100644
--- a/pkg/analysis_server/lib/src/edit/edit_domain.dart
+++ b/pkg/analysis_server/lib/src/edit/edit_domain.dart
@@ -728,6 +728,7 @@
bool get _requiresOptions {
return refactoring is ExtractLocalRefactoring ||
refactoring is ExtractMethodRefactoring ||
+ refactoring is ExtractWidgetRefactoring ||
refactoring is InlineMethodRefactoring ||
refactoring is RenameRefactoring;
}
@@ -902,6 +903,15 @@
false, <RefactoringMethodParameter>[], <int>[], <int>[]);
}
}
+ if (kind == RefactoringKind.EXTRACT_WIDGET) {
+ CompilationUnit unit = await server.getResolvedCompilationUnit(file);
+ if (unit != null) {
+ var analysisSession = server.getAnalysisDriver(file).currentSession;
+ refactoring = new ExtractWidgetRefactoring(
+ searchEngine, analysisSession, unit, offset);
+ feedback = new ExtractWidgetFeedback();
+ }
+ }
if (kind == RefactoringKind.INLINE_LOCAL_VARIABLE) {
CompilationUnit unit = await server.getResolvedCompilationUnit(file);
if (unit != null) {
@@ -1056,6 +1066,12 @@
extractRefactoring.returnType = extractOptions.returnType;
return extractRefactoring.checkName();
}
+ if (refactoring is ExtractWidgetRefactoring) {
+ ExtractWidgetRefactoring extractRefactoring = this.refactoring;
+ ExtractWidgetOptions extractOptions = params.options;
+ extractRefactoring.name = extractOptions.name;
+ return extractRefactoring.checkName();
+ }
if (refactoring is InlineMethodRefactoring) {
InlineMethodRefactoring inlineRefactoring = this.refactoring;
InlineMethodOptions inlineOptions = params.options;
diff --git a/pkg/analysis_server/lib/src/flutter/flutter_outline_computer.dart b/pkg/analysis_server/lib/src/flutter/flutter_outline_computer.dart
index f786479..56e4162 100644
--- a/pkg/analysis_server/lib/src/flutter/flutter_outline_computer.dart
+++ b/pkg/analysis_server/lib/src/flutter/flutter_outline_computer.dart
@@ -67,7 +67,7 @@
unit.accept(new _FlutterOutlineBuilder(this));
// Compute instrumented code.
- if (widgets.isNotEmpty) {
+ if (widgets.values.any((w) => w.hasDesignTimeConstructor)) {
_rewriteRelativeDirectives();
instrumentationEdits.sort((a, b) => b.offset - a.offset);
instrumentedCode =
@@ -147,7 +147,11 @@
if (dartOutline.element.kind == protocol.ElementKind.CLASS) {
var widget = widgets[dartOutline.element.location.offset];
if (widget != null) {
- flutterOutline.renderConstructor = CONSTRUCTOR_NAME;
+ flutterOutline.isWidgetClass = true;
+ if (widget.hasDesignTimeConstructor) {
+ flutterOutline.renderConstructor = CONSTRUCTOR_NAME;
+ }
+ flutterOutline.stateClassName = widget.state?.name?.name;
flutterOutline.stateOffset = widget.state?.offset;
flutterOutline.stateLength = widget.state?.length;
}
@@ -302,17 +306,17 @@
int nameOffset = widget.name.offset;
var designTimeConstructor = widget.getConstructor(CONSTRUCTOR_NAME);
- if (designTimeConstructor == null) {
- continue;
- }
+ bool hasDesignTimeConstructor = designTimeConstructor != null;
InterfaceType superType = widget.element.supertype;
if (isExactlyStatelessWidgetType(superType)) {
- widgets[nameOffset] = new _WidgetClass(nameOffset);
+ widgets[nameOffset] =
+ new _WidgetClass(nameOffset, hasDesignTimeConstructor);
} else if (isExactlyStatefulWidgetType(superType)) {
ClassDeclaration state = _findState(widget);
if (state != null) {
- widgets[nameOffset] = new _WidgetClass(nameOffset, state);
+ widgets[nameOffset] =
+ new _WidgetClass(nameOffset, hasDesignTimeConstructor, state);
}
}
}
@@ -388,8 +392,11 @@
class _WidgetClass {
final int nameOffset;
+ /// Is `true` if has `forDesignTime` constructor, so can be rendered.
+ final bool hasDesignTimeConstructor;
+
/// If a `StatefulWidget` with the `State` in the same file.
final ClassDeclaration state;
- _WidgetClass(this.nameOffset, [this.state]);
+ _WidgetClass(this.nameOffset, this.hasDesignTimeConstructor, [this.state]);
}
diff --git a/pkg/analysis_server/lib/src/plugin/plugin_manager.dart b/pkg/analysis_server/lib/src/plugin/plugin_manager.dart
index 982e415..89fbbc3 100644
--- a/pkg/analysis_server/lib/src/plugin/plugin_manager.dart
+++ b/pkg/analysis_server/lib/src/plugin/plugin_manager.dart
@@ -805,7 +805,7 @@
if (contents is YamlMap) {
YamlNode dependencies = contents['dependencies'];
if (dependencies is YamlMap) {
- return dependencies.keys;
+ return dependencies.keys.cast<String>();
}
}
return const <String>[];
@@ -1069,7 +1069,7 @@
sendRequest(new PluginShutdownParams());
new Future.delayed(WAIT_FOR_SHUTDOWN_DURATION, () {
if (channel != null) {
- channel.kill();
+ channel?.kill();
channel = null;
}
});
diff --git a/pkg/analysis_server/lib/src/services/refactoring/extract_widget.dart b/pkg/analysis_server/lib/src/services/refactoring/extract_widget.dart
index fae6127..6a0010c 100644
--- a/pkg/analysis_server/lib/src/services/refactoring/extract_widget.dart
+++ b/pkg/analysis_server/lib/src/services/refactoring/extract_widget.dart
@@ -10,6 +10,7 @@
import 'package:analysis_server/src/services/refactoring/naming_conventions.dart';
import 'package:analysis_server/src/services/refactoring/refactoring.dart';
import 'package:analysis_server/src/services/refactoring/refactoring_internal.dart';
+import 'package:analysis_server/src/services/search/element_visitors.dart';
import 'package:analysis_server/src/services/search/search_engine.dart';
import 'package:analysis_server/src/utilities/flutter.dart';
import 'package:analyzer/analyzer.dart';
@@ -18,6 +19,7 @@
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/type.dart';
import 'package:analyzer/src/dart/analysis/session_helper.dart';
+import 'package:analyzer/src/generated/java_core.dart';
import 'package:analyzer/src/generated/source.dart' show SourceRange;
import 'package:analyzer_plugin/utilities/change_builder/change_builder_dart.dart';
import 'package:analyzer_plugin/utilities/range_factory.dart';
@@ -42,9 +44,6 @@
@override
String name;
- @override
- bool stateful = false;
-
/// If [offset] is in a class, the node of this class, `null` otherwise.
ClassDeclaration _enclosingClassNode;
@@ -105,7 +104,25 @@
@override
RefactoringStatus checkName() {
- return validateClassName(name);
+ RefactoringStatus result = new RefactoringStatus();
+
+ // Validate the name.
+ result.addStatus(validateClassName(name));
+
+ // Check for duplicate declarations.
+ if (!result.hasFatalError) {
+ visitLibraryTopLevelElements(libraryElement, (element) {
+ if (hasDisplayName(element, name)) {
+ String message = format(
+ "Library already declares {0} with name '{1}'.",
+ getElementKindName(element),
+ name);
+ result.addError(message, newLocation_fromElement(element));
+ }
+ });
+ }
+
+ return result;
}
@override
@@ -139,8 +156,9 @@
_enclosingClassElement = _enclosingClassNode?.element;
// new MyWidget(...)
- if (node is InstanceCreationExpression && isWidgetCreation(node)) {
- _expression = node;
+ InstanceCreationExpression newExpression = identifyNewExpression(node);
+ if (isWidgetCreation(newExpression)) {
+ _expression = newExpression;
return new RefactoringStatus();
}
@@ -366,6 +384,7 @@
final SourceRange expressionRange;
final RefactoringStatus status = new RefactoringStatus();
+ final Set<Element> uniqueElements = new Set<Element>();
final List<_Parameter> parameters = [];
List<ClassElement> enclosingClasses;
@@ -405,7 +424,7 @@
}
}
- if (type != null) {
+ if (type != null && uniqueElements.add(element)) {
parameters.add(new _Parameter(elementName, type));
}
}
diff --git a/pkg/analysis_server/lib/src/services/refactoring/refactoring.dart b/pkg/analysis_server/lib/src/services/refactoring/refactoring.dart
index e336845..3fe03a8 100644
--- a/pkg/analysis_server/lib/src/services/refactoring/refactoring.dart
+++ b/pkg/analysis_server/lib/src/services/refactoring/refactoring.dart
@@ -241,12 +241,6 @@
void set name(String name);
/**
- * Set to `true` if a subclass of `StatefulWidget` should be extracted,
- * otherwise a subclass of `StatelessWidget` will be extracted.
- */
- void set stateful(bool stateful);
-
- /**
* Validates that the [name] is a valid identifier and is appropriate for a
* class.
*
diff --git a/pkg/analysis_server/lib/src/services/search/hierarchy.dart b/pkg/analysis_server/lib/src/services/search/hierarchy.dart
index 93bb9a8..3f9bb483 100644
--- a/pkg/analysis_server/lib/src/services/search/hierarchy.dart
+++ b/pkg/analysis_server/lib/src/services/search/hierarchy.dart
@@ -58,7 +58,7 @@
Future<Set<ClassElement>> getDirectSubClasses(
SearchEngine searchEngine, ClassElement seed) async {
List<SearchMatch> matches = await searchEngine.searchSubtypes(seed);
- return matches.map((match) => match.element).toSet();
+ return matches.map((match) => match.element).cast<ClassElement>().toSet();
}
/**
diff --git a/pkg/analysis_server/pubspec.yaml b/pkg/analysis_server/pubspec.yaml
index 451bee0..0e1ae08 100644
--- a/pkg/analysis_server/pubspec.yaml
+++ b/pkg/analysis_server/pubspec.yaml
@@ -22,6 +22,5 @@
yaml: any
dev_dependencies:
html: any
- test_reflective_loader: ^0.1.0
- mockito: ^2.0.2
+ test_reflective_loader: ^0.1.4
test: ^0.12.17
diff --git a/pkg/analysis_server/test/analysis/get_hover_test.dart b/pkg/analysis_server/test/analysis/get_hover_test.dart
index 3a74968..35cc310 100644
--- a/pkg/analysis_server/test/analysis/get_hover_test.dart
+++ b/pkg/analysis_server/test/analysis/get_hover_test.dart
@@ -549,6 +549,58 @@
}
}
+ test_instanceCreation_noKeyword_const() async {
+ addTestFile('''
+library my.library;
+class A {
+ const A(int i);
+}
+main() {
+ var a = A(0);
+}
+''');
+ HoverInformation hover = await prepareHover('A(0)');
+ // range
+ expect(hover.offset, findOffset('A(0)'));
+ expect(hover.length, 'A(0)'.length);
+ // element
+ expect(hover.containingLibraryName, 'my.library');
+ expect(hover.containingLibraryPath, testFile);
+ expect(hover.dartdoc, isNull);
+ expect(hover.elementDescription, '(const) A(int i) → A');
+ expect(hover.elementKind, 'constructor');
+ // types
+ expect(hover.staticType, isNull);
+ expect(hover.propagatedType, isNull);
+ // no parameter
+ expect(hover.parameter, isNull);
+ }
+
+ test_instanceCreation_noKeyword_new() async {
+ addTestFile('''
+library my.library;
+class A {}
+main() {
+ var a = A();
+}
+''');
+ HoverInformation hover = await prepareHover('A()');
+ // range
+ expect(hover.offset, findOffset('A()'));
+ expect(hover.length, 'A()'.length);
+ // element
+ expect(hover.containingLibraryName, 'my.library');
+ expect(hover.containingLibraryPath, testFile);
+ expect(hover.dartdoc, isNull);
+ expect(hover.elementDescription, '(new) A() → A');
+ expect(hover.elementKind, 'constructor');
+ // types
+ expect(hover.staticType, isNull);
+ expect(hover.propagatedType, isNull);
+ // no parameter
+ expect(hover.parameter, isNull);
+ }
+
test_noHoverInfo() async {
addTestFile('''
library my.library;
diff --git a/pkg/analysis_server/test/channel/byte_stream_channel_test.dart b/pkg/analysis_server/test/channel/byte_stream_channel_test.dart
index e5756a0..f6a0692 100644
--- a/pkg/analysis_server/test/channel/byte_stream_channel_test.dart
+++ b/pkg/analysis_server/test/channel/byte_stream_channel_test.dart
@@ -9,7 +9,6 @@
import 'package:analysis_server/protocol/protocol.dart';
import 'package:analysis_server/src/channel/byte_stream_channel.dart';
import 'package:analyzer/instrumentation/instrumentation.dart';
-import 'package:mockito/mockito.dart';
import 'package:test/test.dart';
import 'package:test_reflective_loader/test_reflective_loader.dart';
@@ -238,11 +237,6 @@
test_sendNotification_exceptionInSink() async {
// This IOSink asynchronously throws an exception on any writeln().
var outputSink = new _IOSinkMock();
- when(outputSink.writeln(any)).thenAnswer((answer) {
- new Timer(new Duration(milliseconds: 10), () {
- throw '42';
- });
- });
var channel = new ByteStreamServerChannel(
null, outputSink, InstrumentationService.NULL_SERVICE);
@@ -267,4 +261,41 @@
}
}
-class _IOSinkMock extends Mock implements IOSink {}
+class _IOSinkMock implements IOSink {
+ @override
+ Encoding encoding;
+
+ @override
+ Future done = null;
+
+ @override
+ void add(List<int> data) {}
+
+ @override
+ void addError(Object error, [StackTrace stackTrace]) {}
+
+ @override
+ Future addStream(Stream<List<int>> stream) => null;
+
+ @override
+ Future close() => null;
+
+ @override
+ Future flush() => null;
+
+ @override
+ void write(Object obj) {}
+
+ @override
+ void writeAll(Iterable objects, [String separator = ""]) {}
+
+ @override
+ void writeCharCode(int charCode) {}
+
+ @override
+ void writeln([Object obj = ""]) {
+ new Timer(new Duration(milliseconds: 10), () {
+ throw '42';
+ });
+ }
+}
diff --git a/pkg/analysis_server/test/integration/analysis/reanalyze_concurrent_test.dart b/pkg/analysis_server/test/integration/analysis/reanalyze_concurrent_test.dart
index 7a726ab..2ee347d 100644
--- a/pkg/analysis_server/test/integration/analysis/reanalyze_concurrent_test.dart
+++ b/pkg/analysis_server/test/integration/analysis/reanalyze_concurrent_test.dart
@@ -10,6 +10,7 @@
*/
import 'dart:async';
+import 'package:test/test.dart';
import 'package:test_reflective_loader/test_reflective_loader.dart';
import '../support/integration_tests.dart';
@@ -23,6 +24,7 @@
@reflectiveTest
class ReanalyzeTest extends AbstractAnalysisServerIntegrationTest {
+ @TestTimeout(const Timeout.factor(2))
test_reanalyze_concurrent() {
String pathname = sourcePath('test.dart');
String text = '''
diff --git a/pkg/analysis_server/test/integration/completion/get_suggestions_test.dart b/pkg/analysis_server/test/integration/completion/get_suggestions_test.dart
index 3c90961..dbdc7fa 100644
--- a/pkg/analysis_server/test/integration/completion/get_suggestions_test.dart
+++ b/pkg/analysis_server/test/integration/completion/get_suggestions_test.dart
@@ -110,10 +110,9 @@
standardAnalysisSetup(subscribeStatus: false);
// Missing file and no overlay
//sendAnalysisUpdateContent({path: new AddContentOverlay(content)});
- var errorToken = 'exception from server';
return sendCompletionGetSuggestions(path, 0).catchError((e) {
// Exception expected
- return errorToken;
+ return null;
}).then((result) {
expect(result, new isInstanceOf<CompletionGetSuggestionsResult>());
});
diff --git a/pkg/analysis_server/test/integration/support/integration_tests.dart b/pkg/analysis_server/test/integration/support/integration_tests.dart
index bd72a42..db7ff54 100644
--- a/pkg/analysis_server/test/integration/support/integration_tests.dart
+++ b/pkg/analysis_server/test/integration/support/integration_tests.dart
@@ -143,8 +143,9 @@
* analysis to finish.
*/
Future<ServerStatusParams> get analysisFinished {
- Completer completer = new Completer();
- StreamSubscription subscription;
+ Completer<ServerStatusParams> completer =
+ new Completer<ServerStatusParams>();
+ StreamSubscription<ServerStatusParams> subscription;
// This will only work if the caller has already subscribed to
// SERVER_STATUS (e.g. using sendServerSetSubscriptions(['STATUS']))
outOfTestExpect(_subscribedToServerStatus, isTrue);
diff --git a/pkg/analysis_server/test/integration/support/protocol_matchers.dart b/pkg/analysis_server/test/integration/support/protocol_matchers.dart
index 42db016..464d280 100644
--- a/pkg/analysis_server/test/integration/support/protocol_matchers.dart
+++ b/pkg/analysis_server/test/integration/support/protocol_matchers.dart
@@ -487,7 +487,9 @@
* "variableName": optional String
* "children": optional List<FlutterOutline>
* "id": optional int
+ * "isWidgetClass": optional bool
* "renderConstructor": optional String
+ * "stateClassName": optional String
* "stateOffset": optional int
* "stateLength": optional int
* }
@@ -508,7 +510,9 @@
"variableName": isString,
"children": isListOf(isFlutterOutline),
"id": isInt,
+ "isWidgetClass": isBool,
"renderConstructor": isString,
+ "stateClassName": isString,
"stateOffset": isInt,
"stateLength": isInt
}));
@@ -1103,7 +1107,6 @@
* INLINE_METHOD
* MOVE_FILE
* RENAME
- * SORT_MEMBERS
* }
*/
final Matcher isRefactoringKind = new MatchesEnum("RefactoringKind", [
@@ -1115,8 +1118,7 @@
"INLINE_LOCAL_VARIABLE",
"INLINE_METHOD",
"MOVE_FILE",
- "RENAME",
- "SORT_MEMBERS"
+ "RENAME"
]);
/**
@@ -2478,12 +2480,10 @@
*
* {
* "name": String
- * "stateful": bool
* }
*/
-final Matcher isExtractWidgetOptions = new LazyMatcher(() =>
- new MatchesJsonObject(
- "extractWidget options", {"name": isString, "stateful": isBool}));
+final Matcher isExtractWidgetOptions = new LazyMatcher(
+ () => new MatchesJsonObject("extractWidget options", {"name": isString}));
/**
* flutter.outline params
diff --git a/pkg/analysis_server/test/mocks.dart b/pkg/analysis_server/test/mocks.dart
index bc58223..53ebe1f 100644
--- a/pkg/analysis_server/test/mocks.dart
+++ b/pkg/analysis_server/test/mocks.dart
@@ -14,7 +14,7 @@
import 'package:analyzer/source/package_map_provider.dart';
import 'package:analyzer/source/pub_package_map_provider.dart';
import 'package:analyzer/src/generated/source.dart';
-import 'package:mockito/mockito.dart';
+import 'package:front_end/src/base/timestamped_data.dart';
import 'package:test/test.dart';
/**
@@ -202,10 +202,43 @@
}
class MockSource extends StringTypedMock implements Source {
+ @override
+ TimestampedData<String> contents = null;
+
+ @override
+ String encoding = null;
+
+ @override
+ String fullName = null;
+
+ @override
+ bool isInSystemLibrary = null;
+
+ @override
+ Source librarySource = null;
+
+ @override
+ int modificationStamp = null;
+
+ @override
+ String shortName = null;
+
+ @override
+ Source source = null;
+
+ @override
+ Uri uri = null;
+
+ @override
+ UriKind uriKind = null;
+
MockSource([String name = 'mocked.dart']) : super(name);
+
+ @override
+ bool exists() => null;
}
-class StringTypedMock extends Mock {
+class StringTypedMock {
String _toString;
StringTypedMock(this._toString);
diff --git a/pkg/analysis_server/test/protocol_server_test.dart b/pkg/analysis_server/test/protocol_server_test.dart
index df05a2b..0019aa2 100644
--- a/pkg/analysis_server/test/protocol_server_test.dart
+++ b/pkg/analysis_server/test/protocol_server_test.dart
@@ -14,7 +14,6 @@
import 'package:analyzer/src/error/codes.dart' as engine;
import 'package:analyzer/src/generated/source.dart' as engine;
import 'package:analyzer_plugin/protocol/protocol_common.dart';
-import 'package:mockito/mockito.dart';
import 'package:test/test.dart';
import 'package:test_reflective_loader/test_reflective_loader.dart';
@@ -27,26 +26,20 @@
});
}
-class AnalysisErrorMock extends Mock implements engine.AnalysisError {}
-
@reflectiveTest
class AnalysisErrorTest {
- engine.Source source = new MockSource();
+ MockSource source = new MockSource();
engine.LineInfo lineInfo;
- engine.AnalysisError engineError = new AnalysisErrorMock();
+ MockAnalysisError engineError;
void setUp() {
// prepare Source
- when(source.fullName).thenReturn('foo.dart');
+ source.fullName = 'foo.dart';
// prepare LineInfo
lineInfo = new engine.LineInfo([0, 5, 9, 20]);
// prepare AnalysisError
- when(engineError.source).thenReturn(source);
- when(engineError.errorCode)
- .thenReturn(engine.CompileTimeErrorCode.AMBIGUOUS_EXPORT);
- when(engineError.message).thenReturn('my message');
- when(engineError.offset).thenReturn(10);
- when(engineError.length).thenReturn(20);
+ engineError = new MockAnalysisError(source,
+ engine.CompileTimeErrorCode.AMBIGUOUS_EXPORT, 10, 20, 'my message');
}
void tearDown() {
@@ -55,7 +48,7 @@
}
void test_fromEngine_hasCorrection() {
- when(engineError.correction).thenReturn('my correction');
+ engineError.correction = 'my correction';
AnalysisError error = newAnalysisError_fromEngine(lineInfo, engineError);
expect(error.toJson(), {
SEVERITY: 'ERROR',
@@ -75,7 +68,7 @@
}
void test_fromEngine_noCorrection() {
- when(engineError.correction).thenReturn(null);
+ engineError.correction = null;
AnalysisError error = newAnalysisError_fromEngine(lineInfo, engineError);
expect(error.toJson(), {
SEVERITY: 'ERROR',
@@ -94,7 +87,7 @@
}
void test_fromEngine_noLineInfo() {
- when(engineError.correction).thenReturn(null);
+ engineError.correction = null;
AnalysisError error = newAnalysisError_fromEngine(null, engineError);
expect(error.toJson(), {
SEVERITY: 'ERROR',
@@ -194,3 +187,29 @@
});
}
}
+
+class MockAnalysisError implements engine.AnalysisError {
+ @override
+ MockSource source;
+
+ @override
+ engine.ErrorCode errorCode;
+
+ @override
+ int offset;
+
+ @override
+ String message;
+
+ @override
+ String correction = null;
+
+ @override
+ bool isStaticOnly;
+
+ @override
+ int length;
+
+ MockAnalysisError(
+ this.source, this.errorCode, this.offset, this.length, this.message);
+}
diff --git a/pkg/analysis_server/test/services/refactoring/extract_widget_test.dart b/pkg/analysis_server/test/services/refactoring/extract_widget_test.dart
index 98bdf4e..3355620 100644
--- a/pkg/analysis_server/test/services/refactoring/extract_widget_test.dart
+++ b/pkg/analysis_server/test/services/refactoring/extract_widget_test.dart
@@ -66,6 +66,28 @@
assertRefactoringStatusOK(refactoring.checkName());
}
+ test_checkName_alreadyDeclared() async {
+ addFlutterPackage();
+ await indexTestUnit('''
+import 'package:flutter/material.dart';
+
+class MyWidget extends StatelessWidget {
+ @override
+ Widget build(BuildContext context) {
+ return new Container();
+ }
+}
+
+class Test {}
+''');
+ _createRefactoringForStringOffset('new Container');
+
+ refactoring.name = 'Test';
+ assertRefactoringStatus(
+ refactoring.checkName(), RefactoringProblemSeverity.ERROR,
+ expectedMessage: "Library already declares class with name 'Test'.");
+ }
+
test_expression() async {
addFlutterPackage();
await indexTestUnit('''
@@ -164,6 +186,39 @@
''');
}
+ test_expression_onTypeName() async {
+ addFlutterPackage();
+ await indexTestUnit('''
+import 'package:flutter/material.dart';
+
+class MyWidget extends StatelessWidget {
+ @override
+ Widget build(BuildContext context) {
+ return new Container();
+ }
+}
+''');
+ _createRefactoringForStringOffset('tainer(');
+
+ await _assertSuccessfulRefactoring('''
+import 'package:flutter/material.dart';
+
+class MyWidget extends StatelessWidget {
+ @override
+ Widget build(BuildContext context) {
+ return new Test();
+ }
+}
+
+class Test extends StatelessWidget {
+ @override
+ Widget build(BuildContext context) {
+ return new Container();
+ }
+}
+''');
+ }
+
test_expression_topFunction() async {
addFlutterPackage();
await indexTestUnit('''
@@ -671,13 +726,13 @@
@override
Widget build(BuildContext context) {
String local;
- return new Text(local);
+ return new Text('$local $local');
}
}
''');
_createRefactoringForStringOffset('new Text');
- await _assertSuccessfulRefactoring('''
+ await _assertSuccessfulRefactoring(r'''
import 'package:flutter/material.dart';
class MyWidget extends StatelessWidget {
@@ -695,7 +750,7 @@
@override
Widget build(BuildContext context) {
- return new Text(local);
+ return new Text('$local $local');
}
}
''');
diff --git a/pkg/analysis_server/test/src/computer/outline_computer_test.dart b/pkg/analysis_server/test/src/computer/outline_computer_test.dart
index c955b00..316cf31 100644
--- a/pkg/analysis_server/test/src/computer/outline_computer_test.dart
+++ b/pkg/analysis_server/test/src/computer/outline_computer_test.dart
@@ -144,7 +144,7 @@
class OutlineComputerTest extends AbstractOutlineComputerTest {
test_class() async {
Outline unitOutline = await _computeOutline('''
-class A<K, V> {
+abstract class A<K, V> {
int fa, fb;
String fc;
A(int i, String s);
@@ -152,15 +152,18 @@
A._privateName(num p);
static String ma(int pa) => null;
_mb(int pb);
+ R mc<R, P>(P p) {}
String get propA => null;
set propB(int v) {}
}
class B {
B(int p);
-}");
+}
+String fa(int pa) => null;
+R fb<R, P>(P p) {}
''');
List<Outline> topOutlines = unitOutline.children;
- expect(topOutlines, hasLength(2));
+ expect(topOutlines, hasLength(4));
// A
{
Outline outline_A = topOutlines[0];
@@ -177,7 +180,7 @@
expect(element_A.returnType, null);
// A children
List<Outline> outlines_A = outline_A.children;
- expect(outlines_A, hasLength(10));
+ expect(outlines_A, hasLength(11));
{
Outline outline = outlines_A[0];
Element element = outline.element;
@@ -280,6 +283,22 @@
{
Outline outline = outlines_A[8];
Element element = outline.element;
+ expect(element.kind, ElementKind.METHOD);
+ expect(element.name, "mc");
+ {
+ Location location = element.location;
+ expect(location.offset, testCode.indexOf("mc<R, P>"));
+ expect(location.length, "mc".length);
+ }
+ expect(element.parameters, "(P p)");
+ expect(element.returnType, "R");
+ expect(element.typeParameters, "<R, P>");
+ expect(element.isAbstract, isFalse);
+ expect(element.isStatic, isFalse);
+ }
+ {
+ Outline outline = outlines_A[9];
+ Element element = outline.element;
expect(element.kind, ElementKind.GETTER);
expect(element.name, "propA");
{
@@ -291,7 +310,7 @@
expect(element.returnType, "String");
}
{
- Outline outline = outlines_A[9];
+ Outline outline = outlines_A[10];
Element element = outline.element;
expect(element.kind, ElementKind.SETTER);
expect(element.name, "propB");
@@ -335,6 +354,37 @@
expect(element.returnType, isNull);
}
}
+ {
+ Outline outline = topOutlines[2];
+ Element element = outline.element;
+ expect(element.kind, ElementKind.FUNCTION);
+ expect(element.name, "fa");
+ {
+ Location location = element.location;
+ expect(location.offset, testCode.indexOf("fa(int pa)"));
+ expect(location.length, "ma".length);
+ }
+ expect(element.parameters, "(int pa)");
+ expect(element.returnType, "String");
+ expect(element.isAbstract, isFalse);
+ expect(element.isStatic, isTrue);
+ }
+ {
+ Outline outline = topOutlines[3];
+ Element element = outline.element;
+ expect(element.kind, ElementKind.FUNCTION);
+ expect(element.name, "fb");
+ {
+ Location location = element.location;
+ expect(location.offset, testCode.indexOf("fb<R, P>"));
+ expect(location.length, "fb".length);
+ }
+ expect(element.parameters, "(P p)");
+ expect(element.returnType, "R");
+ expect(element.typeParameters, "<R, P>");
+ expect(element.isAbstract, isFalse);
+ expect(element.isStatic, isTrue);
+ }
}
test_enum() async {
diff --git a/pkg/analysis_server/test/src/flutter/flutter_outline_computer_test.dart b/pkg/analysis_server/test/src/flutter/flutter_outline_computer_test.dart
index 374cf39..94d9cc0 100644
--- a/pkg/analysis_server/test/src/flutter/flutter_outline_computer_test.dart
+++ b/pkg/analysis_server/test/src/flutter/flutter_outline_computer_test.dart
@@ -336,7 +336,23 @@
}
''');
var myWidget = unitOutline.children[0];
+ expect(myWidget.isWidgetClass, isTrue);
expect(myWidget.renderConstructor, isNull);
+ expect(myWidget.stateClassName, isNull);
+ expect(myWidget.stateOffset, isNull);
+ expect(myWidget.stateLength, isNull);
+
+ expect(computer.instrumentedCode, isNull);
+ }
+
+ test_render_BAD_notWidget() async {
+ FlutterOutline unitOutline = await _computeOutline('''
+class C {}
+''');
+ var myWidget = unitOutline.children[0];
+ expect(myWidget.isWidgetClass, isNull);
+ expect(myWidget.renderConstructor, isNull);
+ expect(myWidget.stateClassName, isNull);
expect(myWidget.stateOffset, isNull);
expect(myWidget.stateLength, isNull);
@@ -373,6 +389,7 @@
// There is forDesignTime() constructor, but we don't handle parts.
var myWidget = unitOutline.children[0];
+ expect(myWidget.isWidgetClass, isNull);
expect(myWidget.renderConstructor, isNull);
}
@@ -510,6 +527,7 @@
''');
var myWidget = unitOutline.children[0];
expect(myWidget.renderConstructor, 'forDesignTime');
+ expect(myWidget.stateClassName, 'MyWidgetState');
expect(myWidget.stateOffset, 192);
expect(myWidget.stateLength, 130);
}
@@ -533,7 +551,9 @@
}
''');
var myWidget = unitOutline.children[0];
+ expect(myWidget.isWidgetClass, isTrue);
expect(myWidget.renderConstructor, 'forDesignTime');
+ expect(myWidget.stateClassName, 'MyWidgetState');
expect(myWidget.stateOffset, 178);
expect(myWidget.stateLength, 130);
}
@@ -557,7 +577,9 @@
}
''');
var myWidget = unitOutline.children[0];
+ expect(myWidget.isWidgetClass, isTrue);
expect(myWidget.renderConstructor, 'forDesignTime');
+ expect(myWidget.stateClassName, isNull);
expect(myWidget.stateOffset, isNull);
expect(myWidget.stateLength, isNull);
diff --git a/pkg/analysis_server/test/src/plugin/plugin_manager_test.dart b/pkg/analysis_server/test/src/plugin/plugin_manager_test.dart
index 72440be..8c0088f 100644
--- a/pkg/analysis_server/test/src/plugin/plugin_manager_test.dart
+++ b/pkg/analysis_server/test/src/plugin/plugin_manager_test.dart
@@ -213,19 +213,20 @@
test_addPluginToContextRoot_pubspec() async {
// We can't successfully run pub until after the analyzer_plugin package has
// been published.
- io.Directory pkg1Dir = io.Directory.systemTemp.createTempSync('pkg1');
- String pkgPath = pkg1Dir.resolveSymbolicLinksSync();
- await withPubspecPlugin(test: (String pluginPath) async {
- ContextRoot contextRoot = new ContextRoot(pkgPath, []);
- await manager.addPluginToContextRoot(contextRoot, pluginPath);
- String packagesPath =
- resourceProvider.pathContext.join(pluginPath, '.packages');
- File packagesFile = resourceProvider.getFile(packagesPath);
- bool exists = packagesFile.exists;
- await manager.stopAll();
- expect(exists, isTrue, reason: '.packages file was not created');
- });
- pkg1Dir.deleteSync(recursive: true);
+ fail('Cannot run pub');
+// io.Directory pkg1Dir = io.Directory.systemTemp.createTempSync('pkg1');
+// String pkgPath = pkg1Dir.resolveSymbolicLinksSync();
+// await withPubspecPlugin(test: (String pluginPath) async {
+// ContextRoot contextRoot = new ContextRoot(pkgPath, []);
+// await manager.addPluginToContextRoot(contextRoot, pluginPath);
+// String packagesPath =
+// resourceProvider.pathContext.join(pluginPath, '.packages');
+// File packagesFile = resourceProvider.getFile(packagesPath);
+// bool exists = packagesFile.exists;
+// await manager.stopAll();
+// expect(exists, isTrue, reason: '.packages file was not created');
+// });
+// pkg1Dir.deleteSync(recursive: true);
}
test_broadcastRequest_many() async {
@@ -774,6 +775,7 @@
*/
String _defaultPluginContent() {
return r'''
+import 'dart:async';
import 'dart:isolate';
import 'package:analyzer/file_system/file_system.dart';
import 'package:analyzer/file_system/physical_file_system.dart';
@@ -800,8 +802,8 @@
String get version => '0.0.1';
@override
- AnalysisHandleWatchEventsResult handleAnalysisHandleWatchEvents(
- AnalysisHandleWatchEventsParams parameters) =>
+ Future<AnalysisHandleWatchEventsResult> handleAnalysisHandleWatchEvents(
+ AnalysisHandleWatchEventsParams parameters) async =>
new AnalysisHandleWatchEventsResult();
@override
diff --git a/pkg/analysis_server/tool/spec/generated/java/types/ExtractWidgetOptions.java b/pkg/analysis_server/tool/spec/generated/java/types/ExtractWidgetOptions.java
index 355f9e3..0a4ea99 100644
--- a/pkg/analysis_server/tool/spec/generated/java/types/ExtractWidgetOptions.java
+++ b/pkg/analysis_server/tool/spec/generated/java/types/ExtractWidgetOptions.java
@@ -39,16 +39,10 @@
private String name;
/**
- * True if a StatefulWidget should be created.
- */
- private boolean stateful;
-
- /**
* Constructor for {@link ExtractWidgetOptions}.
*/
- public ExtractWidgetOptions(String name, boolean stateful) {
+ public ExtractWidgetOptions(String name) {
this.name = name;
- this.stateful = stateful;
}
@Override
@@ -56,16 +50,14 @@
if (obj instanceof ExtractWidgetOptions) {
ExtractWidgetOptions other = (ExtractWidgetOptions) obj;
return
- ObjectUtilities.equals(other.name, name) &&
- other.stateful == stateful;
+ ObjectUtilities.equals(other.name, name);
}
return false;
}
public static ExtractWidgetOptions fromJson(JsonObject jsonObject) {
String name = jsonObject.get("name").getAsString();
- boolean stateful = jsonObject.get("stateful").getAsBoolean();
- return new ExtractWidgetOptions(name, stateful);
+ return new ExtractWidgetOptions(name);
}
public static List<ExtractWidgetOptions> fromJsonArray(JsonArray jsonArray) {
@@ -87,18 +79,10 @@
return name;
}
- /**
- * True if a StatefulWidget should be created.
- */
- public boolean stateful() {
- return stateful;
- }
-
@Override
public int hashCode() {
HashCodeBuilder builder = new HashCodeBuilder();
builder.append(name);
- builder.append(stateful);
return builder.toHashCode();
}
@@ -109,17 +93,9 @@
this.name = name;
}
- /**
- * True if a StatefulWidget should be created.
- */
- public void setStateful(boolean stateful) {
- this.stateful = stateful;
- }
-
public JsonObject toJson() {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("name", name);
- jsonObject.addProperty("stateful", stateful);
return jsonObject;
}
@@ -128,9 +104,7 @@
StringBuilder builder = new StringBuilder();
builder.append("[");
builder.append("name=");
- builder.append(name + ", ");
- builder.append("stateful=");
- builder.append(stateful);
+ builder.append(name);
builder.append("]");
return builder.toString();
}
diff --git a/pkg/analysis_server/tool/spec/generated/java/types/FlutterOutline.java b/pkg/analysis_server/tool/spec/generated/java/types/FlutterOutline.java
index c3cfe10..4d186fdf 100644
--- a/pkg/analysis_server/tool/spec/generated/java/types/FlutterOutline.java
+++ b/pkg/analysis_server/tool/spec/generated/java/types/FlutterOutline.java
@@ -110,6 +110,12 @@
private final Integer id;
/**
+ * True if the node is a widget class, so it can potentially be rendered, even if it does not yet
+ * have the rendering constructor. This field is omitted if the node is not a widget class.
+ */
+ private final Boolean isWidgetClass;
+
+ /**
* If the node is a widget class that can be rendered for IDE, the name of the constructor that
* should be used to instantiate the widget. Empty string for default constructor. Absent if the
* node is not a widget class that can be rendered.
@@ -117,21 +123,27 @@
private final String renderConstructor;
/**
- * If the node is a StatefulWidget that can be rendered, and its State class is defined in the same
- * file, the offset of the State class code in the file.
+ * If the node is a StatefulWidget, and its state class is defined in the same file, the name of
+ * the state class.
+ */
+ private final String stateClassName;
+
+ /**
+ * If the node is a StatefulWidget that can be rendered, and its state class is defined in the same
+ * file, the offset of the state class code in the file.
*/
private final Integer stateOffset;
/**
- * If the node is a StatefulWidget that can be rendered, and its State class is defined in the same
- * file, the length of the State class code in the file.
+ * If the node is a StatefulWidget that can be rendered, and its state class is defined in the same
+ * file, the length of the state class code in the file.
*/
private final Integer stateLength;
/**
* Constructor for {@link FlutterOutline}.
*/
- public FlutterOutline(String kind, int offset, int length, int codeOffset, int codeLength, String label, Element dartElement, List<FlutterOutlineAttribute> attributes, String className, String parentAssociationLabel, String variableName, List<FlutterOutline> children, Integer id, String renderConstructor, Integer stateOffset, Integer stateLength) {
+ public FlutterOutline(String kind, int offset, int length, int codeOffset, int codeLength, String label, Element dartElement, List<FlutterOutlineAttribute> attributes, String className, String parentAssociationLabel, String variableName, List<FlutterOutline> children, Integer id, Boolean isWidgetClass, String renderConstructor, String stateClassName, Integer stateOffset, Integer stateLength) {
this.kind = kind;
this.offset = offset;
this.length = length;
@@ -145,7 +157,9 @@
this.variableName = variableName;
this.children = children;
this.id = id;
+ this.isWidgetClass = isWidgetClass;
this.renderConstructor = renderConstructor;
+ this.stateClassName = stateClassName;
this.stateOffset = stateOffset;
this.stateLength = stateLength;
}
@@ -168,7 +182,9 @@
ObjectUtilities.equals(other.variableName, variableName) &&
ObjectUtilities.equals(other.children, children) &&
ObjectUtilities.equals(other.id, id) &&
+ ObjectUtilities.equals(other.isWidgetClass, isWidgetClass) &&
ObjectUtilities.equals(other.renderConstructor, renderConstructor) &&
+ ObjectUtilities.equals(other.stateClassName, stateClassName) &&
ObjectUtilities.equals(other.stateOffset, stateOffset) &&
ObjectUtilities.equals(other.stateLength, stateLength);
}
@@ -189,10 +205,12 @@
String variableName = jsonObject.get("variableName") == null ? null : jsonObject.get("variableName").getAsString();
List<FlutterOutline> children = jsonObject.get("children") == null ? null : FlutterOutline.fromJsonArray(jsonObject.get("children").getAsJsonArray());
Integer id = jsonObject.get("id") == null ? null : jsonObject.get("id").getAsInt();
+ Boolean isWidgetClass = jsonObject.get("isWidgetClass") == null ? null : jsonObject.get("isWidgetClass").getAsBoolean();
String renderConstructor = jsonObject.get("renderConstructor") == null ? null : jsonObject.get("renderConstructor").getAsString();
+ String stateClassName = jsonObject.get("stateClassName") == null ? null : jsonObject.get("stateClassName").getAsString();
Integer stateOffset = jsonObject.get("stateOffset") == null ? null : jsonObject.get("stateOffset").getAsInt();
Integer stateLength = jsonObject.get("stateLength") == null ? null : jsonObject.get("stateLength").getAsInt();
- return new FlutterOutline(kind, offset, length, codeOffset, codeLength, label, dartElement, attributes, className, parentAssociationLabel, variableName, children, id, renderConstructor, stateOffset, stateLength);
+ return new FlutterOutline(kind, offset, length, codeOffset, codeLength, label, dartElement, attributes, className, parentAssociationLabel, variableName, children, id, isWidgetClass, renderConstructor, stateClassName, stateOffset, stateLength);
}
public static List<FlutterOutline> fromJsonArray(JsonArray jsonArray) {
@@ -262,6 +280,14 @@
}
/**
+ * True if the node is a widget class, so it can potentially be rendered, even if it does not yet
+ * have the rendering constructor. This field is omitted if the node is not a widget class.
+ */
+ public Boolean getIsWidgetClass() {
+ return isWidgetClass;
+ }
+
+ /**
* The kind of the node.
*/
public String getKind() {
@@ -310,16 +336,24 @@
}
/**
- * If the node is a StatefulWidget that can be rendered, and its State class is defined in the same
- * file, the length of the State class code in the file.
+ * If the node is a StatefulWidget, and its state class is defined in the same file, the name of
+ * the state class.
+ */
+ public String getStateClassName() {
+ return stateClassName;
+ }
+
+ /**
+ * If the node is a StatefulWidget that can be rendered, and its state class is defined in the same
+ * file, the length of the state class code in the file.
*/
public Integer getStateLength() {
return stateLength;
}
/**
- * If the node is a StatefulWidget that can be rendered, and its State class is defined in the same
- * file, the offset of the State class code in the file.
+ * If the node is a StatefulWidget that can be rendered, and its state class is defined in the same
+ * file, the offset of the state class code in the file.
*/
public Integer getStateOffset() {
return stateOffset;
@@ -348,7 +382,9 @@
builder.append(variableName);
builder.append(children);
builder.append(id);
+ builder.append(isWidgetClass);
builder.append(renderConstructor);
+ builder.append(stateClassName);
builder.append(stateOffset);
builder.append(stateLength);
return builder.toHashCode();
@@ -393,9 +429,15 @@
if (id != null) {
jsonObject.addProperty("id", id);
}
+ if (isWidgetClass != null) {
+ jsonObject.addProperty("isWidgetClass", isWidgetClass);
+ }
if (renderConstructor != null) {
jsonObject.addProperty("renderConstructor", renderConstructor);
}
+ if (stateClassName != null) {
+ jsonObject.addProperty("stateClassName", stateClassName);
+ }
if (stateOffset != null) {
jsonObject.addProperty("stateOffset", stateOffset);
}
@@ -435,8 +477,12 @@
builder.append(StringUtils.join(children, ", ") + ", ");
builder.append("id=");
builder.append(id + ", ");
+ builder.append("isWidgetClass=");
+ builder.append(isWidgetClass + ", ");
builder.append("renderConstructor=");
builder.append(renderConstructor + ", ");
+ builder.append("stateClassName=");
+ builder.append(stateClassName + ", ");
builder.append("stateOffset=");
builder.append(stateOffset + ", ");
builder.append("stateLength=");
diff --git a/pkg/analysis_server/tool/spec/generated/java/types/RefactoringKind.java b/pkg/analysis_server/tool/spec/generated/java/types/RefactoringKind.java
index 5a6fa35..65ba515 100644
--- a/pkg/analysis_server/tool/spec/generated/java/types/RefactoringKind.java
+++ b/pkg/analysis_server/tool/spec/generated/java/types/RefactoringKind.java
@@ -33,6 +33,4 @@
public static final String RENAME = "RENAME";
- public static final String SORT_MEMBERS = "SORT_MEMBERS";
-
}
diff --git a/pkg/analysis_server/tool/spec/spec_input.html b/pkg/analysis_server/tool/spec/spec_input.html
index dcccfc0..c0fcd8f 100644
--- a/pkg/analysis_server/tool/spec/spec_input.html
+++ b/pkg/analysis_server/tool/spec/spec_input.html
@@ -3172,6 +3172,14 @@
with this node.
</p>
</field>
+ <field name="isWidgetClass" optional="true">
+ <ref>bool</ref>
+ <p>
+ True if the node is a widget class, so it can potentially be
+ rendered, even if it does not yet have the rendering constructor.
+ This field is omitted if the node is not a widget class.
+ </p>
+ </field>
<field name="renderConstructor" optional="true">
<ref>String</ref>
<p>
@@ -3181,19 +3189,26 @@
widget class that can be rendered.
</p>
</field>
+ <field name="stateClassName" optional="true">
+ <ref>String</ref>
+ <p>
+ If the node is a StatefulWidget, and its state class is defined in
+ the same file, the name of the state class.
+ </p>
+ </field>
<field name="stateOffset" optional="true">
<ref>int</ref>
<p>
- If the node is a StatefulWidget that can be rendered, and its State
- class is defined in the same file, the offset of the State class code
+ If the node is a StatefulWidget that can be rendered, and its state
+ class is defined in the same file, the offset of the state class code
in the file.
</p>
</field>
<field name="stateLength" optional="true">
<ref>int</ref>
<p>
- If the node is a StatefulWidget that can be rendered, and its State
- class is defined in the same file, the length of the State class code
+ If the node is a StatefulWidget that can be rendered, and its state
+ class is defined in the same file, the length of the state class code
in the file.
</p>
</field>
@@ -4239,9 +4254,9 @@
</refactoring>
<refactoring kind="EXTRACT_WIDGET">
<p>
- Create a new class that extends either StatelessWidget or StatefulWidget,
- whose build() method is the widget creation expression, or a method
- returning a Flutter widget, at the specified offset.
+ Create a new class that extends StatelessWidget, whose build() method is
+ the widget creation expression, or a method returning a Flutter widget,
+ at the specified offset.
</p>
<feedback>
</feedback>
@@ -4252,12 +4267,6 @@
The name that the widget class should be given.
</p>
</field>
- <field name="stateful">
- <ref>bool</ref>
- <p>
- True if a StatefulWidget should be created.
- </p>
- </field>
</options>
</refactoring>
<refactoring kind="INLINE_LOCAL_VARIABLE">
diff --git a/pkg/analysis_server_client/pubspec.yaml b/pkg/analysis_server_client/pubspec.yaml
index 25ea57e..bb7ca3d 100644
--- a/pkg/analysis_server_client/pubspec.yaml
+++ b/pkg/analysis_server_client/pubspec.yaml
@@ -8,6 +8,5 @@
homepage: http://github.com/dart-lang/sdk/pkg/analysis_server_client
dev_dependencies:
test: ">=0.12.0 <0.13.0"
- mockito: ^2.0.2
environment:
sdk: ">=1.0.0 < 2.0.0-dev.infinity"
diff --git a/pkg/analysis_server_client/test/analysis_server_client_test.dart b/pkg/analysis_server_client/test/analysis_server_client_test.dart
index 8d4c806..6ceabe2 100644
--- a/pkg/analysis_server_client/test/analysis_server_client_test.dart
+++ b/pkg/analysis_server_client/test/analysis_server_client_test.dart
@@ -7,23 +7,19 @@
import 'dart:io';
import 'package:analysis_server_client/analysis_server_client.dart';
-import 'package:mockito/mockito.dart';
import 'package:test/test.dart';
void main() {
- Process _process;
+ MockProcess process;
AnalysisServerClient serverWrapper;
setUp(() async {
- _process = new MockProcess();
- final _mockStdin = new MockStdin();
- serverWrapper = new AnalysisServerClient(_process);
- when(_process.stdin).thenReturn(_mockStdin);
- when(_mockStdin.add).thenReturn(null);
+ process = new MockProcess();
+ serverWrapper = new AnalysisServerClient(process);
});
test('test_listenToOutput_good', () async {
- when(_process.stdout).thenAnswer((_) => _goodMessage());
+ process.stdout = _goodMessage();
final future = serverWrapper.send('blahMethod', null);
serverWrapper.listenToOutput();
@@ -35,7 +31,7 @@
});
test('test_listenToOutput_error', () async {
- when(_process.stdout).thenAnswer((_) => _badMessage());
+ process.stdout = _badMessage();
final future = serverWrapper.send('blahMethod', null);
future.catchError((e) {
expect(e, new isInstanceOf<ServerErrorMessage>());
@@ -48,7 +44,7 @@
});
test('test_listenToOutput_event', () async {
- when(_process.stdout).thenAnswer((_) => _eventMessage());
+ process.stdout = _eventMessage();
void eventHandler(String event, Map<String, Object> params) {
expect(event, 'fooEvent');
@@ -92,6 +88,57 @@
yield utf8.encoder.convert(json.encode(sampleJson));
}
-class MockProcess extends Mock implements Process {}
+class MockProcess implements Process {
+ @override
+ Stream<List<int>> stderr;
-class MockStdin extends Mock implements List {}
+ @override
+ IOSink stdin = new MockStdin();
+
+ @override
+ Stream<List<int>> stdout;
+
+ @override
+ Future<int> get exitCode => null;
+
+ @override
+ int get pid => null;
+
+ @override
+ bool kill([ProcessSignal signal = ProcessSignal.SIGTERM]) => null;
+}
+
+class MockStdin implements IOSink {
+ @override
+ Encoding encoding;
+
+ @override
+ Future get done => null;
+
+ @override
+ void add(List<int> data) {}
+
+ @override
+ void addError(Object error, [StackTrace stackTrace]) {}
+
+ @override
+ Future addStream(Stream<List<int>> stream) => null;
+
+ @override
+ Future close() => null;
+
+ @override
+ Future flush() => null;
+
+ @override
+ void write(Object obj) {}
+
+ @override
+ void writeAll(Iterable objects, [String separator = ""]) {}
+
+ @override
+ void writeCharCode(int charCode) {}
+
+ @override
+ void writeln([Object obj = ""]) {}
+}
diff --git a/pkg/analyzer/lib/src/context/builder.dart b/pkg/analyzer/lib/src/context/builder.dart
index 4162aa8..c084ed5 100644
--- a/pkg/analyzer/lib/src/context/builder.dart
+++ b/pkg/analyzer/lib/src/context/builder.dart
@@ -330,8 +330,15 @@
Resource location = _findPackagesLocation(path);
if (location is File) {
List<int> fileBytes = location.readAsBytesSync();
- Map<String, Uri> map =
- parse(fileBytes, resourceProvider.pathContext.toUri(location.path));
+ Map<String, Uri> map;
+ try {
+ map =
+ parse(fileBytes, resourceProvider.pathContext.toUri(location.path));
+ } catch (exception) {
+ // If we cannot read the file, then we respond as if the file did not
+ // exist.
+ return Packages.noPackages;
+ }
resolveSymbolicLinks(map);
return new MapPackages(map);
} else if (location is Folder) {
diff --git a/pkg/analyzer/lib/src/dart/ast/utilities.dart b/pkg/analyzer/lib/src/dart/ast/utilities.dart
index 0fe0143..3156fe9 100644
--- a/pkg/analyzer/lib/src/dart/ast/utilities.dart
+++ b/pkg/analyzer/lib/src/dart/ast/utilities.dart
@@ -8415,11 +8415,11 @@
@override
Object visitBinaryExpression(BinaryExpression node) {
- safelyVisitNode(node.leftOperand);
+ _writeOperand(node, node.leftOperand);
sink.write(' ');
sink.write(node.operator.lexeme);
sink.write(' ');
- safelyVisitNode(node.rightOperand);
+ _writeOperand(node, node.rightOperand);
return null;
}
@@ -9125,7 +9125,7 @@
@override
Object visitPostfixExpression(PostfixExpression node) {
- safelyVisitNode(node.operand);
+ _writeOperand(node, node.operand);
sink.write(node.operator.lexeme);
return null;
}
@@ -9141,7 +9141,7 @@
@override
Object visitPrefixExpression(PrefixExpression node) {
sink.write(node.operator.lexeme);
- safelyVisitNode(node.operand);
+ _writeOperand(node, node.operand);
return null;
}
@@ -9397,4 +9397,17 @@
sink.write(";");
return null;
}
+
+ void _writeOperand(Expression node, Expression operand) {
+ if (operand != null) {
+ bool needsParenthesis = operand.precedence < node.precedence;
+ if (needsParenthesis) {
+ sink.write('(');
+ }
+ operand.accept(this);
+ if (needsParenthesis) {
+ sink.write(')');
+ }
+ }
+ }
}
diff --git a/pkg/analyzer/lib/src/dart/element/element.dart b/pkg/analyzer/lib/src/dart/element/element.dart
index 094a77b..9a0e0b1 100644
--- a/pkg/analyzer/lib/src/dart/element/element.dart
+++ b/pkg/analyzer/lib/src/dart/element/element.dart
@@ -1136,15 +1136,8 @@
}
@override
- ConstructorElement getNamedConstructor(String name) {
- for (ConstructorElement element in constructors) {
- String elementName = element.name;
- if (elementName != null && elementName == name) {
- return element;
- }
- }
- return null;
- }
+ ConstructorElement getNamedConstructor(String name) =>
+ getNamedConstructorFromList(name, constructors);
@override
bool isSuperConstructorAccessible(ConstructorElement constructor) {
@@ -1460,6 +1453,17 @@
}
}
+ static ConstructorElement getNamedConstructorFromList(
+ String name, List<ConstructorElement> constructors) {
+ for (ConstructorElement element in constructors) {
+ String elementName = element.name;
+ if (elementName != null && elementName == name) {
+ return element;
+ }
+ }
+ return null;
+ }
+
/**
* Return `true` if the given [type] is a class [InterfaceType].
*/
@@ -6228,7 +6232,7 @@
*/
final KernelLibraryResynthesizerContext _kernelContext;
- final UnlinkedUnit _unlinkedDefiningUnit;
+ final UnlinkedUnit unlinkedDefiningUnit;
/**
* The compilation unit that defines this library.
@@ -6306,7 +6310,7 @@
LibraryElementImpl(this.context, String name, int offset, this.nameLength)
: resynthesizerContext = null,
_kernelContext = null,
- _unlinkedDefiningUnit = null,
+ unlinkedDefiningUnit = null,
super(name, offset);
/**
@@ -6314,7 +6318,7 @@
*/
LibraryElementImpl.forKernel(this.context, this._kernelContext)
: resynthesizerContext = null,
- _unlinkedDefiningUnit = null,
+ unlinkedDefiningUnit = null,
nameLength = _kernelContext.library.name?.length ?? 0,
super.forKernel(null) {
_name = _kernelContext.library.name ?? '';
@@ -6333,14 +6337,14 @@
: nameLength = name != null ? name.length : 0,
resynthesizerContext = null,
_kernelContext = null,
- _unlinkedDefiningUnit = null,
+ unlinkedDefiningUnit = null,
super.forNode(name);
/**
* Initialize using the given serialized information.
*/
LibraryElementImpl.forSerialized(this.context, String name, int offset,
- this.nameLength, this.resynthesizerContext, this._unlinkedDefiningUnit)
+ this.nameLength, this.resynthesizerContext, this.unlinkedDefiningUnit)
: _kernelContext = null,
super.forSerialized(null) {
_name = name;
@@ -6389,8 +6393,8 @@
var metadata = AnalyzerMetadata.forNode(_kernelContext.library);
return metadata?.documentationComment;
}
- if (_unlinkedDefiningUnit != null) {
- return _unlinkedDefiningUnit.libraryDocumentationComment?.text;
+ if (unlinkedDefiningUnit != null) {
+ return unlinkedDefiningUnit.libraryDocumentationComment?.text;
}
return super.documentationComment;
}
@@ -6442,12 +6446,12 @@
.map((k) => new ExportElementImpl.forKernel(this, k))
.toList(growable: false);
}
- if (_unlinkedDefiningUnit != null) {
+ if (unlinkedDefiningUnit != null) {
List<UnlinkedExportNonPublic> unlinkedNonPublicExports =
- _unlinkedDefiningUnit.exports;
+ unlinkedDefiningUnit.exports;
List<UnlinkedExportPublic> unlinkedPublicExports =
- _unlinkedDefiningUnit.publicNamespace.exports;
- assert(_unlinkedDefiningUnit.exports.length ==
+ unlinkedDefiningUnit.publicNamespace.exports;
+ assert(unlinkedDefiningUnit.exports.length ==
unlinkedPublicExports.length);
int length = unlinkedNonPublicExports.length;
if (length != 0) {
@@ -6476,7 +6480,7 @@
* given list of [exports].
*/
void set exports(List<ExportElement> exports) {
- _assertNotResynthesized(_unlinkedDefiningUnit);
+ _assertNotResynthesized(unlinkedDefiningUnit);
for (ExportElement exportElement in exports) {
(exportElement as ExportElementImpl).enclosingElement = this;
}
@@ -6488,8 +6492,8 @@
if (_kernelContext != null) {
return _kernelContext.hasExtUri;
}
- if (_unlinkedDefiningUnit != null) {
- List<UnlinkedImport> unlinkedImports = _unlinkedDefiningUnit.imports;
+ if (unlinkedDefiningUnit != null) {
+ List<UnlinkedImport> unlinkedImports = unlinkedDefiningUnit.imports;
for (UnlinkedImport import in unlinkedImports) {
if (DartUriResolver.isDartExtUri(import.uri)) {
return true;
@@ -6570,23 +6574,9 @@
// Set imports into the field.
_imports = imports;
}
- if (_unlinkedDefiningUnit != null) {
- List<UnlinkedImport> unlinkedImports = _unlinkedDefiningUnit.imports;
- int length = unlinkedImports.length;
- if (length != 0) {
- List<ImportElement> imports = new List<ImportElement>();
- LinkedLibrary linkedLibrary = resynthesizerContext.linkedLibrary;
- for (int i = 0; i < length; i++) {
- int dependency = linkedLibrary.importDependencies[i];
- ImportElementImpl importElement =
- new ImportElementImpl.forSerialized(
- unlinkedImports[i], dependency, library);
- imports.add(importElement);
- }
- _imports = imports;
- } else {
- _imports = const <ImportElement>[];
- }
+ if (unlinkedDefiningUnit != null) {
+ _imports = buildImportsFromSummary(this, unlinkedDefiningUnit.imports,
+ resynthesizerContext.linkedLibrary.importDependencies);
}
}
return _imports ?? ImportElement.EMPTY_LIST;
@@ -6597,7 +6587,7 @@
* given list of [imports].
*/
void set imports(List<ImportElement> imports) {
- _assertNotResynthesized(_unlinkedDefiningUnit);
+ _assertNotResynthesized(unlinkedDefiningUnit);
for (ImportElement importElement in imports) {
(importElement as ImportElementImpl).enclosingElement = this;
PrefixElementImpl prefix = importElement.prefix as PrefixElementImpl;
@@ -6756,10 +6746,10 @@
_metadata = definingUnit._kernelContext
.buildAnnotations(_kernelContext.library.annotations);
}
- if (_unlinkedDefiningUnit != null) {
+ if (unlinkedDefiningUnit != null) {
_metadata = _buildAnnotations(
_definingCompilationUnit as CompilationUnitElementImpl,
- _unlinkedDefiningUnit.libraryAnnotations);
+ unlinkedDefiningUnit.libraryAnnotations);
return _metadata;
}
}
@@ -6783,19 +6773,8 @@
}
@override
- List<PrefixElement> get prefixes {
- if (_prefixes == null) {
- HashSet<PrefixElement> prefixes = new HashSet<PrefixElement>();
- for (ImportElement element in imports) {
- PrefixElement prefix = element.prefix;
- if (prefix != null) {
- prefixes.add(prefix);
- }
- }
- _prefixes = prefixes.toList(growable: false);
- }
- return _prefixes;
- }
+ List<PrefixElement> get prefixes =>
+ _prefixes ??= buildPrefixesFromImports(imports);
@override
Namespace get publicNamespace {
@@ -6977,6 +6956,35 @@
safelyVisitChildren(_parts, visitor);
}
+ static List<ImportElement> buildImportsFromSummary(LibraryElement library,
+ List<UnlinkedImport> unlinkedImports, List<int> importDependencies) {
+ int length = unlinkedImports.length;
+ if (length != 0) {
+ List<ImportElement> imports = new List<ImportElement>();
+ for (int i = 0; i < length; i++) {
+ int dependency = importDependencies[i];
+ ImportElementImpl importElement = new ImportElementImpl.forSerialized(
+ unlinkedImports[i], dependency, library);
+ imports.add(importElement);
+ }
+ return imports;
+ } else {
+ return const <ImportElement>[];
+ }
+ }
+
+ static List<PrefixElement> buildPrefixesFromImports(
+ List<ImportElement> imports) {
+ HashSet<PrefixElement> prefixes = new HashSet<PrefixElement>();
+ for (ImportElement element in imports) {
+ PrefixElement prefix = element.prefix;
+ if (prefix != null) {
+ prefixes.add(prefix);
+ }
+ }
+ return prefixes.toList(growable: false);
+ }
+
/**
* Return the [LibraryElementImpl] of the given [element].
*/
@@ -8718,7 +8726,7 @@
if (_unlinkedImport != null) {
LibraryElementImpl library = enclosingElement as LibraryElementImpl;
int prefixId = _unlinkedImport.prefixReference;
- return _name = library._unlinkedDefiningUnit.references[prefixId].name;
+ return _name = library.unlinkedDefiningUnit.references[prefixId].name;
}
}
return super.name;
@@ -9335,6 +9343,8 @@
@override
ElementKind get kind => ElementKind.TOP_LEVEL_VARIABLE;
+ UnlinkedVariable get unlinkedVariableForTesting => _unlinkedVariable;
+
@override
T accept<T>(ElementVisitor<T> visitor) =>
visitor.visitTopLevelVariableElement(this);
diff --git a/pkg/analyzer/lib/src/generated/static_type_analyzer.dart b/pkg/analyzer/lib/src/generated/static_type_analyzer.dart
index 45c1a73..58f46f6 100644
--- a/pkg/analyzer/lib/src/generated/static_type_analyzer.dart
+++ b/pkg/analyzer/lib/src/generated/static_type_analyzer.dart
@@ -85,12 +85,15 @@
Map<ExecutableElement, DartType> _propagatedReturnTypes =
new HashMap<ExecutableElement, DartType>();
+ /// Indicates whether type propagation should be performed.
+ final bool propagateTypes;
+
/**
* Initialize a newly created type analyzer.
*
* @param resolver the resolver driving this participant
*/
- StaticTypeAnalyzer(this._resolver) {
+ StaticTypeAnalyzer(this._resolver, {this.propagateTypes: true}) {
_typeProvider = _resolver.typeProvider;
_typeSystem = _resolver.typeSystem;
_dynamicType = _typeProvider.dynamicType;
@@ -306,10 +309,12 @@
DartType staticType = _getStaticType(rightHandSide);
_recordStaticType(node, staticType);
DartType overrideType = staticType;
- DartType propagatedType = rightHandSide.propagatedType;
- if (propagatedType != null) {
- _resolver.recordPropagatedTypeIfBetter(node, propagatedType);
- overrideType = propagatedType;
+ if (propagateTypes) {
+ DartType propagatedType = rightHandSide.propagatedType;
+ if (propagatedType != null) {
+ _resolver.recordPropagatedTypeIfBetter(node, propagatedType);
+ overrideType = propagatedType;
+ }
}
_resolver.overrideExpression(node.leftHandSide, overrideType, true, true);
} else if (operator == TokenType.QUESTION_QUESTION_EQ) {
@@ -330,16 +335,18 @@
node.rightHandSide.staticType,
staticType);
_recordStaticType(node, staticType);
- MethodElement propagatedMethodElement = node.propagatedElement;
- if (!identical(propagatedMethodElement, staticMethodElement)) {
- DartType propagatedType =
- _computeStaticReturnType(propagatedMethodElement);
- propagatedType = _typeSystem.refineBinaryExpressionType(
- node.leftHandSide.propagatedType,
- operator,
- node.rightHandSide.propagatedType,
- propagatedType);
- _resolver.recordPropagatedTypeIfBetter(node, propagatedType);
+ if (propagateTypes) {
+ MethodElement propagatedMethodElement = node.propagatedElement;
+ if (!identical(propagatedMethodElement, staticMethodElement)) {
+ DartType propagatedType =
+ _computeStaticReturnType(propagatedMethodElement);
+ propagatedType = _typeSystem.refineBinaryExpressionType(
+ node.leftHandSide.propagatedType,
+ operator,
+ node.rightHandSide.propagatedType,
+ propagatedType);
+ _resolver.recordPropagatedTypeIfBetter(node, propagatedType);
+ }
}
}
return null;
@@ -365,8 +372,10 @@
}
_recordStaticType(node, awaitType(_getStaticType(node.expression)));
- DartType propagatedType = awaitType(node.expression.propagatedType);
- _resolver.recordPropagatedTypeIfBetter(node, propagatedType);
+ if (propagateTypes) {
+ DartType propagatedType = awaitType(node.expression.propagatedType);
+ _resolver.recordPropagatedTypeIfBetter(node, propagatedType);
+ }
return null;
}
@@ -425,16 +434,18 @@
node.rightOperand.staticType,
staticType);
_recordStaticType(node, staticType);
- MethodElement propagatedMethodElement = node.propagatedElement;
- if (!identical(propagatedMethodElement, staticMethodElement)) {
- DartType propagatedType =
- _computeStaticReturnType(propagatedMethodElement);
- propagatedType = _typeSystem.refineBinaryExpressionType(
- node.leftOperand.bestType,
- node.operator.type,
- node.rightOperand.bestType,
- propagatedType);
- _resolver.recordPropagatedTypeIfBetter(node, propagatedType);
+ if (propagateTypes) {
+ MethodElement propagatedMethodElement = node.propagatedElement;
+ if (!identical(propagatedMethodElement, staticMethodElement)) {
+ DartType propagatedType =
+ _computeStaticReturnType(propagatedMethodElement);
+ propagatedType = _typeSystem.refineBinaryExpressionType(
+ node.leftOperand.bestType,
+ node.operator.type,
+ node.rightOperand.bestType,
+ propagatedType);
+ _resolver.recordPropagatedTypeIfBetter(node, propagatedType);
+ }
}
return null;
}
@@ -457,7 +468,9 @@
@override
Object visitCascadeExpression(CascadeExpression node) {
_recordStaticType(node, _getStaticType(node.target));
- _resolver.recordPropagatedTypeIfBetter(node, node.target.propagatedType);
+ if (propagateTypes) {
+ _resolver.recordPropagatedTypeIfBetter(node, node.target.propagatedType);
+ }
return null;
}
@@ -509,7 +522,9 @@
}
functionElement.returnType =
_computeStaticReturnTypeOfFunctionDeclaration(node);
- _recordPropagatedTypeOfFunction(functionElement, function.body);
+ if (propagateTypes) {
+ _recordPropagatedTypeOfFunction(functionElement, function.body);
+ }
}
_recordStaticType(function, functionElement.type);
return null;
@@ -575,10 +590,12 @@
}
DartType staticType = _computeInvokeReturnType(node.staticInvokeType);
_recordStaticType(node, staticType);
- DartType functionPropagatedType = node.propagatedInvokeType;
- if (functionPropagatedType is FunctionType) {
- DartType propagatedType = functionPropagatedType.returnType;
- _resolver.recordPropagatedTypeIfBetter(node, propagatedType);
+ if (propagateTypes) {
+ DartType functionPropagatedType = node.propagatedInvokeType;
+ if (functionPropagatedType is FunctionType) {
+ DartType propagatedType = functionPropagatedType.returnType;
+ _resolver.recordPropagatedTypeIfBetter(node, propagatedType);
+ }
}
return null;
}
@@ -594,20 +611,25 @@
ExecutableElement staticMethodElement = node.staticElement;
DartType staticType = _computeArgumentType(staticMethodElement);
_recordStaticType(node, staticType);
- MethodElement propagatedMethodElement = node.propagatedElement;
- if (!identical(propagatedMethodElement, staticMethodElement)) {
- DartType propagatedType = _computeArgumentType(propagatedMethodElement);
- _resolver.recordPropagatedTypeIfBetter(node, propagatedType);
+ if (propagateTypes) {
+ MethodElement propagatedMethodElement = node.propagatedElement;
+ if (!identical(propagatedMethodElement, staticMethodElement)) {
+ DartType propagatedType =
+ _computeArgumentType(propagatedMethodElement);
+ _resolver.recordPropagatedTypeIfBetter(node, propagatedType);
+ }
}
} else {
ExecutableElement staticMethodElement = node.staticElement;
DartType staticType = _computeStaticReturnType(staticMethodElement);
_recordStaticType(node, staticType);
- MethodElement propagatedMethodElement = node.propagatedElement;
- if (!identical(propagatedMethodElement, staticMethodElement)) {
- DartType propagatedType =
- _computeStaticReturnType(propagatedMethodElement);
- _resolver.recordPropagatedTypeIfBetter(node, propagatedType);
+ if (propagateTypes) {
+ MethodElement propagatedMethodElement = node.propagatedElement;
+ if (!identical(propagatedMethodElement, staticMethodElement)) {
+ DartType propagatedType =
+ _computeStaticReturnType(propagatedMethodElement);
+ _resolver.recordPropagatedTypeIfBetter(node, propagatedType);
+ }
}
}
return null;
@@ -629,19 +651,21 @@
}
_recordStaticType(node, node.constructorName.type.type);
- ConstructorElement element = node.staticElement;
- if (element != null && "Element" == element.enclosingElement.name) {
- LibraryElement library = element.library;
- if (_isHtmlLibrary(library)) {
- String constructorName = element.name;
- if ("tag" == constructorName) {
- DartType returnType = _getFirstArgumentAsTypeWithMap(
- library, node.argumentList, _HTML_ELEMENT_TO_CLASS_MAP);
- _resolver.recordPropagatedTypeIfBetter(node, returnType);
- } else {
- DartType returnType = _getElementNameAsType(
- library, constructorName, _HTML_ELEMENT_TO_CLASS_MAP);
- _resolver.recordPropagatedTypeIfBetter(node, returnType);
+ if (propagateTypes) {
+ ConstructorElement element = node.staticElement;
+ if (element != null && "Element" == element.enclosingElement.name) {
+ LibraryElement library = element.library;
+ if (_isHtmlLibrary(library)) {
+ String constructorName = element.name;
+ if ("tag" == constructorName) {
+ DartType returnType = _getFirstArgumentAsTypeWithMap(
+ library, node.argumentList, _HTML_ELEMENT_TO_CLASS_MAP);
+ _resolver.recordPropagatedTypeIfBetter(node, returnType);
+ } else {
+ DartType returnType = _getElementNameAsType(
+ library, constructorName, _HTML_ELEMENT_TO_CLASS_MAP);
+ _resolver.recordPropagatedTypeIfBetter(node, returnType);
+ }
}
}
}
@@ -827,7 +851,7 @@
_inferGenericInvocationExpression(node);
}
// Record types of the variable invoked as a function.
- if (staticMethodElement is VariableElement) {
+ if (propagateTypes && staticMethodElement is VariableElement) {
DartType propagatedType = _overrideManager.getType(staticMethodElement);
_resolver.recordPropagatedTypeIfBetter(methodNameNode, propagatedType);
}
@@ -842,136 +866,138 @@
_recordStaticType(node, staticStaticType);
}
- // Record propagated return type of the static element.
- DartType staticPropagatedType =
- _computePropagatedReturnType(staticMethodElement);
- _resolver.recordPropagatedTypeIfBetter(node, staticPropagatedType);
- // Check for special cases.
- bool needPropagatedType = true;
- String methodName = methodNameNode.name;
- if (!_strongMode && methodName == "then") {
- Expression target = node.realTarget;
- if (target != null) {
- DartType targetType = target.bestType;
- if (targetType.isDartAsyncFuture) {
- // Future.then(closure) return type is:
- // 1) the returned Future type, if the closure returns a Future;
- // 2) Future<valueType>, if the closure returns a value.
- NodeList<Expression> arguments = node.argumentList.arguments;
- if (arguments.length == 1) {
- // TODO(brianwilkerson) Handle the case where both arguments are
- // provided.
- Expression closureArg = arguments[0];
- if (closureArg is FunctionExpression) {
- FunctionExpression closureExpr = closureArg;
- DartType returnType =
- _computePropagatedReturnType(closureExpr.element);
- if (returnType != null) {
- // prepare the type of the returned Future
- InterfaceType newFutureType = _typeProvider.futureType
- .instantiate([returnType.flattenFutures(_typeSystem)]);
- // set the 'then' invocation type
- _resolver.recordPropagatedTypeIfBetter(node, newFutureType);
- needPropagatedType = false;
- return null;
+ if (propagateTypes) {
+ // Record propagated return type of the static element.
+ DartType staticPropagatedType =
+ _computePropagatedReturnType(staticMethodElement);
+ _resolver.recordPropagatedTypeIfBetter(node, staticPropagatedType);
+ // Check for special cases.
+ bool needPropagatedType = true;
+ String methodName = methodNameNode.name;
+ if (!_strongMode && methodName == "then") {
+ Expression target = node.realTarget;
+ if (target != null) {
+ DartType targetType = target.bestType;
+ if (targetType.isDartAsyncFuture) {
+ // Future.then(closure) return type is:
+ // 1) the returned Future type, if the closure returns a Future;
+ // 2) Future<valueType>, if the closure returns a value.
+ NodeList<Expression> arguments = node.argumentList.arguments;
+ if (arguments.length == 1) {
+ // TODO(brianwilkerson) Handle the case where both arguments are
+ // provided.
+ Expression closureArg = arguments[0];
+ if (closureArg is FunctionExpression) {
+ FunctionExpression closureExpr = closureArg;
+ DartType returnType =
+ _computePropagatedReturnType(closureExpr.element);
+ if (returnType != null) {
+ // prepare the type of the returned Future
+ InterfaceType newFutureType = _typeProvider.futureType
+ .instantiate([returnType.flattenFutures(_typeSystem)]);
+ // set the 'then' invocation type
+ _resolver.recordPropagatedTypeIfBetter(node, newFutureType);
+ needPropagatedType = false;
+ return null;
+ }
}
}
}
}
- }
- } else if (methodName == "\$dom_createEvent") {
- Expression target = node.realTarget;
- if (target != null) {
- DartType targetType = target.bestType;
- if (targetType is InterfaceType &&
- (targetType.name == "HtmlDocument" ||
- targetType.name == "Document")) {
- LibraryElement library = targetType.element.library;
- if (_isHtmlLibrary(library)) {
- DartType returnType =
- _getFirstArgumentAsType(library, node.argumentList);
- if (returnType != null) {
- _recordPropagatedType(node, returnType);
- needPropagatedType = false;
+ } else if (methodName == "\$dom_createEvent") {
+ Expression target = node.realTarget;
+ if (target != null) {
+ DartType targetType = target.bestType;
+ if (targetType is InterfaceType &&
+ (targetType.name == "HtmlDocument" ||
+ targetType.name == "Document")) {
+ LibraryElement library = targetType.element.library;
+ if (_isHtmlLibrary(library)) {
+ DartType returnType =
+ _getFirstArgumentAsType(library, node.argumentList);
+ if (returnType != null) {
+ _recordPropagatedType(node, returnType);
+ needPropagatedType = false;
+ }
}
}
}
- }
- } else if (methodName == "query") {
- Expression target = node.realTarget;
- if (target == null) {
- Element methodElement = methodNameNode.bestElement;
- if (methodElement != null) {
- LibraryElement library = methodElement.library;
- if (_isHtmlLibrary(library)) {
- DartType returnType =
- _getFirstArgumentAsQuery(library, node.argumentList);
- if (returnType != null) {
- _recordPropagatedType(node, returnType);
- needPropagatedType = false;
+ } else if (methodName == "query") {
+ Expression target = node.realTarget;
+ if (target == null) {
+ Element methodElement = methodNameNode.bestElement;
+ if (methodElement != null) {
+ LibraryElement library = methodElement.library;
+ if (_isHtmlLibrary(library)) {
+ DartType returnType =
+ _getFirstArgumentAsQuery(library, node.argumentList);
+ if (returnType != null) {
+ _recordPropagatedType(node, returnType);
+ needPropagatedType = false;
+ }
+ }
+ }
+ } else {
+ DartType targetType = target.bestType;
+ if (targetType is InterfaceType &&
+ (targetType.name == "HtmlDocument" ||
+ targetType.name == "Document")) {
+ LibraryElement library = targetType.element.library;
+ if (_isHtmlLibrary(library)) {
+ DartType returnType =
+ _getFirstArgumentAsQuery(library, node.argumentList);
+ if (returnType != null) {
+ _recordPropagatedType(node, returnType);
+ needPropagatedType = false;
+ }
}
}
}
- } else {
- DartType targetType = target.bestType;
- if (targetType is InterfaceType &&
- (targetType.name == "HtmlDocument" ||
- targetType.name == "Document")) {
- LibraryElement library = targetType.element.library;
- if (_isHtmlLibrary(library)) {
- DartType returnType =
- _getFirstArgumentAsQuery(library, node.argumentList);
- if (returnType != null) {
- _recordPropagatedType(node, returnType);
- needPropagatedType = false;
+ } else if (methodName == "\$dom_createElement") {
+ Expression target = node.realTarget;
+ if (target != null) {
+ DartType targetType = target.bestType;
+ if (targetType is InterfaceType &&
+ (targetType.name == "HtmlDocument" ||
+ targetType.name == "Document")) {
+ LibraryElement library = targetType.element.library;
+ if (_isHtmlLibrary(library)) {
+ DartType returnType =
+ _getFirstArgumentAsQuery(library, node.argumentList);
+ if (returnType != null) {
+ _recordPropagatedType(node, returnType);
+ needPropagatedType = false;
+ }
}
}
}
- }
- } else if (methodName == "\$dom_createElement") {
- Expression target = node.realTarget;
- if (target != null) {
- DartType targetType = target.bestType;
- if (targetType is InterfaceType &&
- (targetType.name == "HtmlDocument" ||
- targetType.name == "Document")) {
- LibraryElement library = targetType.element.library;
- if (_isHtmlLibrary(library)) {
- DartType returnType =
- _getFirstArgumentAsQuery(library, node.argumentList);
- if (returnType != null) {
- _recordPropagatedType(node, returnType);
- needPropagatedType = false;
- }
- }
+ } else if (methodName == "JS") {
+ DartType returnType = _getFirstArgumentAsType(
+ _typeProvider.objectType.element.library, node.argumentList);
+ if (returnType != null) {
+ _recordPropagatedType(node, returnType);
+ needPropagatedType = false;
}
- }
- } else if (methodName == "JS") {
- DartType returnType = _getFirstArgumentAsType(
- _typeProvider.objectType.element.library, node.argumentList);
- if (returnType != null) {
- _recordPropagatedType(node, returnType);
- needPropagatedType = false;
- }
- } else if (methodName == "getContext") {
- Expression target = node.realTarget;
- if (target != null) {
- DartType targetType = target.bestType;
- if (targetType is InterfaceType &&
- (targetType.name == "CanvasElement")) {
- NodeList<Expression> arguments = node.argumentList.arguments;
- if (arguments.length == 1) {
- Expression argument = arguments[0];
- if (argument is StringLiteral) {
- String value = argument.stringValue;
- if ("2d" == value) {
- PropertyAccessorElement getter =
- targetType.element.getGetter("context2D");
- if (getter != null) {
- DartType returnType = getter.returnType;
- if (returnType != null) {
- _recordPropagatedType(node, returnType);
- needPropagatedType = false;
+ } else if (methodName == "getContext") {
+ Expression target = node.realTarget;
+ if (target != null) {
+ DartType targetType = target.bestType;
+ if (targetType is InterfaceType &&
+ (targetType.name == "CanvasElement")) {
+ NodeList<Expression> arguments = node.argumentList.arguments;
+ if (arguments.length == 1) {
+ Expression argument = arguments[0];
+ if (argument is StringLiteral) {
+ String value = argument.stringValue;
+ if ("2d" == value) {
+ PropertyAccessorElement getter =
+ targetType.element.getGetter("context2D");
+ if (getter != null) {
+ DartType returnType = getter.returnType;
+ if (returnType != null) {
+ _recordPropagatedType(node, returnType);
+ needPropagatedType = false;
+ }
}
}
}
@@ -979,31 +1005,31 @@
}
}
}
- }
- if (needPropagatedType) {
- Element propagatedElement = methodNameNode.propagatedElement;
- DartType propagatedInvokeType = node.propagatedInvokeType;
- // HACK: special case for object methods ([toString]) on dynamic
- // expressions. More special cases in [visitPrefixedIdentfier].
- if (propagatedElement == null) {
- MethodElement objMethod =
- _typeProvider.objectType.getMethod(methodNameNode.name);
- if (objMethod != null) {
- propagatedElement = objMethod;
- propagatedInvokeType = objMethod.type;
+ if (needPropagatedType) {
+ Element propagatedElement = methodNameNode.propagatedElement;
+ DartType propagatedInvokeType = node.propagatedInvokeType;
+ // HACK: special case for object methods ([toString]) on dynamic
+ // expressions. More special cases in [visitPrefixedIdentfier].
+ if (propagatedElement == null) {
+ MethodElement objMethod =
+ _typeProvider.objectType.getMethod(methodNameNode.name);
+ if (objMethod != null) {
+ propagatedElement = objMethod;
+ propagatedInvokeType = objMethod.type;
+ }
}
- }
- if (!identical(propagatedElement, staticMethodElement)) {
- // Record static return type of the propagated element.
- DartType propagatedStaticType =
- _computeInvokeReturnType(propagatedInvokeType);
- _resolver.recordPropagatedTypeIfBetter(
- node, propagatedStaticType, true);
- // Record propagated return type of the propagated element.
- DartType propagatedPropagatedType =
- _computePropagatedReturnType(propagatedElement);
- _resolver.recordPropagatedTypeIfBetter(
- node, propagatedPropagatedType, true);
+ if (!identical(propagatedElement, staticMethodElement)) {
+ // Record static return type of the propagated element.
+ DartType propagatedStaticType =
+ _computeInvokeReturnType(propagatedInvokeType);
+ _resolver.recordPropagatedTypeIfBetter(
+ node, propagatedStaticType, true);
+ // Record propagated return type of the propagated element.
+ DartType propagatedPropagatedType =
+ _computePropagatedReturnType(propagatedElement);
+ _resolver.recordPropagatedTypeIfBetter(
+ node, propagatedPropagatedType, true);
+ }
}
}
return null;
@@ -1013,7 +1039,9 @@
Object visitNamedExpression(NamedExpression node) {
Expression expression = node.expression;
_recordStaticType(node, _getStaticType(expression));
- _resolver.recordPropagatedTypeIfBetter(node, expression.propagatedType);
+ if (propagateTypes) {
+ _resolver.recordPropagatedTypeIfBetter(node, expression.propagatedType);
+ }
return null;
}
@@ -1031,7 +1059,9 @@
Object visitParenthesizedExpression(ParenthesizedExpression node) {
Expression expression = node.expression;
_recordStaticType(node, _getStaticType(expression));
- _resolver.recordPropagatedTypeIfBetter(node, expression.propagatedType);
+ if (propagateTypes) {
+ _resolver.recordPropagatedTypeIfBetter(node, expression.propagatedType);
+ }
return null;
}
@@ -1073,7 +1103,9 @@
}
}
_recordStaticType(node, staticType);
- _resolver.recordPropagatedTypeIfBetter(node, operand.propagatedType);
+ if (propagateTypes) {
+ _resolver.recordPropagatedTypeIfBetter(node, operand.propagatedType);
+ }
return null;
}
@@ -1102,8 +1134,10 @@
staticType = staticElement.type;
} else if (staticElement is PropertyAccessorElement) {
staticType = _getTypeOfProperty(staticElement);
- propagatedType =
- _getPropertyPropagatedType(staticElement, propagatedType);
+ if (propagateTypes) {
+ propagatedType =
+ _getPropertyPropagatedType(staticElement, propagatedType);
+ }
} else if (staticElement is ExecutableElement) {
staticType = staticElement.type;
} else if (staticElement is TypeParameterElement) {
@@ -1117,42 +1151,45 @@
_recordStaticType(prefixedIdentifier, staticType);
_recordStaticType(node, staticType);
}
- Element propagatedElement = prefixedIdentifier.propagatedElement;
- // HACK: special case for object getters ([hashCode] and [runtimeType]) on
- // dynamic expressions. More special cases in [visitMethodInvocation].
- if (propagatedElement == null) {
- propagatedElement =
- _typeProvider.objectType.getGetter(prefixedIdentifier.name);
- }
- if (propagatedElement is ClassElement) {
- if (_isNotTypeLiteral(node)) {
- propagatedType = propagatedElement.type;
- } else {
- propagatedType = _typeProvider.typeType;
+ if (propagateTypes) {
+ Element propagatedElement = prefixedIdentifier.propagatedElement;
+ // HACK: special case for object getters ([hashCode] and [runtimeType]) on
+ // dynamic expressions. More special cases in [visitMethodInvocation].
+ if (propagatedElement == null) {
+ propagatedElement =
+ _typeProvider.objectType.getGetter(prefixedIdentifier.name);
}
- } else if (propagatedElement is FunctionTypeAliasElement) {
- propagatedType = propagatedElement.type;
- } else if (propagatedElement is MethodElement) {
- propagatedType = propagatedElement.type;
- } else if (propagatedElement is PropertyAccessorElement) {
- propagatedType = _getTypeOfProperty(propagatedElement);
- propagatedType =
- _getPropertyPropagatedType(propagatedElement, propagatedType);
- } else if (propagatedElement is ExecutableElement) {
- propagatedType = propagatedElement.type;
- } else if (propagatedElement is TypeParameterElement) {
- propagatedType = propagatedElement.type;
- } else if (propagatedElement is VariableElement) {
- propagatedType = propagatedElement.type;
+ if (propagatedElement is ClassElement) {
+ if (_isNotTypeLiteral(node)) {
+ propagatedType = propagatedElement.type;
+ } else {
+ propagatedType = _typeProvider.typeType;
+ }
+ } else if (propagatedElement is FunctionTypeAliasElement) {
+ propagatedType = propagatedElement.type;
+ } else if (propagatedElement is MethodElement) {
+ propagatedType = propagatedElement.type;
+ } else if (propagatedElement is PropertyAccessorElement) {
+ propagatedType = _getTypeOfProperty(propagatedElement);
+ propagatedType =
+ _getPropertyPropagatedType(propagatedElement, propagatedType);
+ } else if (propagatedElement is ExecutableElement) {
+ propagatedType = propagatedElement.type;
+ } else if (propagatedElement is TypeParameterElement) {
+ propagatedType = propagatedElement.type;
+ } else if (propagatedElement is VariableElement) {
+ propagatedType = propagatedElement.type;
+ }
+ DartType overriddenType = _overrideManager.getType(propagatedElement);
+ if (propagatedType == null ||
+ (overriddenType != null &&
+ overriddenType.isMoreSpecificThan(propagatedType))) {
+ propagatedType = overriddenType;
+ }
+ _resolver.recordPropagatedTypeIfBetter(
+ prefixedIdentifier, propagatedType);
+ _resolver.recordPropagatedTypeIfBetter(node, propagatedType);
}
- DartType overriddenType = _overrideManager.getType(propagatedElement);
- if (propagatedType == null ||
- (overriddenType != null &&
- overriddenType.isMoreSpecificThan(propagatedType))) {
- propagatedType = overriddenType;
- }
- _resolver.recordPropagatedTypeIfBetter(prefixedIdentifier, propagatedType);
- _resolver.recordPropagatedTypeIfBetter(node, propagatedType);
return null;
}
@@ -1178,11 +1215,13 @@
}
}
_recordStaticType(node, staticType);
- MethodElement propagatedMethodElement = node.propagatedElement;
- if (!identical(propagatedMethodElement, staticMethodElement)) {
- DartType propagatedType =
- _computeStaticReturnType(propagatedMethodElement);
- _resolver.recordPropagatedTypeIfBetter(node, propagatedType);
+ if (propagateTypes) {
+ MethodElement propagatedMethodElement = node.propagatedElement;
+ if (!identical(propagatedMethodElement, staticMethodElement)) {
+ DartType propagatedType =
+ _computeStaticReturnType(propagatedMethodElement);
+ _resolver.recordPropagatedTypeIfBetter(node, propagatedType);
+ }
}
}
return null;
@@ -1246,17 +1285,19 @@
_recordStaticType(propertyName, staticType);
_recordStaticType(node, staticType);
}
- Element propagatedElement = propertyName.propagatedElement;
- DartType propagatedType = _overrideManager.getType(propagatedElement);
- if (propagatedElement is MethodElement) {
- propagatedType = propagatedElement.type;
- } else if (propagatedElement is PropertyAccessorElement) {
- propagatedType = _getTypeOfProperty(propagatedElement);
- } else {
- // TODO(brianwilkerson) Report this internal error.
+ if (propagateTypes) {
+ Element propagatedElement = propertyName.propagatedElement;
+ DartType propagatedType = _overrideManager.getType(propagatedElement);
+ if (propagatedElement is MethodElement) {
+ propagatedType = propagatedElement.type;
+ } else if (propagatedElement is PropertyAccessorElement) {
+ propagatedType = _getTypeOfProperty(propagatedElement);
+ } else {
+ // TODO(brianwilkerson) Report this internal error.
+ }
+ _resolver.recordPropagatedTypeIfBetter(propertyName, propagatedType);
+ _resolver.recordPropagatedTypeIfBetter(node, propagatedType);
}
- _resolver.recordPropagatedTypeIfBetter(propertyName, propagatedType);
- _resolver.recordPropagatedTypeIfBetter(node, propagatedType);
return null;
}
@@ -1344,18 +1385,20 @@
}
staticType = _inferGenericInstantiationFromContext(node, staticType);
_recordStaticType(node, staticType);
- // TODO(brianwilkerson) I think we want to repeat the logic above using the
- // propagated element to get another candidate for the propagated type.
- DartType propagatedType = _getPropertyPropagatedType(element, null);
- if (propagatedType == null) {
- DartType overriddenType = _overrideManager.getType(element);
- if (propagatedType == null ||
- overriddenType != null &&
- overriddenType.isMoreSpecificThan(propagatedType)) {
- propagatedType = overriddenType;
+ if (propagateTypes) {
+ // TODO(brianwilkerson) I think we want to repeat the logic above using the
+ // propagated element to get another candidate for the propagated type.
+ DartType propagatedType = _getPropertyPropagatedType(element, null);
+ if (propagatedType == null) {
+ DartType overriddenType = _overrideManager.getType(element);
+ if (propagatedType == null ||
+ overriddenType != null &&
+ overriddenType.isMoreSpecificThan(propagatedType)) {
+ propagatedType = overriddenType;
+ }
}
+ _resolver.recordPropagatedTypeIfBetter(node, propagatedType);
}
- _resolver.recordPropagatedTypeIfBetter(node, propagatedType);
return null;
}
@@ -1432,7 +1475,9 @@
if (initializer != null) {
DartType rightType = initializer.bestType;
SimpleIdentifier name = node.name;
- _resolver.recordPropagatedTypeIfBetter(name, rightType);
+ if (propagateTypes) {
+ _resolver.recordPropagatedTypeIfBetter(name, rightType);
+ }
VariableElement element = name.staticElement as VariableElement;
if (element != null) {
_resolver.overrideVariable(element, rightType, true);
@@ -1464,18 +1509,20 @@
_dynamicType;
_recordStaticType(node, staticType);
- DartType propagatedType1 = expr1.propagatedType;
- DartType propagatedType2 = expr2.propagatedType;
- if (propagatedType1 != null || propagatedType2 != null) {
- if (propagatedType1 == null) {
- propagatedType1 = staticType1;
+ if (propagateTypes) {
+ DartType propagatedType1 = expr1.propagatedType;
+ DartType propagatedType2 = expr2.propagatedType;
+ if (propagatedType1 != null || propagatedType2 != null) {
+ if (propagatedType1 == null) {
+ propagatedType1 = staticType1;
+ }
+ if (propagatedType2 == null) {
+ propagatedType2 = staticType2;
+ }
+ DartType propagatedType =
+ _typeSystem.getLeastUpperBound(propagatedType1, propagatedType2);
+ _resolver.recordPropagatedTypeIfBetter(node, propagatedType);
}
- if (propagatedType2 == null) {
- propagatedType2 = staticType2;
- }
- DartType propagatedType =
- _typeSystem.getLeastUpperBound(propagatedType1, propagatedType2);
- _resolver.recordPropagatedTypeIfBetter(node, propagatedType);
}
}
@@ -2038,7 +2085,9 @@
computedType = _computeReturnTypeOfFunction(body, computedType);
functionElement.returnType = computedType;
- _recordPropagatedTypeOfFunction(functionElement, node.body);
+ if (propagateTypes) {
+ _recordPropagatedTypeOfFunction(functionElement, node.body);
+ }
_recordStaticType(node, functionElement.type);
if (_strongMode) {
_resolver.inferenceContext.recordInference(node, functionElement.type);
diff --git a/pkg/analyzer/lib/src/summary/expr_builder.dart b/pkg/analyzer/lib/src/summary/expr_builder.dart
new file mode 100644
index 0000000..09bd56b
--- /dev/null
+++ b/pkg/analyzer/lib/src/summary/expr_builder.dart
@@ -0,0 +1,659 @@
+// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+import 'package:analyzer/dart/ast/ast.dart';
+import 'package:analyzer/dart/ast/standard_ast_factory.dart';
+import 'package:analyzer/dart/ast/token.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/generated/testing/ast_test_factory.dart';
+import 'package:analyzer/src/generated/testing/token_factory.dart';
+import 'package:analyzer/src/summary/idl.dart';
+import 'package:analyzer/src/summary/resynthesize.dart';
+
+/**
+ * Builder of [Expression]s from [UnlinkedExpr]s.
+ */
+class ExprBuilder {
+ static const ARGUMENT_LIST = 'ARGUMENT_LIST';
+
+ final UnitResynthesizer resynthesizer;
+ final ElementImpl context;
+ final UnlinkedExpr uc;
+ final bool requireValidConst;
+
+ int intPtr = 0;
+ int doublePtr = 0;
+ int stringPtr = 0;
+ int refPtr = 0;
+ int assignmentOperatorPtr = 0;
+ final List<Expression> stack = <Expression>[];
+
+ final List<UnlinkedExecutable> localFunctions;
+
+ ExprBuilder(this.resynthesizer, this.context, this.uc,
+ {this.requireValidConst: true, this.localFunctions});
+
+ /**
+ * Return the [ConstructorElement] enclosing [context].
+ */
+ ConstructorElement get _enclosingConstructor {
+ for (Element e = context; e != null; e = e.enclosingElement) {
+ if (e is ConstructorElement) {
+ return e;
+ }
+ }
+ throw new StateError(
+ 'Unable to find the enclosing constructor of $context');
+ }
+
+ Expression build() {
+ if (requireValidConst && !uc.isValidConst) {
+ return null;
+ }
+ try {
+ for (UnlinkedExprOperation operation in uc.operations) {
+ switch (operation) {
+ case UnlinkedExprOperation.pushNull:
+ _push(AstTestFactory.nullLiteral());
+ break;
+ // bool
+ case UnlinkedExprOperation.pushFalse:
+ _push(AstTestFactory.booleanLiteral(false));
+ break;
+ case UnlinkedExprOperation.pushTrue:
+ _push(AstTestFactory.booleanLiteral(true));
+ break;
+ // literals
+ case UnlinkedExprOperation.pushInt:
+ int value = uc.ints[intPtr++];
+ _push(AstTestFactory.integer(value));
+ break;
+ case UnlinkedExprOperation.pushLongInt:
+ int value = 0;
+ int count = uc.ints[intPtr++];
+ for (int i = 0; i < count; i++) {
+ int next = uc.ints[intPtr++];
+ value = value << 32 | next;
+ }
+ _push(AstTestFactory.integer(value));
+ break;
+ case UnlinkedExprOperation.pushDouble:
+ double value = uc.doubles[doublePtr++];
+ _push(AstTestFactory.doubleLiteral(value));
+ break;
+ case UnlinkedExprOperation.makeSymbol:
+ String component = uc.strings[stringPtr++];
+ _push(AstTestFactory.symbolLiteral([component]));
+ break;
+ // String
+ case UnlinkedExprOperation.pushString:
+ String value = uc.strings[stringPtr++];
+ _push(AstTestFactory.string2(value));
+ break;
+ case UnlinkedExprOperation.concatenate:
+ int count = uc.ints[intPtr++];
+ List<InterpolationElement> elements = <InterpolationElement>[];
+ for (int i = 0; i < count; i++) {
+ Expression expr = _pop();
+ InterpolationElement element = _newInterpolationElement(expr);
+ elements.insert(0, element);
+ }
+ _push(AstTestFactory.string(elements));
+ break;
+ // binary
+ case UnlinkedExprOperation.equal:
+ _pushBinary(TokenType.EQ_EQ);
+ break;
+ case UnlinkedExprOperation.notEqual:
+ _pushBinary(TokenType.BANG_EQ);
+ break;
+ case UnlinkedExprOperation.and:
+ _pushBinary(TokenType.AMPERSAND_AMPERSAND);
+ break;
+ case UnlinkedExprOperation.or:
+ _pushBinary(TokenType.BAR_BAR);
+ break;
+ case UnlinkedExprOperation.bitXor:
+ _pushBinary(TokenType.CARET);
+ break;
+ case UnlinkedExprOperation.bitAnd:
+ _pushBinary(TokenType.AMPERSAND);
+ break;
+ case UnlinkedExprOperation.bitOr:
+ _pushBinary(TokenType.BAR);
+ break;
+ case UnlinkedExprOperation.bitShiftLeft:
+ _pushBinary(TokenType.LT_LT);
+ break;
+ case UnlinkedExprOperation.bitShiftRight:
+ _pushBinary(TokenType.GT_GT);
+ break;
+ case UnlinkedExprOperation.add:
+ _pushBinary(TokenType.PLUS);
+ break;
+ case UnlinkedExprOperation.subtract:
+ _pushBinary(TokenType.MINUS);
+ break;
+ case UnlinkedExprOperation.multiply:
+ _pushBinary(TokenType.STAR);
+ break;
+ case UnlinkedExprOperation.divide:
+ _pushBinary(TokenType.SLASH);
+ break;
+ case UnlinkedExprOperation.floorDivide:
+ _pushBinary(TokenType.TILDE_SLASH);
+ break;
+ case UnlinkedExprOperation.modulo:
+ _pushBinary(TokenType.PERCENT);
+ break;
+ case UnlinkedExprOperation.greater:
+ _pushBinary(TokenType.GT);
+ break;
+ case UnlinkedExprOperation.greaterEqual:
+ _pushBinary(TokenType.GT_EQ);
+ break;
+ case UnlinkedExprOperation.less:
+ _pushBinary(TokenType.LT);
+ break;
+ case UnlinkedExprOperation.lessEqual:
+ _pushBinary(TokenType.LT_EQ);
+ break;
+ // prefix
+ case UnlinkedExprOperation.complement:
+ _pushPrefix(TokenType.TILDE);
+ break;
+ case UnlinkedExprOperation.negate:
+ _pushPrefix(TokenType.MINUS);
+ break;
+ case UnlinkedExprOperation.not:
+ _pushPrefix(TokenType.BANG);
+ break;
+ // conditional
+ case UnlinkedExprOperation.conditional:
+ Expression elseExpr = _pop();
+ Expression thenExpr = _pop();
+ Expression condition = _pop();
+ _push(AstTestFactory.conditionalExpression(
+ condition, thenExpr, elseExpr));
+ break;
+ case UnlinkedExprOperation.invokeMethodRef:
+ _pushInvokeMethodRef();
+ break;
+ case UnlinkedExprOperation.invokeMethod:
+ List<Expression> arguments = _buildArguments();
+ TypeArgumentList typeArguments = _buildTypeArguments();
+ Expression target = _pop();
+ String name = uc.strings[stringPtr++];
+ _push(AstTestFactory.methodInvocation3(
+ target, name, typeArguments, arguments));
+ break;
+ // containers
+ case UnlinkedExprOperation.makeUntypedList:
+ _pushList(null);
+ break;
+ case UnlinkedExprOperation.makeTypedList:
+ TypeAnnotation itemType = _newTypeName();
+ _pushList(
+ AstTestFactory.typeArgumentList(<TypeAnnotation>[itemType]));
+ break;
+ case UnlinkedExprOperation.makeUntypedMap:
+ _pushMap(null);
+ break;
+ case UnlinkedExprOperation.makeTypedMap:
+ TypeAnnotation keyType = _newTypeName();
+ TypeAnnotation valueType = _newTypeName();
+ _pushMap(AstTestFactory
+ .typeArgumentList(<TypeAnnotation>[keyType, valueType]));
+ break;
+ case UnlinkedExprOperation.pushReference:
+ _pushReference();
+ break;
+ case UnlinkedExprOperation.extractProperty:
+ _pushExtractProperty();
+ break;
+ case UnlinkedExprOperation.invokeConstructor:
+ _pushInstanceCreation();
+ break;
+ case UnlinkedExprOperation.pushParameter:
+ String name = uc.strings[stringPtr++];
+ SimpleIdentifier identifier = AstTestFactory.identifier3(name);
+ identifier.staticElement = _enclosingConstructor.parameters
+ .firstWhere((parameter) => parameter.name == name,
+ orElse: () => throw new StateError(
+ 'Unable to resolve constructor parameter: $name'));
+ _push(identifier);
+ break;
+ case UnlinkedExprOperation.ifNull:
+ _pushBinary(TokenType.QUESTION_QUESTION);
+ break;
+ case UnlinkedExprOperation.await:
+ // TODO(scheglov) No test, requires closures.
+ Expression expression = _pop();
+ _push(AstTestFactory.awaitExpression(expression));
+ break;
+ case UnlinkedExprOperation.pushLocalFunctionReference:
+ _pushLocalFunctionReference();
+ break;
+ case UnlinkedExprOperation.assignToRef:
+ var ref = _createReference();
+ _push(_createAssignment(ref));
+ break;
+ case UnlinkedExprOperation.typeCast:
+ Expression expression = _pop();
+ TypeAnnotation type = _newTypeName();
+ _push(AstTestFactory.asExpression(expression, type));
+ break;
+ case UnlinkedExprOperation.typeCheck:
+ Expression expression = _pop();
+ TypeAnnotation type = _newTypeName();
+ _push(AstTestFactory.isExpression(expression, false, type));
+ break;
+ case UnlinkedExprOperation.throwException:
+ Expression expression = _pop();
+ _push(AstTestFactory.throwExpression2(expression));
+ break;
+ case UnlinkedExprOperation.assignToProperty:
+ Expression target = _pop();
+ String name = uc.strings[stringPtr++];
+ SimpleIdentifier propertyNode = AstTestFactory.identifier3(name);
+ PropertyAccess propertyAccess =
+ AstTestFactory.propertyAccess(target, propertyNode);
+ _push(_createAssignment(propertyAccess));
+ break;
+ case UnlinkedExprOperation.assignToIndex:
+ Expression index = _pop();
+ Expression target = _pop();
+ IndexExpression indexExpression =
+ AstTestFactory.indexExpression(target, index);
+ _push(_createAssignment(indexExpression));
+ break;
+ case UnlinkedExprOperation.extractIndex:
+ Expression index = _pop();
+ Expression target = _pop();
+ _push(AstTestFactory.indexExpression(target, index));
+ break;
+ case UnlinkedExprOperation.pushSuper:
+ case UnlinkedExprOperation.pushThis:
+ throw const _InvalidConstantException(); // TODO(paulberry)
+ case UnlinkedExprOperation.cascadeSectionBegin:
+ case UnlinkedExprOperation.cascadeSectionEnd:
+ case UnlinkedExprOperation.pushLocalFunctionReference:
+ case UnlinkedExprOperation.pushError:
+ case UnlinkedExprOperation.pushTypedAbstract:
+ case UnlinkedExprOperation.pushUntypedAbstract:
+ throw new UnimplementedError(
+ 'Unexpected $operation in a constant expression.');
+ }
+ }
+ } on _InvalidConstantException {
+ return AstTestFactory.identifier3(r'#invalidConst');
+ }
+ return stack.single;
+ }
+
+ List<Expression> _buildArguments() {
+ List<Expression> arguments;
+ {
+ int numNamedArgs = uc.ints[intPtr++];
+ int numPositionalArgs = uc.ints[intPtr++];
+ int numArgs = numNamedArgs + numPositionalArgs;
+ arguments = _removeTopItems(numArgs);
+ // add names to the named arguments
+ for (int i = 0; i < numNamedArgs; i++) {
+ String name = uc.strings[stringPtr++];
+ int index = numPositionalArgs + i;
+ arguments[index] =
+ AstTestFactory.namedExpression2(name, arguments[index]);
+ }
+ }
+ return arguments;
+ }
+
+ /**
+ * Build the identifier sequence (a single or prefixed identifier, or a
+ * property access) corresponding to the given reference [info].
+ */
+ Expression _buildIdentifierSequence(ReferenceInfo info) {
+ Expression enclosing;
+ if (info.enclosing != null) {
+ enclosing = _buildIdentifierSequence(info.enclosing);
+ }
+ Element element = info.element;
+ if (element == null && info.name == 'length') {
+ element = _getStringLengthElement();
+ }
+ if (enclosing == null) {
+ return AstTestFactory.identifier3(info.name)..staticElement = element;
+ }
+ if (enclosing is SimpleIdentifier) {
+ SimpleIdentifier identifier = AstTestFactory.identifier3(info.name)
+ ..staticElement = element;
+ return AstTestFactory.identifier(enclosing, identifier);
+ }
+ if (element == null) {
+ throw const _InvalidConstantException();
+ }
+ SimpleIdentifier property = AstTestFactory.identifier3(info.name)
+ ..staticElement = element;
+ return AstTestFactory.propertyAccess(enclosing, property);
+ }
+
+ TypeAnnotation _buildTypeAst(DartType type) {
+ List<TypeAnnotation> argumentNodes;
+ if (type is ParameterizedType) {
+ if (!resynthesizer.doesTypeHaveImplicitArguments(type)) {
+ List<DartType> typeArguments = type.typeArguments;
+ argumentNodes = typeArguments.every((a) => a.isDynamic)
+ ? null
+ : typeArguments.map(_buildTypeAst).toList();
+ }
+ }
+ TypeName node = AstTestFactory.typeName4(type.name, argumentNodes);
+ node.type = type;
+ (node.name as SimpleIdentifier).staticElement = type.element;
+ return node;
+ }
+
+ Expression _createAssignment(Expression lhs) {
+ Expression binary(TokenType tokenType) {
+ return AstTestFactory.assignmentExpression(lhs, tokenType, _pop());
+ }
+
+ Expression prefix(TokenType tokenType) {
+ return AstTestFactory.prefixExpression(tokenType, lhs);
+ }
+
+ Expression postfix(TokenType tokenType) {
+ return AstTestFactory.postfixExpression(lhs, tokenType);
+ }
+
+ switch (uc.assignmentOperators[assignmentOperatorPtr++]) {
+ case UnlinkedExprAssignOperator.assign:
+ return binary(TokenType.EQ);
+ case UnlinkedExprAssignOperator.ifNull:
+ return binary(TokenType.QUESTION_QUESTION_EQ);
+ case UnlinkedExprAssignOperator.multiply:
+ return binary(TokenType.STAR_EQ);
+ case UnlinkedExprAssignOperator.divide:
+ return binary(TokenType.SLASH_EQ);
+ case UnlinkedExprAssignOperator.floorDivide:
+ return binary(TokenType.TILDE_SLASH_EQ);
+ case UnlinkedExprAssignOperator.modulo:
+ return binary(TokenType.PERCENT_EQ);
+ case UnlinkedExprAssignOperator.plus:
+ return binary(TokenType.PLUS_EQ);
+ case UnlinkedExprAssignOperator.minus:
+ return binary(TokenType.MINUS_EQ);
+ case UnlinkedExprAssignOperator.shiftLeft:
+ return binary(TokenType.LT_LT_EQ);
+ case UnlinkedExprAssignOperator.shiftRight:
+ return binary(TokenType.GT_GT_EQ);
+ case UnlinkedExprAssignOperator.bitAnd:
+ return binary(TokenType.AMPERSAND_EQ);
+ case UnlinkedExprAssignOperator.bitXor:
+ return binary(TokenType.CARET_EQ);
+ case UnlinkedExprAssignOperator.bitOr:
+ return binary(TokenType.BAR_EQ);
+ case UnlinkedExprAssignOperator.prefixIncrement:
+ return prefix(TokenType.PLUS_PLUS);
+ case UnlinkedExprAssignOperator.prefixDecrement:
+ return prefix(TokenType.MINUS_MINUS);
+ case UnlinkedExprAssignOperator.postfixIncrement:
+ return postfix(TokenType.PLUS_PLUS);
+ case UnlinkedExprAssignOperator.postfixDecrement:
+ return postfix(TokenType.MINUS_MINUS);
+ }
+ }
+
+ Expression _createReference() {
+ EntityRef ref = uc.references[refPtr++];
+ ReferenceInfo info = resynthesizer.getReferenceInfo(ref.reference);
+ Expression node = _buildIdentifierSequence(info);
+ if (requireValidConst && node is Identifier && node.staticElement == null) {
+ throw const _InvalidConstantException();
+ }
+ return node;
+ }
+
+ PropertyAccessorElement _getStringLengthElement() =>
+ resynthesizer.typeProvider.stringType.getGetter('length');
+
+ FormalParameter _makeParameter(UnlinkedParam param) {
+ var simpleParam = AstTestFactory.simpleFormalParameter(null, param.name);
+ if (param.kind == UnlinkedParamKind.positional) {
+ return AstTestFactory.positionalFormalParameter(simpleParam, null);
+ } else if (param.kind == UnlinkedParamKind.named) {
+ return AstTestFactory.namedFormalParameter(simpleParam, null);
+ } else {
+ return simpleParam;
+ }
+ }
+
+ InterpolationElement _newInterpolationElement(Expression expr) {
+ if (expr is SimpleStringLiteral) {
+ return astFactory.interpolationString(expr.literal, expr.value);
+ } else {
+ return astFactory.interpolationExpression(
+ TokenFactory.tokenFromType(TokenType.STRING_INTERPOLATION_EXPRESSION),
+ expr,
+ TokenFactory.tokenFromType(TokenType.CLOSE_CURLY_BRACKET));
+ }
+ }
+
+ /**
+ * Convert the next reference to the [DartType] and return the AST
+ * corresponding to this type.
+ */
+ TypeAnnotation _newTypeName() {
+ EntityRef typeRef = uc.references[refPtr++];
+ DartType type = resynthesizer.buildType(context, typeRef);
+ return _buildTypeAst(type);
+ }
+
+ Expression _pop() => stack.removeLast();
+
+ void _push(Expression expr) {
+ stack.add(expr);
+ }
+
+ void _pushBinary(TokenType operator) {
+ Expression right = _pop();
+ Expression left = _pop();
+ _push(AstTestFactory.binaryExpression(left, operator, right));
+ }
+
+ void _pushExtractProperty() {
+ Expression target = _pop();
+ String name = uc.strings[stringPtr++];
+ SimpleIdentifier propertyNode = AstTestFactory.identifier3(name);
+ // Only String.length property access can be potentially resolved.
+ if (name == 'length') {
+ propertyNode.staticElement = _getStringLengthElement();
+ }
+ _push(AstTestFactory.propertyAccess(target, propertyNode));
+ }
+
+ void _pushInstanceCreation() {
+ EntityRef ref = uc.references[refPtr++];
+ ReferenceInfo info = resynthesizer.getReferenceInfo(ref.reference);
+ // prepare ConstructorElement
+ TypeName typeNode;
+ String constructorName;
+ ConstructorElement constructorElement;
+ if (info.element != null) {
+ if (info.element is ConstructorElement) {
+ constructorName = info.name;
+ } else if (info.element is ClassElement) {
+ constructorName = null;
+ } else {
+ List<Expression> arguments = _buildArguments();
+ SimpleIdentifier name = AstTestFactory.identifier3(info.name);
+ name.staticElement = info.element;
+ name.setProperty(ARGUMENT_LIST, AstTestFactory.argumentList(arguments));
+ _push(name);
+ return;
+ }
+ InterfaceType definingType = resynthesizer.createConstructorDefiningType(
+ context, info, ref.typeArguments);
+ constructorElement =
+ resynthesizer.getConstructorForInfo(definingType, info);
+ typeNode = _buildTypeAst(definingType);
+ } else {
+ if (info.enclosing != null) {
+ if (info.enclosing.enclosing != null) {
+ PrefixedIdentifier typeName = AstTestFactory.identifier5(
+ info.enclosing.enclosing.name, info.enclosing.name);
+ typeName.prefix.staticElement = info.enclosing.enclosing.element;
+ typeName.identifier.staticElement = info.enclosing.element;
+ typeName.identifier.staticType = info.enclosing.type;
+ typeNode = AstTestFactory.typeName3(typeName);
+ typeNode.type = info.enclosing.type;
+ constructorName = info.name;
+ } else if (info.enclosing.element != null) {
+ SimpleIdentifier typeName =
+ AstTestFactory.identifier3(info.enclosing.name);
+ typeName.staticElement = info.enclosing.element;
+ typeName.staticType = info.enclosing.type;
+ typeNode = AstTestFactory.typeName3(typeName);
+ typeNode.type = info.enclosing.type;
+ constructorName = info.name;
+ } else {
+ typeNode = AstTestFactory.typeName3(
+ AstTestFactory.identifier5(info.enclosing.name, info.name));
+ constructorName = null;
+ }
+ } else {
+ typeNode = AstTestFactory.typeName4(info.name);
+ }
+ }
+ // prepare arguments
+ List<Expression> arguments = _buildArguments();
+ // create ConstructorName
+ ConstructorName constructorNode;
+ if (constructorName != null) {
+ constructorNode =
+ AstTestFactory.constructorName(typeNode, constructorName);
+ constructorNode.name.staticElement = constructorElement;
+ } else {
+ constructorNode = AstTestFactory.constructorName(typeNode, null);
+ }
+ constructorNode.staticElement = constructorElement;
+ if (constructorElement == null) {
+ throw const _InvalidConstantException();
+ }
+ // create InstanceCreationExpression
+ InstanceCreationExpression instanceCreation =
+ AstTestFactory.instanceCreationExpression(
+ requireValidConst ? Keyword.CONST : Keyword.NEW,
+ constructorNode,
+ arguments);
+ instanceCreation.staticElement = constructorElement;
+ _push(instanceCreation);
+ }
+
+ void _pushInvokeMethodRef() {
+ List<Expression> arguments = _buildArguments();
+ EntityRef ref = uc.references[refPtr++];
+ ReferenceInfo info = resynthesizer.getReferenceInfo(ref.reference);
+ Expression node = _buildIdentifierSequence(info);
+ TypeArgumentList typeArguments = _buildTypeArguments();
+ if (node is SimpleIdentifier) {
+ _push(astFactory.methodInvocation(
+ null,
+ TokenFactory.tokenFromType(TokenType.PERIOD),
+ node,
+ typeArguments,
+ AstTestFactory.argumentList(arguments)));
+ } else {
+ throw new UnimplementedError('For ${node?.runtimeType}: $node');
+ }
+ }
+
+ TypeArgumentList _buildTypeArguments() {
+ int numTypeArguments = uc.ints[intPtr++];
+ if (numTypeArguments == 0) {
+ return null;
+ }
+
+ var typeNames = new List<TypeAnnotation>(numTypeArguments);
+ for (int i = 0; i < numTypeArguments; i++) {
+ typeNames[i] = _newTypeName();
+ }
+ return AstTestFactory.typeArgumentList(typeNames);
+ }
+
+ void _pushList(TypeArgumentList typeArguments) {
+ int count = uc.ints[intPtr++];
+ List<Expression> elements = <Expression>[];
+ for (int i = 0; i < count; i++) {
+ elements.insert(0, _pop());
+ }
+ _push(AstTestFactory.listLiteral2(Keyword.CONST, typeArguments, elements));
+ }
+
+ void _pushLocalFunctionReference() {
+ _throwIfConst();
+ int popCount = uc.ints[intPtr++];
+ // Note: nonzero popCount is no longer used.
+ assert(popCount == 0);
+ int functionIndex = uc.ints[intPtr++];
+ var localFunction = localFunctions[functionIndex];
+ // TODO(paulberry): need to create a sub-element for the local function;
+ // don't just pass along context.
+ var bodyExpr = new ExprBuilder(
+ resynthesizer, context, localFunction.bodyExpr,
+ requireValidConst: requireValidConst)
+ .build();
+ var parameters = localFunction.parameters.map(_makeParameter).toList();
+ _push(astFactory.functionExpression(
+ null,
+ AstTestFactory.formalParameterList(parameters),
+ astFactory.expressionFunctionBody(null,
+ TokenFactory.tokenFromType(TokenType.FUNCTION), bodyExpr, null)));
+ }
+
+ void _pushMap(TypeArgumentList typeArguments) {
+ int count = uc.ints[intPtr++];
+ List<MapLiteralEntry> entries = <MapLiteralEntry>[];
+ for (int i = 0; i < count; i++) {
+ Expression value = _pop();
+ Expression key = _pop();
+ entries.insert(0, AstTestFactory.mapLiteralEntry2(key, value));
+ }
+ _push(AstTestFactory.mapLiteral(Keyword.CONST, typeArguments, entries));
+ }
+
+ void _pushPrefix(TokenType operator) {
+ Expression operand = _pop();
+ _push(AstTestFactory.prefixExpression(operator, operand));
+ }
+
+ void _pushReference() {
+ _push(_createReference());
+ }
+
+ List<Expression> _removeTopItems(int count) {
+ int start = stack.length - count;
+ int end = stack.length;
+ List<Expression> items = stack.getRange(start, end).toList();
+ stack.removeRange(start, end);
+ return items;
+ }
+
+ void _throwIfConst() {
+ if (requireValidConst) {
+ throw const _InvalidConstantException();
+ }
+ }
+}
+
+/**
+ * This exception is thrown when we detect that the constant expression
+ * being resynthesized is not a valid constant expression.
+ */
+class _InvalidConstantException {
+ const _InvalidConstantException();
+}
diff --git a/pkg/analyzer/lib/src/summary/link.dart b/pkg/analyzer/lib/src/summary/link.dart
index 4f2ed45..928a170 100644
--- a/pkg/analyzer/lib/src/summary/link.dart
+++ b/pkg/analyzer/lib/src/summary/link.dart
@@ -778,6 +778,10 @@
}
@override
+ ConstructorElement getNamedConstructor(String name) =>
+ ClassElementImpl.getNamedConstructorFromList(name, constructors);
+
+ @override
void link(CompilationUnitElementInBuildUnit compilationUnit) {
// Force mixins to be inferred by calling this.mixins. We don't need the
// return value from the getter; we just need it to execute and record the
diff --git a/pkg/analyzer/lib/src/summary/resynthesize.dart b/pkg/analyzer/lib/src/summary/resynthesize.dart
index 58fbf60..5dec73d 100644
--- a/pkg/analyzer/lib/src/summary/resynthesize.dart
+++ b/pkg/analyzer/lib/src/summary/resynthesize.dart
@@ -7,8 +7,6 @@
import 'dart:collection';
import 'package:analyzer/dart/ast/ast.dart';
-import 'package:analyzer/dart/ast/standard_ast_factory.dart';
-import 'package:analyzer/dart/ast/token.dart';
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/type.dart';
import 'package:analyzer/src/dart/element/element.dart';
@@ -19,12 +17,105 @@
import 'package:analyzer/src/generated/resolver.dart';
import 'package:analyzer/src/generated/source_io.dart';
import 'package:analyzer/src/generated/testing/ast_test_factory.dart';
-import 'package:analyzer/src/generated/testing/token_factory.dart';
+import 'package:analyzer/src/summary/expr_builder.dart';
import 'package:analyzer/src/summary/format.dart';
import 'package:analyzer/src/summary/idl.dart';
import 'package:analyzer/src/summary/summary_sdk.dart';
/**
+ * Expando for marking types with implicit type arguments, which are the same as
+ * type parameter bounds (in strong mode), or `dynamic` (in spec mode).
+ *
+ * If a type is associated with a non-null value in this expando, then it has
+ * implicit type arguments.
+ */
+final _typesWithImplicitTypeArguments = new Expando();
+
+/// An instance of [LibraryResynthesizer] is responsible for resynthesizing the
+/// elements in a single library from that library's summary.
+abstract class LibraryResynthesizer {
+ /// Builds the export namespace for the library by aggregating together its
+ /// public namespace and export names.
+ Namespace buildExportNamespace();
+
+ /// Builds the public namespace for the library.
+ Namespace buildPublicNamespace();
+}
+
+/// [LibraryResynthesizerContextMixin] contains methods useful for implementing
+/// the [LibraryResynthesizerContext] interface.
+abstract class LibraryResynthesizerContextMixin
+ implements LibraryResynthesizerContext {
+ /// Gets the associated [LibraryResynthesizer].
+ LibraryResynthesizer get resynthesizer;
+
+ @override
+ Namespace buildExportNamespace() => resynthesizer.buildExportNamespace();
+
+ @override
+ Namespace buildPublicNamespace() => resynthesizer.buildPublicNamespace();
+}
+
+/// [LibraryResynthesizerMixin] contains methods useful for implementing the
+/// [LibraryResynthesizer] interface.
+abstract class LibraryResynthesizerMixin implements LibraryResynthesizer {
+ /// Gets the library element being resynthesized.
+ LibraryElement get library;
+
+ /// Gets the list of export names created during summary linking.
+ List<LinkedExportName> get linkedExportNames;
+
+ /// Builds or retrieves an [Element] for the entity referred to by the given
+ /// [exportName].
+ Element buildExportName(LinkedExportName exportName);
+
+ @override
+ Namespace buildExportNamespace() {
+ Namespace publicNamespace = library.publicNamespace;
+ List<LinkedExportName> exportNames = linkedExportNames;
+ Map<String, Element> definedNames = new HashMap<String, Element>();
+ // Start by populating all the public names from [publicNamespace].
+ publicNamespace.definedNames.forEach((String name, Element element) {
+ definedNames[name] = element;
+ });
+ // Add all the names from [exportNames].
+ for (LinkedExportName exportName in exportNames) {
+ definedNames.putIfAbsent(
+ exportName.name, () => buildExportName(exportName));
+ }
+ return new Namespace(definedNames);
+ }
+
+ @override
+ Namespace buildPublicNamespace() =>
+ new NamespaceBuilder().createPublicNamespaceForLibrary(library);
+}
+
+/// Data structure used during resynthesis to record all the information that is
+/// known about how to resynthesize a single entry in [LinkedUnit.references]
+/// (and its associated entry in [UnlinkedUnit.references], if it exists).
+abstract class ReferenceInfo {
+ /// The element referred to by this reference, or `null` if there is no
+ /// associated element (e.g. because it is a reference to an undefined
+ /// entity).
+ Element get element;
+
+ /// The enclosing [_ReferenceInfo], or `null` for top-level elements.
+ ReferenceInfo get enclosing;
+
+ /// Indicates whether the thing being referenced has at least one type
+ /// parameter.
+ bool get hasTypeParameters;
+
+ /// The name of the entity referred to by this reference.
+ String get name;
+
+ /// If this reference refers to a non-generic type, the type it refers to.
+ /// Otherwise `null`.
+ DartType get type;
+}
+
+/**
* Implementation of [ElementResynthesizer] used when resynthesizing an element
* model from summaries.
*/
@@ -297,495 +388,146 @@
}
}
-/**
- * Builder of [Expression]s from [UnlinkedExpr]s.
- */
-class _ConstExprBuilder {
- static const ARGUMENT_LIST = 'ARGUMENT_LIST';
+class SummaryResynthesizerContext implements ResynthesizerContext {
+ final _UnitResynthesizer unitResynthesizer;
- final _UnitResynthesizer resynthesizer;
- final ElementImpl context;
- final UnlinkedExpr uc;
+ SummaryResynthesizerContext(this.unitResynthesizer);
- int intPtr = 0;
- int doublePtr = 0;
- int stringPtr = 0;
- int refPtr = 0;
- final List<Expression> stack = <Expression>[];
+ @override
+ bool get isStrongMode => unitResynthesizer.summaryResynthesizer.strongMode;
- _ConstExprBuilder(this.resynthesizer, this.context, this.uc);
-
- /**
- * Return the [ConstructorElement] enclosing [context].
- */
- ConstructorElement get _enclosingConstructor {
- for (Element e = context; e != null; e = e.enclosingElement) {
- if (e is ConstructorElement) {
- return e;
- }
- }
- throw new StateError(
- 'Unable to find the enclosing constructor of $context');
+ @override
+ ElementAnnotationImpl buildAnnotation(ElementImpl context, UnlinkedExpr uc) {
+ return unitResynthesizer.buildAnnotation(context, uc);
}
- Expression build() {
- if (!uc.isValidConst) {
- return null;
- }
- try {
- for (UnlinkedExprOperation operation in uc.operations) {
- switch (operation) {
- case UnlinkedExprOperation.pushNull:
- _push(AstTestFactory.nullLiteral());
- break;
- // bool
- case UnlinkedExprOperation.pushFalse:
- _push(AstTestFactory.booleanLiteral(false));
- break;
- case UnlinkedExprOperation.pushTrue:
- _push(AstTestFactory.booleanLiteral(true));
- break;
- // literals
- case UnlinkedExprOperation.pushInt:
- int value = uc.ints[intPtr++];
- _push(AstTestFactory.integer(value));
- break;
- case UnlinkedExprOperation.pushLongInt:
- int value = 0;
- int count = uc.ints[intPtr++];
- for (int i = 0; i < count; i++) {
- int next = uc.ints[intPtr++];
- value = value << 32 | next;
- }
- _push(AstTestFactory.integer(value));
- break;
- case UnlinkedExprOperation.pushDouble:
- double value = uc.doubles[doublePtr++];
- _push(AstTestFactory.doubleLiteral(value));
- break;
- case UnlinkedExprOperation.makeSymbol:
- String component = uc.strings[stringPtr++];
- _push(AstTestFactory.symbolLiteral([component]));
- break;
- // String
- case UnlinkedExprOperation.pushString:
- String value = uc.strings[stringPtr++];
- _push(AstTestFactory.string2(value));
- break;
- case UnlinkedExprOperation.concatenate:
- int count = uc.ints[intPtr++];
- List<InterpolationElement> elements = <InterpolationElement>[];
- for (int i = 0; i < count; i++) {
- Expression expr = _pop();
- InterpolationElement element = _newInterpolationElement(expr);
- elements.insert(0, element);
- }
- _push(AstTestFactory.string(elements));
- break;
- // binary
- case UnlinkedExprOperation.equal:
- _pushBinary(TokenType.EQ_EQ);
- break;
- case UnlinkedExprOperation.notEqual:
- _pushBinary(TokenType.BANG_EQ);
- break;
- case UnlinkedExprOperation.and:
- _pushBinary(TokenType.AMPERSAND_AMPERSAND);
- break;
- case UnlinkedExprOperation.or:
- _pushBinary(TokenType.BAR_BAR);
- break;
- case UnlinkedExprOperation.bitXor:
- _pushBinary(TokenType.CARET);
- break;
- case UnlinkedExprOperation.bitAnd:
- _pushBinary(TokenType.AMPERSAND);
- break;
- case UnlinkedExprOperation.bitOr:
- _pushBinary(TokenType.BAR);
- break;
- case UnlinkedExprOperation.bitShiftLeft:
- _pushBinary(TokenType.LT_LT);
- break;
- case UnlinkedExprOperation.bitShiftRight:
- _pushBinary(TokenType.GT_GT);
- break;
- case UnlinkedExprOperation.add:
- _pushBinary(TokenType.PLUS);
- break;
- case UnlinkedExprOperation.subtract:
- _pushBinary(TokenType.MINUS);
- break;
- case UnlinkedExprOperation.multiply:
- _pushBinary(TokenType.STAR);
- break;
- case UnlinkedExprOperation.divide:
- _pushBinary(TokenType.SLASH);
- break;
- case UnlinkedExprOperation.floorDivide:
- _pushBinary(TokenType.TILDE_SLASH);
- break;
- case UnlinkedExprOperation.modulo:
- _pushBinary(TokenType.PERCENT);
- break;
- case UnlinkedExprOperation.greater:
- _pushBinary(TokenType.GT);
- break;
- case UnlinkedExprOperation.greaterEqual:
- _pushBinary(TokenType.GT_EQ);
- break;
- case UnlinkedExprOperation.less:
- _pushBinary(TokenType.LT);
- break;
- case UnlinkedExprOperation.lessEqual:
- _pushBinary(TokenType.LT_EQ);
- break;
- // prefix
- case UnlinkedExprOperation.complement:
- _pushPrefix(TokenType.TILDE);
- break;
- case UnlinkedExprOperation.negate:
- _pushPrefix(TokenType.MINUS);
- break;
- case UnlinkedExprOperation.not:
- _pushPrefix(TokenType.BANG);
- break;
- // conditional
- case UnlinkedExprOperation.conditional:
- Expression elseExpr = _pop();
- Expression thenExpr = _pop();
- Expression condition = _pop();
- _push(AstTestFactory.conditionalExpression(
- condition, thenExpr, elseExpr));
- break;
- // invokeMethodRef
- case UnlinkedExprOperation.invokeMethodRef:
- _pushInvokeMethodRef();
- break;
- // containers
- case UnlinkedExprOperation.makeUntypedList:
- _pushList(null);
- break;
- case UnlinkedExprOperation.makeTypedList:
- TypeAnnotation itemType = _newTypeName();
- _pushList(
- AstTestFactory.typeArgumentList(<TypeAnnotation>[itemType]));
- break;
- case UnlinkedExprOperation.makeUntypedMap:
- _pushMap(null);
- break;
- case UnlinkedExprOperation.makeTypedMap:
- TypeAnnotation keyType = _newTypeName();
- TypeAnnotation valueType = _newTypeName();
- _pushMap(AstTestFactory
- .typeArgumentList(<TypeAnnotation>[keyType, valueType]));
- break;
- case UnlinkedExprOperation.pushReference:
- _pushReference();
- break;
- case UnlinkedExprOperation.extractProperty:
- _pushExtractProperty();
- break;
- case UnlinkedExprOperation.invokeConstructor:
- _pushInstanceCreation();
- break;
- case UnlinkedExprOperation.pushParameter:
- String name = uc.strings[stringPtr++];
- SimpleIdentifier identifier = AstTestFactory.identifier3(name);
- identifier.staticElement = _enclosingConstructor.parameters
- .firstWhere((parameter) => parameter.name == name,
- orElse: () => throw new StateError(
- 'Unable to resolve constructor parameter: $name'));
- _push(identifier);
- break;
- case UnlinkedExprOperation.ifNull:
- _pushBinary(TokenType.QUESTION_QUESTION);
- break;
- case UnlinkedExprOperation.await:
- Expression expression = _pop();
- _push(AstTestFactory.awaitExpression(expression));
- break;
- case UnlinkedExprOperation.pushSuper:
- case UnlinkedExprOperation.pushThis:
- throw const _UnresolvedReferenceException();
- case UnlinkedExprOperation.assignToRef:
- case UnlinkedExprOperation.assignToProperty:
- case UnlinkedExprOperation.assignToIndex:
- case UnlinkedExprOperation.extractIndex:
- case UnlinkedExprOperation.invokeMethod:
- case UnlinkedExprOperation.cascadeSectionBegin:
- case UnlinkedExprOperation.cascadeSectionEnd:
- case UnlinkedExprOperation.typeCast:
- case UnlinkedExprOperation.typeCheck:
- case UnlinkedExprOperation.throwException:
- case UnlinkedExprOperation.pushLocalFunctionReference:
- case UnlinkedExprOperation.pushError:
- case UnlinkedExprOperation.pushTypedAbstract:
- case UnlinkedExprOperation.pushUntypedAbstract:
- throw new UnimplementedError(
- 'Unexpected $operation in a constant expression.');
- }
- }
- } on _UnresolvedReferenceException {
- return AstTestFactory.identifier3(r'#invalidConst');
- }
- return stack.single;
+ @override
+ Expression buildExpression(ElementImpl context, UnlinkedExpr uc) {
+ return unitResynthesizer._buildConstExpression(context, uc);
}
- List<Expression> _buildArguments() {
- List<Expression> arguments;
- {
- int numNamedArgs = uc.ints[intPtr++];
- int numPositionalArgs = uc.ints[intPtr++];
- int numArgs = numNamedArgs + numPositionalArgs;
- arguments = _removeTopItems(numArgs);
- // add names to the named arguments
- for (int i = 0; i < numNamedArgs; i++) {
- String name = uc.strings[stringPtr++];
- int index = numPositionalArgs + i;
- arguments[index] =
- AstTestFactory.namedExpression2(name, arguments[index]);
- }
- }
- return arguments;
+ @override
+ UnitExplicitTopLevelAccessors buildTopLevelAccessors() {
+ return unitResynthesizer.buildUnitExplicitTopLevelAccessors();
}
- /**
- * Build the identifier sequence (a single or prefixed identifier, or a
- * property access) corresponding to the given reference [info].
- */
- Expression _buildIdentifierSequence(_ReferenceInfo info) {
- Expression enclosing;
- if (info.enclosing != null) {
- enclosing = _buildIdentifierSequence(info.enclosing);
- }
- Element element = info.element;
- if (element == null && info.name == 'length') {
- element = _getStringLengthElement();
- }
- if (enclosing == null) {
- return AstTestFactory.identifier3(info.name)..staticElement = element;
- }
- if (enclosing is SimpleIdentifier) {
- SimpleIdentifier identifier = AstTestFactory.identifier3(info.name)
- ..staticElement = element;
- return AstTestFactory.identifier(enclosing, identifier);
- }
- if (element == null) {
- throw const _UnresolvedReferenceException();
- }
- SimpleIdentifier property = AstTestFactory.identifier3(info.name)
- ..staticElement = element;
- return AstTestFactory.propertyAccess(enclosing, property);
+ @override
+ UnitExplicitTopLevelVariables buildTopLevelVariables() {
+ return unitResynthesizer.buildUnitExplicitTopLevelVariables();
}
- TypeAnnotation _buildTypeAst(DartType type) {
- List<TypeAnnotation> argumentNodes;
- if (type is ParameterizedType) {
- if (!resynthesizer.libraryResynthesizer.typesWithImplicitTypeArguments
- .contains(type)) {
- List<DartType> typeArguments = type.typeArguments;
- argumentNodes = typeArguments.every((a) => a.isDynamic)
- ? null
- : typeArguments.map(_buildTypeAst).toList();
- }
+ @override
+ TopLevelInferenceError getTypeInferenceError(int slot) {
+ return unitResynthesizer.getTypeInferenceError(slot);
+ }
+
+ @override
+ bool inheritsCovariant(int slot) {
+ return unitResynthesizer.parametersInheritingCovariant.contains(slot);
+ }
+
+ @override
+ bool isInConstCycle(int slot) {
+ return unitResynthesizer.constCycles.contains(slot);
+ }
+
+ @override
+ ConstructorElement resolveConstructorRef(
+ ElementImpl context, EntityRef entry) {
+ return unitResynthesizer._getConstructorForEntry(context, entry);
+ }
+
+ @override
+ DartType resolveLinkedType(ElementImpl context, int slot) {
+ return unitResynthesizer.buildLinkedType(context, slot);
+ }
+
+ @override
+ DartType resolveTypeRef(ElementImpl context, EntityRef type,
+ {bool defaultVoid: false,
+ bool instantiateToBoundsAllowed: true,
+ bool declaredType: false}) {
+ return unitResynthesizer.buildType(context, type,
+ defaultVoid: defaultVoid,
+ instantiateToBoundsAllowed: instantiateToBoundsAllowed,
+ declaredType: declaredType);
+ }
+}
+
+/// An instance of [_UnitResynthesizer] is responsible for resynthesizing the
+/// elements in a single unit from that unit's summary.
+abstract class UnitResynthesizer {
+ /// Gets the [TypeProvider], which may be used to create core types.
+ TypeProvider get typeProvider;
+
+ /// Builds a [DartType] object based on a [EntityRef]. This [DartType]
+ /// may refer to elements in other libraries than the library being
+ /// deserialized, so handles may be used to avoid having to deserialize other
+ /// libraries in the process.
+ DartType buildType(ElementImpl context, EntityRef type);
+
+ /// Builds a [DartType] object based on [ReferenceInfo], which should refer to
+ /// a class, by filling in the type arguments as appropriate, and performing
+ /// instantiate to bounds if necessary.
+ DartType buildTypeForClassInfo(ReferenceInfo info, int numTypeArguments,
+ DartType getTypeArgument(int i));
+
+ /// Returns the defining type for a [ConstructorElement] by applying
+ /// [typeArgumentRefs] to the given linked [info]. Returns [DynamicTypeImpl]
+ /// if the [info] is unresolved.
+ DartType createConstructorDefiningType(ElementImpl context,
+ ReferenceInfo info, List<EntityRef> typeArgumentRefs);
+
+ /// Determines if the given [type] has implicit type arguments.
+ bool doesTypeHaveImplicitArguments(ParameterizedType type);
+
+ /// Returns the [ConstructorElement] corresponding to the given linked [info],
+ /// using the [classType] which has already been computed (e.g. by
+ /// [createConstructorDefiningType]). Both cases when [info] is a
+ /// [ClassElement] and [ConstructorElement] are supported.
+ ConstructorElement getConstructorForInfo(
+ InterfaceType classType, ReferenceInfo info);
+
+ /// Returns the [ReferenceInfo] with the given [index].
+ ReferenceInfo getReferenceInfo(int index);
+}
+
+/// [UnitResynthesizerMixin] contains methods useful for implementing the
+/// [UnitResynthesizer] interface.
+abstract class UnitResynthesizerMixin implements UnitResynthesizer {
+ @override
+ DartType createConstructorDefiningType(ElementImpl context,
+ ReferenceInfo info, List<EntityRef> typeArgumentRefs) {
+ bool isClass = info.element is ClassElement;
+ ReferenceInfo classInfo = isClass ? info : info.enclosing;
+ if (classInfo == null) {
+ return DynamicTypeImpl.instance;
}
- TypeName node = AstTestFactory.typeName4(type.name, argumentNodes);
- node.type = type;
- (node.name as SimpleIdentifier).staticElement = type.element;
- return node;
- }
-
- PropertyAccessorElement _getStringLengthElement() =>
- resynthesizer.typeProvider.stringType.getGetter('length');
-
- InterpolationElement _newInterpolationElement(Expression expr) {
- if (expr is SimpleStringLiteral) {
- return astFactory.interpolationString(expr.literal, expr.value);
- } else {
- return astFactory.interpolationExpression(
- TokenFactory.tokenFromType(TokenType.STRING_INTERPOLATION_EXPRESSION),
- expr,
- TokenFactory.tokenFromType(TokenType.CLOSE_CURLY_BRACKET));
- }
- }
-
- /**
- * Convert the next reference to the [DartType] and return the AST
- * corresponding to this type.
- */
- TypeAnnotation _newTypeName() {
- EntityRef typeRef = uc.references[refPtr++];
- DartType type = resynthesizer.buildType(context, typeRef);
- return _buildTypeAst(type);
- }
-
- Expression _pop() => stack.removeLast();
-
- void _push(Expression expr) {
- stack.add(expr);
- }
-
- void _pushBinary(TokenType operator) {
- Expression right = _pop();
- Expression left = _pop();
- _push(AstTestFactory.binaryExpression(left, operator, right));
- }
-
- void _pushExtractProperty() {
- Expression target = _pop();
- String name = uc.strings[stringPtr++];
- SimpleIdentifier propertyNode = AstTestFactory.identifier3(name);
- // Only String.length property access can be potentially resolved.
- if (name == 'length') {
- propertyNode.staticElement = _getStringLengthElement();
- }
- _push(AstTestFactory.propertyAccess(target, propertyNode));
- }
-
- void _pushInstanceCreation() {
- EntityRef ref = uc.references[refPtr++];
- _ReferenceInfo info = resynthesizer.getReferenceInfo(ref.reference);
- // prepare ConstructorElement
- TypeName typeNode;
- String constructorName;
- ConstructorElement constructorElement;
- if (info.element != null) {
- if (info.element is ConstructorElement) {
- constructorName = info.name;
- } else if (info.element is ClassElement) {
- constructorName = null;
+ List<DartType> typeArguments =
+ typeArgumentRefs.map((t) => buildType(context, t)).toList();
+ return buildTypeForClassInfo(classInfo, typeArguments.length, (i) {
+ if (i < typeArguments.length) {
+ return typeArguments[i];
} else {
- List<Expression> arguments = _buildArguments();
- SimpleIdentifier name = AstTestFactory.identifier3(info.name);
- name.staticElement = info.element;
- name.setProperty(ARGUMENT_LIST, AstTestFactory.argumentList(arguments));
- _push(name);
- return;
+ return DynamicTypeImpl.instance;
}
- InterfaceType definingType = resynthesizer._createConstructorDefiningType(
- context, info, ref.typeArguments);
- constructorElement =
- resynthesizer._getConstructorForInfo(definingType, info);
- typeNode = _buildTypeAst(definingType);
- } else {
- if (info.enclosing != null) {
- if (info.enclosing.enclosing != null) {
- PrefixedIdentifier typeName = AstTestFactory.identifier5(
- info.enclosing.enclosing.name, info.enclosing.name);
- typeName.prefix.staticElement = info.enclosing.enclosing.element;
- typeName.identifier.staticElement = info.enclosing.element;
- typeName.identifier.staticType = info.enclosing.type;
- typeNode = AstTestFactory.typeName3(typeName);
- typeNode.type = info.enclosing.type;
- constructorName = info.name;
- } else if (info.enclosing.element != null) {
- SimpleIdentifier typeName =
- AstTestFactory.identifier3(info.enclosing.name);
- typeName.staticElement = info.enclosing.element;
- typeName.staticType = info.enclosing.type;
- typeNode = AstTestFactory.typeName3(typeName);
- typeNode.type = info.enclosing.type;
- constructorName = info.name;
- } else {
- typeNode = AstTestFactory.typeName3(
- AstTestFactory.identifier5(info.enclosing.name, info.name));
- constructorName = null;
- }
- } else {
- typeNode = AstTestFactory.typeName4(info.name);
- }
- }
- // prepare arguments
- List<Expression> arguments = _buildArguments();
- // create ConstructorName
- ConstructorName constructorNode;
- if (constructorName != null) {
- constructorNode =
- AstTestFactory.constructorName(typeNode, constructorName);
- constructorNode.name.staticElement = constructorElement;
- } else {
- constructorNode = AstTestFactory.constructorName(typeNode, null);
- }
- constructorNode.staticElement = constructorElement;
- if (constructorElement == null) {
- throw const _UnresolvedReferenceException();
- }
- // create InstanceCreationExpression
- InstanceCreationExpression instanceCreation = AstTestFactory
- .instanceCreationExpression(Keyword.CONST, constructorNode, arguments);
- instanceCreation.staticElement = constructorElement;
- _push(instanceCreation);
+ });
}
- void _pushInvokeMethodRef() {
- List<Expression> arguments = _buildArguments();
- EntityRef ref = uc.references[refPtr++];
- _ReferenceInfo info = resynthesizer.getReferenceInfo(ref.reference);
- Expression node = _buildIdentifierSequence(info);
- TypeArgumentList typeArguments;
- int numTypeArguments = uc.ints[intPtr++];
- if (numTypeArguments > 0) {
- List<TypeAnnotation> typeNames =
- new List<TypeAnnotation>(numTypeArguments);
- for (int i = 0; i < numTypeArguments; i++) {
- typeNames[i] = _newTypeName();
- }
- typeArguments = AstTestFactory.typeArgumentList(typeNames);
+ @override
+ ConstructorElement getConstructorForInfo(
+ InterfaceType classType, ReferenceInfo info) {
+ ConstructorElement element;
+ Element infoElement = info.element;
+ if (infoElement is ConstructorElement) {
+ element = infoElement;
+ } else if (infoElement is ClassElement) {
+ element = infoElement.unnamedConstructor;
}
- if (node is SimpleIdentifier) {
- _push(astFactory.methodInvocation(
- null,
- TokenFactory.tokenFromType(TokenType.PERIOD),
- node,
- typeArguments,
- AstTestFactory.argumentList(arguments)));
- } else {
- throw new UnimplementedError('For ${node?.runtimeType}: $node');
+ if (element != null && info.hasTypeParameters) {
+ return new ConstructorMember(element, classType);
}
- }
-
- void _pushList(TypeArgumentList typeArguments) {
- int count = uc.ints[intPtr++];
- List<Expression> elements = <Expression>[];
- for (int i = 0; i < count; i++) {
- elements.insert(0, _pop());
- }
- _push(AstTestFactory.listLiteral2(Keyword.CONST, typeArguments, elements));
- }
-
- void _pushMap(TypeArgumentList typeArguments) {
- int count = uc.ints[intPtr++];
- List<MapLiteralEntry> entries = <MapLiteralEntry>[];
- for (int i = 0; i < count; i++) {
- Expression value = _pop();
- Expression key = _pop();
- entries.insert(0, AstTestFactory.mapLiteralEntry2(key, value));
- }
- _push(AstTestFactory.mapLiteral(Keyword.CONST, typeArguments, entries));
- }
-
- void _pushPrefix(TokenType operator) {
- Expression operand = _pop();
- _push(AstTestFactory.prefixExpression(operator, operand));
- }
-
- void _pushReference() {
- EntityRef ref = uc.references[refPtr++];
- _ReferenceInfo info = resynthesizer.getReferenceInfo(ref.reference);
- Expression node = _buildIdentifierSequence(info);
- if (node is Identifier && node.staticElement == null) {
- throw const _UnresolvedReferenceException();
- }
- _push(node);
- }
-
- List<Expression> _removeTopItems(int count) {
- int start = stack.length - count;
- int end = stack.length;
- List<Expression> items = stack.getRange(start, end).toList();
- stack.removeRange(start, end);
- return items;
+ return element;
}
}
@@ -814,11 +556,9 @@
ElementLocation get location => actualElement.location;
}
-/**
- * An instance of [_LibraryResynthesizer] is responsible for resynthesizing the
- * elements in a single library from that library's summary.
- */
-class _LibraryResynthesizer {
+/// Specialization of [LibraryResynthesizer] for resynthesis from linked
+/// summaries.
+class _LibraryResynthesizer extends LibraryResynthesizerMixin {
/**
* The [SummaryResynthesizer] which is being used to obtain summaries.
*/
@@ -861,19 +601,15 @@
final Map<String, CompilationUnitElementImpl> resynthesizedUnits =
<String, CompilationUnitElementImpl>{};
- /**
- * Types with implicit type arguments, which are the same as type parameter
- * bounds (in strong mode), or `dynamic` (in spec mode).
- */
- final Set<DartType> typesWithImplicitTypeArguments =
- new Set<DartType>.identity();
-
_LibraryResynthesizer(this.summaryResynthesizer, this.linkedLibrary,
this.unlinkedUnits, this.librarySource) {
libraryUri = librarySource.uri.toString();
isCoreLibrary = libraryUri == 'dart:core';
}
+ @override
+ List<LinkedExportName> get linkedExportNames => linkedLibrary.exportNames;
+
/**
* Resynthesize a [NamespaceCombinator].
*/
@@ -885,10 +621,7 @@
}
}
- /**
- * Build an [ElementHandle] referring to the entity referred to by the given
- * [exportName].
- */
+ @override
ElementHandle buildExportName(LinkedExportName exportName) {
String name = exportName.name;
if (exportName.kind == ReferenceKind.topLevelPropertyAccessor &&
@@ -927,25 +660,6 @@
}
/**
- * Build the export namespace for the library by aggregating together its
- * [publicNamespace] and [exportNames].
- */
- Namespace buildExportNamespace(
- Namespace publicNamespace, List<LinkedExportName> exportNames) {
- Map<String, Element> definedNames = new HashMap<String, Element>();
- // Start by populating all the public names from [publicNamespace].
- publicNamespace.definedNames.forEach((String name, Element element) {
- definedNames[name] = element;
- });
- // Add all the names from [exportNames].
- for (LinkedExportName exportName in exportNames) {
- definedNames.putIfAbsent(
- exportName.name, () => buildExportName(exportName));
- }
- return new Namespace(definedNames);
- }
-
- /**
* Main entry point. Resynthesize the [LibraryElement] and return it.
*/
LibraryElement buildLibrary() {
@@ -1080,7 +794,8 @@
/**
* Implementation of [LibraryResynthesizerContext] for [_LibraryResynthesizer].
*/
-class _LibraryResynthesizerContext implements LibraryResynthesizerContext {
+class _LibraryResynthesizerContext extends LibraryResynthesizerContextMixin
+ implements LibraryResynthesizerContext {
final _LibraryResynthesizer resynthesizer;
_LibraryResynthesizerContext(this.resynthesizer);
@@ -1094,25 +809,12 @@
}
@override
- Namespace buildExportNamespace() {
- LibraryElementImpl library = resynthesizer.library;
- return resynthesizer.buildExportNamespace(
- library.publicNamespace, resynthesizer.linkedLibrary.exportNames);
- }
-
- @override
LibraryElement buildImportedLibrary(int dependency) {
String depUri = resynthesizer.linkedLibrary.dependencies[dependency].uri;
return _getLibraryByRelativeUri(depUri);
}
@override
- Namespace buildPublicNamespace() {
- LibraryElementImpl library = resynthesizer.library;
- return new NamespaceBuilder().createPublicNamespaceForLibrary(library);
- }
-
- @override
FunctionElement findEntryPoint() {
LibraryElementImpl library = resynthesizer.library;
Element entryPoint =
@@ -1141,25 +843,17 @@
}
}
-/**
- * Data structure used during resynthesis to record all the information that is
- * known about how to resynthesize a single entry in [LinkedUnit.references]
- * (and its associated entry in [UnlinkedUnit.references], if it exists).
- */
-class _ReferenceInfo {
+/// Specialization of [ReferenceInfo] for resynthesis from linked summaries.
+class _ReferenceInfo extends ReferenceInfo {
/**
* The [_LibraryResynthesizer] which is being used to obtain summaries.
*/
final _LibraryResynthesizer libraryResynthesizer;
- /**
- * The enclosing [_ReferenceInfo], or `null` for top-level elements.
- */
+ @override
final _ReferenceInfo enclosing;
- /**
- * The name of the entity referred to by this reference.
- */
+ @override
final String name;
/**
@@ -1167,11 +861,7 @@
*/
final bool isDeclarableType;
- /**
- * The element referred to by this reference, or `null` if there is no
- * associated element (e.g. because it is a reference to an undefined
- * entity).
- */
+ @override
final Element element;
/**
@@ -1211,10 +901,10 @@
}
}
- /**
- * If this reference refers to a non-generic type, the type it refers to.
- * Otherwise `null`.
- */
+ @override
+ bool get hasTypeParameters => numTypeParameters != 0;
+
+ @override
DartType get type {
if (_type == null) {
_type = _buildType(true, 0, (_) => DynamicTypeImpl.instance, const []);
@@ -1293,7 +983,7 @@
// Mark the type as having implicit type arguments, so that we don't
// attempt to request them during constant expression resynthesizing.
if (typeArguments == null) {
- libraryResynthesizer.typesWithImplicitTypeArguments.add(type);
+ _typesWithImplicitTypeArguments[type] = true;
}
// Done.
return type;
@@ -1405,77 +1095,8 @@
}
}
-class _ResynthesizerContext implements ResynthesizerContext {
- final _UnitResynthesizer _unitResynthesizer;
-
- _ResynthesizerContext(this._unitResynthesizer);
-
- @override
- bool get isStrongMode => _unitResynthesizer.summaryResynthesizer.strongMode;
-
- @override
- ElementAnnotationImpl buildAnnotation(ElementImpl context, UnlinkedExpr uc) {
- return _unitResynthesizer.buildAnnotation(context, uc);
- }
-
- @override
- Expression buildExpression(ElementImpl context, UnlinkedExpr uc) {
- return _unitResynthesizer._buildConstExpression(context, uc);
- }
-
- @override
- UnitExplicitTopLevelAccessors buildTopLevelAccessors() {
- return _unitResynthesizer.buildUnitExplicitTopLevelAccessors();
- }
-
- @override
- UnitExplicitTopLevelVariables buildTopLevelVariables() {
- return _unitResynthesizer.buildUnitExplicitTopLevelVariables();
- }
-
- @override
- TopLevelInferenceError getTypeInferenceError(int slot) {
- return _unitResynthesizer.getTypeInferenceError(slot);
- }
-
- @override
- bool inheritsCovariant(int slot) {
- return _unitResynthesizer.parametersInheritingCovariant.contains(slot);
- }
-
- @override
- bool isInConstCycle(int slot) {
- return _unitResynthesizer.constCycles.contains(slot);
- }
-
- @override
- ConstructorElement resolveConstructorRef(
- ElementImpl context, EntityRef entry) {
- return _unitResynthesizer._getConstructorForEntry(context, entry);
- }
-
- @override
- DartType resolveLinkedType(ElementImpl context, int slot) {
- return _unitResynthesizer.buildLinkedType(context, slot);
- }
-
- @override
- DartType resolveTypeRef(ElementImpl context, EntityRef type,
- {bool defaultVoid: false,
- bool instantiateToBoundsAllowed: true,
- bool declaredType: false}) {
- return _unitResynthesizer.buildType(context, type,
- defaultVoid: defaultVoid,
- instantiateToBoundsAllowed: instantiateToBoundsAllowed,
- declaredType: declaredType);
- }
-}
-
-/**
- * An instance of [_UnitResynthesizer] is responsible for resynthesizing the
- * elements in a single unit from that unit's summary.
- */
-class _UnitResynthesizer {
+/// Specialization of [UnitResynthesizer] for resynthesis from linked summaries.
+class _UnitResynthesizer extends UnitResynthesizer with UnitResynthesizerMixin {
/**
* The [_LibraryResynthesizer] which is being used to obtain summaries.
*/
@@ -1532,7 +1153,7 @@
_UnitResynthesizer(this.libraryResynthesizer, this.unlinkedUnit,
this.linkedUnit, Source unitSource, UnlinkedPart unlinkedPart) {
- _resynthesizerContext = new _ResynthesizerContext(this);
+ _resynthesizerContext = new SummaryResynthesizerContext(this);
unit = new CompilationUnitElementImpl.forSerialized(
libraryResynthesizer.library,
_resynthesizerContext,
@@ -1562,6 +1183,7 @@
SummaryResynthesizer get summaryResynthesizer =>
libraryResynthesizer.summaryResynthesizer;
+ @override
TypeProvider get typeProvider => summaryResynthesizer.typeProvider;
/**
@@ -1574,8 +1196,7 @@
// Invalid constant expression.
} else if (constExpr is Identifier) {
var element = constExpr.staticElement;
- ArgumentList arguments =
- constExpr.getProperty(_ConstExprBuilder.ARGUMENT_LIST);
+ ArgumentList arguments = constExpr.getProperty(ExprBuilder.ARGUMENT_LIST);
if (element is PropertyAccessorElement && arguments == null) {
elementAnnotation.element = element;
elementAnnotation.annotationAst = AstTestFactory.annotation(constExpr);
@@ -1604,8 +1225,7 @@
var target = constExpr.target as Identifier;
var propertyName = constExpr.propertyName;
var propertyElement = propertyName.staticElement;
- ArgumentList arguments =
- constExpr.getProperty(_ConstExprBuilder.ARGUMENT_LIST);
+ ArgumentList arguments = constExpr.getProperty(ExprBuilder.ARGUMENT_LIST);
if (propertyElement is PropertyAccessorElement && arguments == null) {
elementAnnotation.element = propertyElement;
elementAnnotation.annotationAst = AstTestFactory.annotation2(
@@ -1669,12 +1289,7 @@
return buildType(context, type);
}
- /**
- * Build a [DartType] object based on a [EntityRef]. This [DartType]
- * may refer to elements in other libraries than the library being
- * deserialized, so handles are used to avoid having to deserialize other
- * libraries in the process.
- */
+ @override
DartType buildType(ElementImpl context, EntityRef type,
{bool defaultVoid: false,
bool instantiateToBoundsAllowed: true,
@@ -1725,6 +1340,11 @@
}
}
+ @override
+ DartType buildTypeForClassInfo(covariant _ReferenceInfo info,
+ int numTypeArguments, DartType getTypeArgument(int i)) =>
+ info.buildType(true, numTypeArguments, getTypeArgument, const <int>[]);
+
UnitExplicitTopLevelAccessors buildUnitExplicitTopLevelAccessors() {
Map<String, TopLevelVariableElementImpl> implicitVariables =
new HashMap<String, TopLevelVariableElementImpl>();
@@ -1795,9 +1415,11 @@
return variablesData;
}
- /**
- * Return [_ReferenceInfo] with the given [index], lazily resolving it.
- */
+ @override
+ bool doesTypeHaveImplicitArguments(ParameterizedType type) =>
+ _typesWithImplicitTypeArguments[type] != null;
+
+ @override
_ReferenceInfo getReferenceInfo(int index) {
_ReferenceInfo result = referenceInfos[index];
if (result == null) {
@@ -1939,30 +1561,7 @@
}
Expression _buildConstExpression(ElementImpl context, UnlinkedExpr uc) {
- return new _ConstExprBuilder(this, context, uc).build();
- }
-
- /**
- * Return the defining type for a [ConstructorElement] by applying
- * [typeArgumentRefs] to the given linked [info]. Return [DynamicTypeImpl]
- * if the [info] is unresolved.
- */
- DartType _createConstructorDefiningType(ElementImpl context,
- _ReferenceInfo info, List<EntityRef> typeArgumentRefs) {
- bool isClass = info.element is ClassElement;
- _ReferenceInfo classInfo = isClass ? info : info.enclosing;
- if (classInfo == null) {
- return DynamicTypeImpl.instance;
- }
- List<DartType> typeArguments =
- typeArgumentRefs.map((t) => buildType(context, t)).toList();
- return classInfo.buildType(true, typeArguments.length, (i) {
- if (i < typeArguments.length) {
- return typeArguments[i];
- } else {
- return DynamicTypeImpl.instance;
- }
- }, const <int>[]);
+ return new ExprBuilder(this, context, uc).build();
}
/**
@@ -1972,35 +1571,14 @@
ElementImpl context, EntityRef entry) {
_ReferenceInfo info = getReferenceInfo(entry.reference);
DartType type =
- _createConstructorDefiningType(context, info, entry.typeArguments);
+ createConstructorDefiningType(context, info, entry.typeArguments);
if (type is InterfaceType) {
- return _getConstructorForInfo(type, info);
+ return getConstructorForInfo(type, info);
}
return null;
}
/**
- * Return the [ConstructorElement] corresponding to the given linked [info],
- * using the [classType] which has already been computed (e.g. by
- * [_createConstructorDefiningType]). Both cases when [info] is a
- * [ClassElement] and [ConstructorElement] are supported.
- */
- ConstructorElement _getConstructorForInfo(
- InterfaceType classType, _ReferenceInfo info) {
- ConstructorElement element;
- Element infoElement = info.element;
- if (infoElement is ConstructorElement) {
- element = infoElement;
- } else if (infoElement is ClassElement) {
- element = infoElement.unnamedConstructor;
- }
- if (element != null && info.numTypeParameters != 0) {
- return new ConstructorMember(element, classType);
- }
- return element;
- }
-
- /**
* If the given [kind] is a top-level or class member property accessor, and
* the given [name] does not end with `=`, i.e. does not denote a setter,
* return the getter identifier by appending `?`.
@@ -2015,12 +1593,3 @@
return name;
}
}
-
-/**
- * This exception is thrown when we detect that the constant expression
- * being resynthesized cannot be fully resolved, so is not a valid constant
- * expression.
- */
-class _UnresolvedReferenceException {
- const _UnresolvedReferenceException();
-}
diff --git a/pkg/analyzer/lib/src/summary/summarize_const_expr.dart b/pkg/analyzer/lib/src/summary/summarize_const_expr.dart
index 91b8015..2cf21ed 100644
--- a/pkg/analyzer/lib/src/summary/summarize_const_expr.dart
+++ b/pkg/analyzer/lib/src/summary/summarize_const_expr.dart
@@ -423,6 +423,9 @@
_serialize(expr.expression);
references.add(serializeType(expr.type));
operations.add(UnlinkedExprOperation.typeCheck);
+ if (expr.notOperator != null) {
+ operations.add(UnlinkedExprOperation.not);
+ }
} else if (expr is SuperExpression) {
operations.add(UnlinkedExprOperation.pushSuper);
} else if (expr is ThisExpression) {
diff --git a/pkg/analyzer/test/generated/parser_test.dart b/pkg/analyzer/test/generated/parser_test.dart
index fb9fe1c..18fa2ba 100644
--- a/pkg/analyzer/test/generated/parser_test.dart
+++ b/pkg/analyzer/test/generated/parser_test.dart
@@ -3681,6 +3681,7 @@
parseStatement("get x { return _x; }", expectedEndOffset: 4);
if (usingFastaParser) {
// Fasta considers `get` to be an identifier in this situation.
+ // TODO(danrubel): Investigate better recovery.
ExpressionStatement statement = result;
listener
.assertErrors([expectedError(ParserErrorCode.EXPECTED_TOKEN, 4, 1)]);
@@ -3959,9 +3960,8 @@
expectNotNullIfNoErrors(unit);
listener.assertErrors(usingFastaParser
? [
- expectedError(ParserErrorCode.EXPECTED_TOKEN, 23, 5),
- expectedError(ParserErrorCode.MISSING_KEYWORD_OPERATOR, 28, 1),
- expectedError(ParserErrorCode.MISSING_METHOD_PARAMETERS, 28, 0)
+ expectedError(ParserErrorCode.UNEXPECTED_TOKEN, 23, 5),
+ expectedError(ParserErrorCode.MISSING_METHOD_PARAMETERS, 28, 1)
]
: [
expectedError(ParserErrorCode.EXPECTED_TOKEN, 14, 8),
@@ -5590,6 +5590,7 @@
void test_varAsTypeName_as() {
parseExpression("x as var",
+ expectedEndOffset: 5,
errors: usingFastaParser
? [expectedError(ParserErrorCode.EXPECTED_TYPE_NAME, 5, 3)]
: [expectedError(ParserErrorCode.VAR_AS_TYPE_NAME, 7, 3)]);
@@ -15859,7 +15860,7 @@
for (Keyword keyword in Keyword.values) {
if (keyword.isBuiltIn || keyword.isPseudo) {
String lexeme = keyword.lexeme;
- if (lexeme == 'Function' && !usingFastaParser) continue;
+ if (lexeme == 'Function') continue;
parseCompilationUnit('$lexeme(x) => 0;');
parseCompilationUnit('class C {$lexeme(x) => 0;}');
}
@@ -15871,6 +15872,7 @@
for (Keyword keyword in Keyword.values) {
if (keyword.isBuiltIn || keyword.isPseudo) {
String lexeme = keyword.lexeme;
+ if (lexeme == 'Function') continue;
// The fasta type resolution phase will report an error
// on type arguments on `dynamic` (e.g. `dynamic<int>`).
parseCompilationUnit('$lexeme<T>(x) => 0;');
diff --git a/pkg/analyzer/test/src/dart/ast/utilities_test.dart b/pkg/analyzer/test/src/dart/ast/utilities_test.dart
index 72483ab..a439379 100644
--- a/pkg/analyzer/test/src/dart/ast/utilities_test.dart
+++ b/pkg/analyzer/test/src/dart/ast/utilities_test.dart
@@ -1209,6 +1209,16 @@
TokenType.PLUS, AstTestFactory.identifier3("b")));
}
+ void test_visitBinaryExpression_precedence() {
+ var a = AstTestFactory.identifier3('a');
+ var b = AstTestFactory.identifier3('b');
+ var c = AstTestFactory.identifier3('c');
+ _assertSource(
+ 'a * (b + c)',
+ AstTestFactory.binaryExpression(a, TokenType.STAR,
+ AstTestFactory.binaryExpression(b, TokenType.PLUS, c)));
+ }
+
void test_visitBlock_empty() {
_assertSource("{}", AstTestFactory.block());
}
@@ -3100,6 +3110,15 @@
TokenType.MINUS, AstTestFactory.identifier3("a")));
}
+ void test_visitPrefixExpression_precedence() {
+ var a = AstTestFactory.identifier3('a');
+ var b = AstTestFactory.identifier3('b');
+ _assertSource(
+ '!(a == b)',
+ AstTestFactory.prefixExpression(TokenType.BANG,
+ AstTestFactory.binaryExpression(a, TokenType.EQ_EQ, b)));
+ }
+
void test_visitPropertyAccess() {
_assertSource("a.b",
AstTestFactory.propertyAccess2(AstTestFactory.identifier3("a"), "b"));
diff --git a/pkg/analyzer/test/src/summary/expr_builder_test.dart b/pkg/analyzer/test/src/summary/expr_builder_test.dart
new file mode 100644
index 0000000..9e8237f
--- /dev/null
+++ b/pkg/analyzer/test/src/summary/expr_builder_test.dart
@@ -0,0 +1,475 @@
+// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+import 'package:analyzer/dart/ast/ast.dart';
+import 'package:analyzer/src/dart/element/element.dart';
+import 'package:analyzer/src/summary/expr_builder.dart';
+import 'package:analyzer/src/summary/idl.dart';
+import 'package:analyzer/src/summary/resynthesize.dart';
+import 'package:test/test.dart';
+import 'package:test_reflective_loader/test_reflective_loader.dart';
+
+import '../abstract_single_unit.dart';
+import 'resynthesize_ast_test.dart';
+import 'resynthesize_common.dart';
+
+main() {
+ defineReflectiveSuite(() {
+ defineReflectiveTests(ExprBuilderTest);
+ });
+}
+
+@reflectiveTest
+class ExprBuilderTest extends AbstractSingleUnitTest
+ with AstSerializeTestMixin {
+ @override
+ bool get allowMissingFiles => false;
+
+ Expression buildConstructorInitializer(String sourceText,
+ {String className: 'C',
+ String initializerName: 'x',
+ bool requireValidConst: false}) {
+ var resynthesizer = encodeSource(sourceText);
+ var library = resynthesizer.getLibraryElement(testSource.uri.toString());
+ var c = library.getType(className);
+ var constructor = c.unnamedConstructor as ConstructorElementImpl;
+ var serializedExecutable = constructor.serializedExecutable;
+ var x = serializedExecutable.constantInitializers
+ .singleWhere((i) => i.name == initializerName);
+ return buildExpression(resynthesizer, constructor, x.expression,
+ serializedExecutable.localFunctions,
+ requireValidConst: requireValidConst);
+ }
+
+ Expression buildExpression(
+ TestSummaryResynthesizer resynthesizer,
+ ElementImpl context,
+ UnlinkedExpr unlinkedExpr,
+ List<UnlinkedExecutable> localFunctions,
+ {bool requireValidConst: false}) {
+ var library = resynthesizer.getLibraryElement(testSource.uri.toString());
+ var unit = library.definingCompilationUnit as CompilationUnitElementImpl;
+ var unitResynthesizerContext =
+ unit.resynthesizerContext as SummaryResynthesizerContext;
+ var unitResynthesizer = unitResynthesizerContext.unitResynthesizer;
+ var exprBuilder = new ExprBuilder(unitResynthesizer, context, unlinkedExpr,
+ requireValidConst: requireValidConst, localFunctions: localFunctions);
+ return exprBuilder.build();
+ }
+
+ Expression buildTopLevelVariable(String sourceText,
+ {String variableName: 'x', bool requireValidConst: false}) {
+ var resynthesizer = encodeSource(sourceText);
+ var library = resynthesizer.getLibraryElement(testSource.uri.toString());
+ var unit = library.definingCompilationUnit as CompilationUnitElementImpl;
+ TopLevelVariableElementImpl x =
+ unit.topLevelVariables.singleWhere((e) => e.name == variableName);
+ return buildExpression(
+ resynthesizer,
+ x,
+ x.unlinkedVariableForTesting.initializer.bodyExpr,
+ x.unlinkedVariableForTesting.initializer.localFunctions,
+ requireValidConst: requireValidConst);
+ }
+
+ void checkCompoundAssignment(String exprText) {
+ checkSimpleExpression(exprText, extraDeclarations: 'var y;');
+ }
+
+ void checkConstructorInitializer(String sourceText, String expectedText,
+ {String className: 'C',
+ String initializerName: 'x',
+ bool requireValidConst: false}) {
+ Expression expr = buildConstructorInitializer(sourceText,
+ className: className,
+ initializerName: initializerName,
+ requireValidConst: requireValidConst);
+ expect(expr.toString(), expectedText);
+ }
+
+ void checkInvalidConst(String expressionText) {
+ checkTopLevelVariable('var x = $expressionText;', 'null',
+ requireValidConst: true);
+ }
+
+ void checkSimpleExpression(String expressionText,
+ {String expectedText,
+ String extraDeclarations: '',
+ bool requireValidConst: false}) {
+ checkTopLevelVariable('var x = $expressionText;\n$extraDeclarations',
+ expectedText ?? expressionText,
+ requireValidConst: requireValidConst);
+ }
+
+ void checkTopLevelVariable(String sourceText, String expectedText,
+ {String variableName: 'x', bool requireValidConst: false}) {
+ Expression expr = buildTopLevelVariable(sourceText,
+ variableName: variableName, requireValidConst: requireValidConst);
+ expect(expr.toString(), expectedText);
+ }
+
+ TestSummaryResynthesizer encodeSource(String text) {
+ var source = addTestSource(text);
+ return encodeLibrary(source);
+ }
+
+ void test_add() {
+ checkSimpleExpression('0 + 1');
+ }
+
+ void test_and() {
+ checkSimpleExpression('false && true');
+ }
+
+ void test_assignToIndex() {
+ checkSimpleExpression('items[0] = 1',
+ extraDeclarations: 'var items = [0, 1, 2]');
+ }
+
+ void test_assignToIndex_compound_multiply() {
+ checkSimpleExpression('items[0] *= 1',
+ extraDeclarations: 'var items = [0, 1, 2]');
+ }
+
+ void test_assignToProperty() {
+ checkSimpleExpression('new A().f = 1', extraDeclarations: r'''
+class A {
+ int f = 0;
+}
+''');
+ }
+
+ void test_assignToProperty_compound_plus() {
+ checkSimpleExpression('new A().f += 1', extraDeclarations: r'''
+class A {
+ int f = 0;
+}
+''');
+ }
+
+ void test_assignToProperty_compound_suffixIncrement() {
+ checkSimpleExpression('new A().f++', extraDeclarations: r'''
+class A {
+ int f = 0;
+}
+''');
+ }
+
+ void test_assignToRef() {
+ checkSimpleExpression('y = 0', extraDeclarations: 'var y;');
+ }
+
+ void test_bitAnd() {
+ checkSimpleExpression('0 & 1');
+ }
+
+ void test_bitOr() {
+ checkSimpleExpression('0 | 1');
+ }
+
+ void test_bitShiftLeft() {
+ checkSimpleExpression('0 << 1');
+ }
+
+ void test_bitShiftRight() {
+ checkSimpleExpression('0 >> 1');
+ }
+
+ void test_bitXor() {
+ checkSimpleExpression('0 ^ 1');
+ }
+
+ void test_cascade() {
+ // Cascade sections don't matter for type inference.
+ // The type of a cascade is the type of the target.
+ checkSimpleExpression('new C()..f1 = 1..m(2, 3)..f2 = 4',
+ extraDeclarations: r'''
+class C {
+ int f1;
+ int f2;
+ int m(int a, int b) => 0;
+}
+''',
+ expectedText: 'new C()');
+ }
+
+ void test_closure_invalid_const() {
+ checkInvalidConst('() => 0');
+ }
+
+ void test_complement() {
+ checkSimpleExpression('~0');
+ }
+
+ void test_compoundAssignment_bitAnd() {
+ checkCompoundAssignment('y &= 0');
+ }
+
+ void test_compoundAssignment_bitOr() {
+ checkCompoundAssignment('y |= 0');
+ }
+
+ void test_compoundAssignment_bitXor() {
+ checkCompoundAssignment('y ^= 0');
+ }
+
+ void test_compoundAssignment_divide() {
+ checkCompoundAssignment('y /= 0');
+ }
+
+ void test_compoundAssignment_floorDivide() {
+ checkCompoundAssignment('y ~/= 0');
+ }
+
+ void test_compoundAssignment_ifNull() {
+ checkCompoundAssignment('y ??= 0');
+ }
+
+ void test_compoundAssignment_minus() {
+ checkCompoundAssignment('y -= 0');
+ }
+
+ void test_compoundAssignment_modulo() {
+ checkCompoundAssignment('y %= 0');
+ }
+
+ void test_compoundAssignment_multiply() {
+ checkCompoundAssignment('y *= 0');
+ }
+
+ void test_compoundAssignment_plus() {
+ checkCompoundAssignment('y += 0');
+ }
+
+ void test_compoundAssignment_postfixDecrement() {
+ checkCompoundAssignment('y--');
+ }
+
+ void test_compoundAssignment_postfixIncrement() {
+ checkCompoundAssignment('y++');
+ }
+
+ void test_compoundAssignment_prefixDecrement() {
+ checkCompoundAssignment('--y');
+ }
+
+ void test_compoundAssignment_prefixIncrement() {
+ checkCompoundAssignment('++y');
+ }
+
+ void test_compoundAssignment_shiftLeft() {
+ checkCompoundAssignment('y <<= 0');
+ }
+
+ void test_compoundAssignment_shiftRight() {
+ checkCompoundAssignment('y >>= 0');
+ }
+
+ void test_concatenate() {
+ var expr = buildTopLevelVariable(r'var x = "${0}";') as StringInterpolation;
+ expect(expr.elements, hasLength(3));
+ expect((expr.elements[0] as InterpolationString).value, '');
+ expect((expr.elements[1] as InterpolationExpression).expression.toString(),
+ '0');
+ expect((expr.elements[2] as InterpolationString).value, '');
+ }
+
+ void test_conditional() {
+ checkSimpleExpression('false ? 0 : 1');
+ }
+
+ void test_divide() {
+ checkSimpleExpression('0 / 1');
+ }
+
+ void test_equal() {
+ checkSimpleExpression('0 == 1');
+ }
+
+ void test_extractIndex() {
+ checkSimpleExpression('items[0]',
+ extraDeclarations: 'var items = [0, 1, 2]');
+ }
+
+ void test_extractProperty() {
+ checkSimpleExpression("'x'.length");
+ }
+
+ void test_floorDivide() {
+ checkSimpleExpression('0 ~/ 1');
+ }
+
+ void test_greater() {
+ checkSimpleExpression('0 > 1');
+ }
+
+ void test_greaterEqual() {
+ checkSimpleExpression('0 >= 1');
+ }
+
+ void test_ifNull() {
+ checkSimpleExpression('0 ?? 1');
+ }
+
+ void test_invokeConstructor_const() {
+ checkSimpleExpression('const C()',
+ extraDeclarations: '''
+class C {
+ const C();
+}
+''',
+ requireValidConst: true);
+ }
+
+ void test_invokeMethod() {
+ checkSimpleExpression('new C().foo(1, 2)', extraDeclarations: r'''
+class C {
+ int foo(int a, int b) => 0;
+}
+''');
+ }
+
+ void test_invokeMethod_typeArguments() {
+ checkSimpleExpression('new C().foo<int, double>(1, 2.3)',
+ extraDeclarations: r'''
+class C {
+ int foo<T, U>(T a, U b) => 0;
+}
+''',
+ expectedText: 'new C().foo<int, double>()');
+ }
+
+ void test_invokeMethodRef() {
+ checkSimpleExpression('identical(0, 0)');
+ }
+
+ void test_less() {
+ checkSimpleExpression('0 < 1');
+ }
+
+ void test_lessEqual() {
+ checkSimpleExpression('0 <= 1');
+ }
+
+ void test_makeSymbol() {
+ checkSimpleExpression('#foo');
+ }
+
+ void test_makeTypedList_const() {
+ checkSimpleExpression('const <int> []');
+ }
+
+ void test_makeTypedMap_const() {
+ checkSimpleExpression('const <int, bool> {}');
+ }
+
+ void test_makeUntypedList_const() {
+ checkSimpleExpression('const [0]');
+ }
+
+ void test_makeUntypedMap_const() {
+ checkSimpleExpression('const {0 : false}');
+ }
+
+ void test_modulo() {
+ checkSimpleExpression('0 % 1');
+ }
+
+ void test_multiply() {
+ checkSimpleExpression('0 * 1');
+ }
+
+ void test_negate() {
+ checkSimpleExpression('-1');
+ }
+
+ void test_not() {
+ checkSimpleExpression('!true');
+ }
+
+ void test_notEqual() {
+ checkSimpleExpression('0 != 1');
+ }
+
+ void test_or() {
+ checkSimpleExpression('false || true');
+ }
+
+ void test_pushDouble() {
+ checkSimpleExpression('0.5');
+ }
+
+ void test_pushFalse() {
+ checkSimpleExpression('false');
+ }
+
+ void test_pushInt() {
+ checkSimpleExpression('0');
+ }
+
+ void test_pushLocalFunctionReference() {
+ checkSimpleExpression('() => 0');
+ }
+
+ void test_pushLocalFunctionReference_namedParam_untyped() {
+ checkSimpleExpression('({x}) => 0');
+ }
+
+ void test_pushLocalFunctionReference_positionalParam_untyped() {
+ checkSimpleExpression('([x]) => 0');
+ }
+
+ void test_pushLocalFunctionReference_requiredParam_untyped() {
+ checkSimpleExpression('(x) => 0');
+ }
+
+ void test_pushLongInt() {
+ checkSimpleExpression('4294967296');
+ }
+
+ void test_pushNull() {
+ checkSimpleExpression('null');
+ }
+
+ void test_pushParameter() {
+ checkConstructorInitializer('''
+class C {
+ int x;
+ const C(int p) : x = p;
+}
+''', 'p');
+ }
+
+ void test_pushReference() {
+ checkSimpleExpression('int');
+ }
+
+ void test_pushString() {
+ checkSimpleExpression("'foo'");
+ }
+
+ void test_pushTrue() {
+ checkSimpleExpression('true');
+ }
+
+ void test_subtract() {
+ checkSimpleExpression('0 - 1');
+ }
+
+ void test_throwException() {
+ checkSimpleExpression('throw 0');
+ }
+
+ void test_typeCast() {
+ checkSimpleExpression('0 as num');
+ }
+
+ void test_typeCheck() {
+ checkSimpleExpression('0 is num');
+ }
+
+ void test_typeCheck_negated() {
+ checkSimpleExpression('0 is! num', expectedText: '!(0 is num)');
+ }
+}
diff --git a/pkg/analyzer/test/src/summary/in_summary_source_test.dart b/pkg/analyzer/test/src/summary/in_summary_source_test.dart
index 473d7e2..486887e 100644
--- a/pkg/analyzer/test/src/summary/in_summary_source_test.dart
+++ b/pkg/analyzer/test/src/summary/in_summary_source_test.dart
@@ -19,7 +19,7 @@
}
@reflectiveTest
-class InSummarySourceTest extends ReflectiveTest {
+class InSummarySourceTest {
test_InSummarySource() {
var sourceFactory = new SourceFactory([
new InSummaryUriResolver(
diff --git a/pkg/analyzer/test/src/summary/resynthesize_ast_test.dart b/pkg/analyzer/test/src/summary/resynthesize_ast_test.dart
index d6686bc..05648d9 100644
--- a/pkg/analyzer/test/src/summary/resynthesize_ast_test.dart
+++ b/pkg/analyzer/test/src/summary/resynthesize_ast_test.dart
@@ -47,51 +47,9 @@
}
}
-@reflectiveTest
-class ResynthesizeAstSpecTest extends _ResynthesizeAstTest {
- @override
- bool get isStrongMode => false;
-}
-
-@reflectiveTest
-class ResynthesizeAstStrongTest extends _ResynthesizeAstTest {
- @override
- bool get isStrongMode => true;
-
- @failingTest // See dartbug.com/32290
- test_const_constructor_inferred_args() =>
- test_const_constructor_inferred_args();
-
- @override
- @failingTest
- test_syntheticFunctionType_genericClosure() async {
- await super.test_syntheticFunctionType_genericClosure();
- }
-
- @override
- @failingTest
- test_syntheticFunctionType_inGenericClass() async {
- await super.test_syntheticFunctionType_inGenericClass();
- }
-
- @override
- @failingTest
- test_syntheticFunctionType_noArguments() async {
- await super.test_syntheticFunctionType_noArguments();
- }
-
- @override
- @failingTest
- test_syntheticFunctionType_withArguments() async {
- await super.test_syntheticFunctionType_withArguments();
- }
-}
-
-/**
- * Abstract mixin for serializing ASTs and resynthesizing elements from it.
- */
-abstract class _AstResynthesizeTestMixin
- implements _AstResynthesizeTestMixinInterface {
+/// Mixin for serializing ASTs during testing.
+abstract class AstSerializeTestMixin
+ implements _AstSerializeTestMixinInterface {
final Set<Source> serializedSources = new Set<Source>();
PackageBundleAssembler bundleAssembler = new PackageBundleAssembler();
final Map<String, UnlinkedUnitBuilder> uriToUnit =
@@ -99,12 +57,7 @@
AnalysisContext get context;
- LibraryElementImpl _encodeDecodeLibraryElement(Source source) {
- SummaryResynthesizer resynthesizer = _encodeLibrary(source);
- return resynthesizer.getLibraryElement(source.uri.toString());
- }
-
- TestSummaryResynthesizer _encodeLibrary(Source source) {
+ TestSummaryResynthesizer encodeLibrary(Source source) {
_serializeLibrary(source);
PackageBundle bundle =
@@ -219,13 +172,68 @@
}
}
+@reflectiveTest
+class ResynthesizeAstSpecTest extends _ResynthesizeAstTest {
+ @override
+ bool get isStrongMode => false;
+}
+
+@reflectiveTest
+class ResynthesizeAstStrongTest extends _ResynthesizeAstTest {
+ @override
+ bool get isStrongMode => true;
+
+ @failingTest // See dartbug.com/32290
+ test_const_constructor_inferred_args() =>
+ test_const_constructor_inferred_args();
+
+ @override
+ @failingTest
+ test_syntheticFunctionType_genericClosure() async {
+ await super.test_syntheticFunctionType_genericClosure();
+ }
+
+ @override
+ @failingTest
+ test_syntheticFunctionType_inGenericClass() async {
+ await super.test_syntheticFunctionType_inGenericClass();
+ }
+
+ @override
+ @failingTest
+ test_syntheticFunctionType_noArguments() async {
+ await super.test_syntheticFunctionType_noArguments();
+ }
+
+ @override
+ @failingTest
+ test_syntheticFunctionType_withArguments() async {
+ await super.test_syntheticFunctionType_withArguments();
+ }
+}
+
/**
- * Interface that [_AstResynthesizeTestMixin] requires of classes it's mixed
- * into. We can't place the getter below into [_AstResynthesizeTestMixin]
+ * Abstract mixin for serializing ASTs and resynthesizing elements from it.
+ */
+abstract class _AstResynthesizeTestMixin
+ implements _AstSerializeTestMixinInterface {
+ AnalysisContext get context;
+
+ TestSummaryResynthesizer encodeLibrary(Source source);
+
+ LibraryElementImpl _encodeDecodeLibraryElement(Source source) {
+ SummaryResynthesizer resynthesizer = encodeLibrary(source);
+ return resynthesizer.getLibraryElement(source.uri.toString());
+ }
+}
+
+/**
+ * Interface that [_AstSerializeTestMixin] requires of classes it's mixed
+ * into. We can't place the getter below into [_AstSerializeTestMixin]
* directly, because then it would be overriding a field at the site where the
* mixin is instantiated.
*/
-abstract class _AstResynthesizeTestMixinInterface {
+abstract class _AstSerializeTestMixinInterface {
/**
* A test should return `true` to indicate that a missing file at the time of
* summary resynthesis shouldn't trigger an error.
@@ -234,7 +242,7 @@
}
abstract class _ResynthesizeAstTest extends ResynthesizeTest
- with _AstResynthesizeTestMixin {
+ with _AstResynthesizeTestMixin, AstSerializeTestMixin {
bool get shouldCompareLibraryElements;
@override
@@ -354,21 +362,12 @@
}
/**
- * Return a [SummaryResynthesizer] to resynthesize the library with the
- * given [Source].
- */
- TestSummaryResynthesizer _encodeDecodeLibrarySource(Source source) {
- return _encodeLibrary(source);
- }
-
- /**
* Encode the library containing [original] into a summary and then use
* [TestSummaryResynthesizer.getElement] to retrieve just the original
* element from the resynthesized summary.
*/
Element _validateGetElement(String text, Element original) {
- SummaryResynthesizer resynthesizer =
- _encodeDecodeLibrarySource(original.library.source);
+ SummaryResynthesizer resynthesizer = encodeLibrary(original.library.source);
ElementLocationImpl location = original.location;
Element result = resynthesizer.getElement(location);
checkMinimalResynthesisWork(resynthesizer, original.library);
diff --git a/pkg/analyzer/test/src/summary/test_all.dart b/pkg/analyzer/test/src/summary/test_all.dart
index f2dd0d7..d064155 100644
--- a/pkg/analyzer/test/src/summary/test_all.dart
+++ b/pkg/analyzer/test/src/summary/test_all.dart
@@ -4,6 +4,7 @@
import 'package:test_reflective_loader/test_reflective_loader.dart';
+import 'expr_builder_test.dart' as expr_builder_test;
import 'in_summary_source_test.dart' as in_summary_source_test;
import 'linker_test.dart' as linker_test;
import 'name_filter_test.dart' as name_filter_test;
@@ -17,6 +18,7 @@
main() {
defineReflectiveSuite(() {
+ expr_builder_test.main();
in_summary_source_test.main();
linker_test.main();
name_filter_test.main();
diff --git a/pkg/analyzer_plugin/doc/api.html b/pkg/analyzer_plugin/doc/api.html
index 3fa21ce..fdf9630 100644
--- a/pkg/analyzer_plugin/doc/api.html
+++ b/pkg/analyzer_plugin/doc/api.html
@@ -1782,7 +1782,7 @@
An enumeration of the kinds of refactorings that can be created.
</p>
- <dl><dt class="value">CONVERT_GETTER_TO_METHOD</dt><dt class="value">CONVERT_METHOD_TO_GETTER</dt><dt class="value">EXTRACT_LOCAL_VARIABLE</dt><dt class="value">EXTRACT_METHOD</dt><dt class="value">EXTRACT_WIDGET</dt><dt class="value">INLINE_LOCAL_VARIABLE</dt><dt class="value">INLINE_METHOD</dt><dt class="value">MOVE_FILE</dt><dt class="value">RENAME</dt><dt class="value">SORT_MEMBERS</dt></dl></dd><dt class="typeDefinition"><a name="type_RefactoringMethodParameter">RefactoringMethodParameter: object</a></dt><dd>
+ <dl><dt class="value">CONVERT_GETTER_TO_METHOD</dt><dt class="value">CONVERT_METHOD_TO_GETTER</dt><dt class="value">EXTRACT_LOCAL_VARIABLE</dt><dt class="value">EXTRACT_METHOD</dt><dt class="value">EXTRACT_WIDGET</dt><dt class="value">INLINE_LOCAL_VARIABLE</dt><dt class="value">INLINE_METHOD</dt><dt class="value">MOVE_FILE</dt><dt class="value">RENAME</dt></dl></dd><dt class="typeDefinition"><a name="type_RefactoringMethodParameter">RefactoringMethodParameter: object</a></dt><dd>
<p>
A description of a parameter in a method refactoring.
diff --git a/pkg/analyzer_plugin/lib/protocol/protocol_common.dart b/pkg/analyzer_plugin/lib/protocol/protocol_common.dart
index ca795ae..d940ac8 100644
--- a/pkg/analyzer_plugin/lib/protocol/protocol_common.dart
+++ b/pkg/analyzer_plugin/lib/protocol/protocol_common.dart
@@ -4672,7 +4672,6 @@
* INLINE_METHOD
* MOVE_FILE
* RENAME
- * SORT_MEMBERS
* }
*
* Clients may not extend, implement or mix-in this class.
@@ -4703,9 +4702,6 @@
static const RefactoringKind RENAME = const RefactoringKind._("RENAME");
- static const RefactoringKind SORT_MEMBERS =
- const RefactoringKind._("SORT_MEMBERS");
-
/**
* A list containing all of the enum values that are defined.
*/
@@ -4718,8 +4714,7 @@
INLINE_LOCAL_VARIABLE,
INLINE_METHOD,
MOVE_FILE,
- RENAME,
- SORT_MEMBERS
+ RENAME
];
@override
@@ -4747,8 +4742,6 @@
return MOVE_FILE;
case "RENAME":
return RENAME;
- case "SORT_MEMBERS":
- return SORT_MEMBERS;
}
throw new Exception('Illegal enum value: $name');
}
diff --git a/pkg/analyzer_plugin/test/integration/support/protocol_matchers.dart b/pkg/analyzer_plugin/test/integration/support/protocol_matchers.dart
index 31c0e6793..30d0bb6 100644
--- a/pkg/analyzer_plugin/test/integration/support/protocol_matchers.dart
+++ b/pkg/analyzer_plugin/test/integration/support/protocol_matchers.dart
@@ -731,7 +731,6 @@
* INLINE_METHOD
* MOVE_FILE
* RENAME
- * SORT_MEMBERS
* }
*/
final Matcher isRefactoringKind = new MatchesEnum("RefactoringKind", [
@@ -743,8 +742,7 @@
"INLINE_LOCAL_VARIABLE",
"INLINE_METHOD",
"MOVE_FILE",
- "RENAME",
- "SORT_MEMBERS"
+ "RENAME"
]);
/**
diff --git a/pkg/analyzer_plugin/tool/spec/common_types_spec.html b/pkg/analyzer_plugin/tool/spec/common_types_spec.html
index 3749755..648c033 100644
--- a/pkg/analyzer_plugin/tool/spec/common_types_spec.html
+++ b/pkg/analyzer_plugin/tool/spec/common_types_spec.html
@@ -1198,7 +1198,6 @@
<value><code>INLINE_METHOD</code></value>
<value><code>MOVE_FILE</code></value>
<value><code>RENAME</code></value>
- <value><code>SORT_MEMBERS</code></value>
</enum>
</type>
<type name="RefactoringMethodParameter">
diff --git a/pkg/compiler/lib/compiler.dart b/pkg/compiler/lib/compiler.dart
index 3b6a816..32c8b43 100644
--- a/pkg/compiler/lib/compiler.dart
+++ b/pkg/compiler/lib/compiler.dart
@@ -112,14 +112,13 @@
Map<String, dynamic> environment = const {},
Uri packageConfig,
PackagesDiscoveryProvider packagesDiscoveryProvider]) {
- CompilerOptions compilerOptions = new CompilerOptions.parse(
- entryPoint: script,
- libraryRoot: libraryRoot,
- packageRoot: packageRoot,
- packageConfig: packageConfig,
- packagesDiscoveryProvider: packagesDiscoveryProvider,
- options: options,
- environment: environment);
+ CompilerOptions compilerOptions =
+ CompilerOptions.parse(options, libraryRoot: libraryRoot)
+ ..entryPoint = script
+ ..packageRoot = packageRoot
+ ..packageConfig = packageConfig
+ ..packagesDiscoveryProvider = packagesDiscoveryProvider
+ ..environment = environment;
new_api.CompilerInput compilerInput = new LegacyCompilerInput(inputProvider);
new_api.CompilerDiagnostics compilerDiagnostics =
diff --git a/pkg/compiler/lib/src/apiimpl.dart b/pkg/compiler/lib/src/apiimpl.dart
index c951790..cfeecb1 100644
--- a/pkg/compiler/lib/src/apiimpl.dart
+++ b/pkg/compiler/lib/src/apiimpl.dart
@@ -106,11 +106,9 @@
Uri resourceUri = translateUri(node, readableUri);
if (resourceUri == null) return _synthesizeScript(readableUri);
if (resourceUri.scheme == 'dart-ext') {
- if (!options.allowNativeExtensions) {
- reporter.withCurrentElement(element, () {
- reporter.reportErrorMessage(node, MessageKind.DART_EXT_NOT_SUPPORTED);
- });
- }
+ reporter.withCurrentElement(element, () {
+ reporter.reportErrorMessage(node, MessageKind.DART_EXT_NOT_SUPPORTED);
+ });
return _synthesizeScript(readableUri);
}
@@ -392,6 +390,8 @@
if (libraryName.startsWith("_")) return null;
Uri libraryUri = compiler.resolvedUriTranslator.sdkLibraries[libraryName];
+ // TODO(sigmund): use libraries.json instead of .platform files, then simply
+ // use the `supported` bit.
if (libraryUri != null && libraryUri.scheme != "unsupported") {
// Dart2js always "supports" importing 'dart:mirrors' but will abort
// the compilation at a later point if the backend doesn't support
@@ -399,6 +399,7 @@
if (libraryName == 'mirrors') {
return compiler.backend.supportsReflection ? "true" : null;
}
+ if (libraryName == 'isolate') return null;
return "true";
}
diff --git a/pkg/compiler/lib/src/commandline_options.dart b/pkg/compiler/lib/src/commandline_options.dart
index 261a3ef..1c0c8d8 100644
--- a/pkg/compiler/lib/src/commandline_options.dart
+++ b/pkg/compiler/lib/src/commandline_options.dart
@@ -48,7 +48,6 @@
static const String noFrequencyBasedMinification =
'--no-frequency-based-minification';
static const String noSourceMaps = '--no-source-maps';
- static const String preserveComments = '--preserve-comments';
static const String preserveUris = '--preserve-uris';
static const String showPackageWarnings = '--show-package-warnings';
static const String suppressHints = '--suppress-hints';
diff --git a/pkg/compiler/lib/src/common_elements.dart b/pkg/compiler/lib/src/common_elements.dart
index e01a9cc..7efe777 100644
--- a/pkg/compiler/lib/src/common_elements.dart
+++ b/pkg/compiler/lib/src/common_elements.dart
@@ -599,12 +599,6 @@
FunctionEntity get preserveMetadataMarker =>
_preserveMetadataMarker ??= _findMirrorsFunction('preserveMetadata');
- /// Holds the method "preserveUris" in js_mirrors when
- /// dart:mirrors has been loaded.
- FunctionEntity _preserveUrisMarker;
- FunctionEntity get preserveUrisMarker =>
- _preserveUrisMarker ??= _findMirrorsFunction('preserveUris');
-
/// Holds the method "preserveLibraryNames" in js_mirrors when
/// dart:mirrors has been loaded.
FunctionEntity _preserveLibraryNamesMarker;
@@ -1030,6 +1024,8 @@
FunctionEntity get functionTypeTest =>
_findHelperFunction('functionTypeTest');
+ FunctionEntity get futureOrTest => _findHelperFunction('futureOrTest');
+
FunctionEntity get checkSubtypeOfRuntimeType =>
_findHelperFunction('checkSubtypeOfRuntimeType');
diff --git a/pkg/compiler/lib/src/compiler.dart b/pkg/compiler/lib/src/compiler.dart
index ddf776e..1767742 100644
--- a/pkg/compiler/lib/src/compiler.dart
+++ b/pkg/compiler/lib/src/compiler.dart
@@ -63,7 +63,6 @@
import 'serialization/task.dart' show SerializationTask;
import 'ssa/nodes.dart' show HInstruction;
import 'package:front_end/src/fasta/scanner.dart' show StringToken, Token;
-import 'tokens/token_map.dart' show TokenMap;
import 'tree/tree.dart' show Node, TypeAnnotation;
import 'typechecker.dart' show TypeCheckerTask;
import 'types/types.dart' show GlobalTypeInferenceTask;
@@ -95,11 +94,6 @@
ImpactStrategy impactStrategy = const ImpactStrategy();
- /**
- * Map from token to the first preceding comment token.
- */
- final TokenMap commentMap = new TokenMap();
-
/// Options provided from command-line arguments.
final CompilerOptions options;
@@ -184,6 +178,8 @@
this.environment: const _EmptyEnvironment(),
MakeReporterFunction makeReporter})
: this.options = options {
+ options.deriveOptions();
+ options.validate();
CompilerTask kernelFrontEndTask;
selfTask = new GenericTask('self', measurer);
_outputProvider = new _CompilerOutput(this, outputProvider);
@@ -271,8 +267,7 @@
///
/// Override this to mock the scanner for testing.
ScannerTask createScannerTask() =>
- new ScannerTask(dietParser, reporter, measurer,
- preserveComments: options.preserveComments, commentMap: commentMap);
+ new ScannerTask(dietParser, reporter, measurer);
/// Creates the resolution object.
///
diff --git a/pkg/compiler/lib/src/dart2js.dart b/pkg/compiler/lib/src/dart2js.dart
index 9c46934..1d15833 100644
--- a/pkg/compiler/lib/src/dart2js.dart
+++ b/pkg/compiler/lib/src/dart2js.dart
@@ -115,21 +115,16 @@
Stopwatch wallclock = new Stopwatch()..start();
stackTraceFilePrefix = '$currentDirectory';
Uri libraryRoot = currentDirectory;
+ bool outputSpecified = false;
Uri out = currentDirectory.resolve('out.js');
Uri sourceMapOut = currentDirectory.resolve('out.js.map');
- List<Uri> resolutionInputs;
List<String> bazelPaths;
Uri packageConfig = null;
Uri packageRoot = null;
List<String> options = new List<String>();
- List<String> explicitOutputArguments = <String>[];
bool wantHelp = false;
bool wantVersion = false;
bool analyzeOnly = false;
- bool analyzeAll = false;
- bool resolveOnly = false;
- Uri resolutionOutput = currentDirectory.resolve('out.data');
- bool allowNativeExtensions = false;
bool trustTypeAnnotations = false;
bool checkedMode = false;
List<String> hints = <String>[];
@@ -141,13 +136,9 @@
bool enableColors;
bool useKernel = true;
Uri platformBinaries = computePlatformBinariesLocation();
- // List of provided options that imply that output is expected.
- List<String> optionsImplyCompilation = <String>[];
- bool hasDisallowUnsafeEval = false;
Map<String, dynamic> environment = new Map<String, dynamic>();
void passThrough(String argument) => options.add(argument);
-
void ignoreOption(String argument) {}
if (BUILD_ID != null) {
@@ -168,23 +159,21 @@
}
void setOutput(Iterator<String> arguments) {
- explicitOutputArguments.add(arguments.current);
+ outputSpecified = true;
String path;
if (arguments.current == '-o') {
if (!arguments.moveNext()) {
helpAndFail('Error: Missing file after -o option.');
}
- explicitOutputArguments.add(arguments.current);
path = arguments.current;
} else {
path = extractParameter(arguments.current);
}
- resolutionOutput = out = currentDirectory.resolve(nativeToUriPath(path));
+ out = currentDirectory.resolve(nativeToUriPath(path));
sourceMapOut = Uri.parse('$out.map');
}
void setOutputType(String argument) {
- optionsImplyCompilation.add(argument);
if (argument == '--output-type=dart' ||
argument == '--output-type=dart-multi') {
helpAndFail(
@@ -193,12 +182,9 @@
}
}
- void setResolutionInput(String argument) {
- resolutionInputs = <Uri>[];
- String parts = extractParameter(argument);
- for (String part in parts.split(',')) {
- resolutionInputs.add(currentDirectory.resolve(nativeToUriPath(part)));
- }
+ setStrip(String argument) {
+ helpAndFail("Option '--force-strip' is not in use now that"
+ "--output-type=dart is no longer supported.");
}
void setBazelPaths(String argument) {
@@ -206,40 +192,19 @@
bazelPaths = <String>[]..addAll(paths.split(','));
}
- void setResolveOnly(String argument) {
- resolveOnly = true;
- passThrough(argument);
- }
-
String getDepsOutput(Iterable<Uri> sourceFiles) {
var filenames = sourceFiles.map((uri) => '$uri').toList();
filenames.sort();
return filenames.join("\n");
}
- implyCompilation(String argument) {
- optionsImplyCompilation.add(argument);
- passThrough(argument);
- }
-
- setStrip(String argument) {
- helpAndFail("Option '--force-strip' is not in use now that"
- "--output-type=dart is no longer supported.");
- }
-
void setAnalyzeOnly(String argument) {
analyzeOnly = true;
passThrough(argument);
}
- void setAnalyzeAll(String argument) {
- analyzeAll = true;
- passThrough(argument);
- }
-
void setAllowNativeExtensions(String argument) {
- allowNativeExtensions = true;
- passThrough(argument);
+ helpAndFail("Option '${Flags.allowNativeExtensions}' is not supported.");
}
void setVerbose(_) {
@@ -249,15 +214,7 @@
void setTrustTypeAnnotations(String argument) {
trustTypeAnnotations = true;
- implyCompilation(argument);
- }
-
- void setTrustJSInteropTypeAnnotations(String argument) {
- implyCompilation(argument);
- }
-
- void setTrustPrimitives(String argument) {
- implyCompilation(argument);
+ passThrough(argument);
}
void setCheckedMode(String argument) {
@@ -321,7 +278,7 @@
setCheckedMode(Flags.enableCheckedMode);
break;
case 'm':
- implyCompilation(Flags.minify);
+ passThrough(Flags.minify);
break;
default:
throw 'Internal error: "$shortOption" did not match';
@@ -333,13 +290,14 @@
List<OptionHandler> handlers = <OptionHandler>[
new OptionHandler('-[chvm?]+', handleShortOptions),
new OptionHandler('--throw-on-error(?:=[0-9]+)?', handleThrowOnError),
- new OptionHandler(Flags.suppressWarnings, (_) {
+ new OptionHandler(Flags.suppressWarnings, (String argument) {
showWarnings = false;
- passThrough(Flags.suppressWarnings);
+ passThrough(argument);
}),
new OptionHandler(Flags.fatalWarnings, passThrough),
- new OptionHandler(Flags.suppressHints, (_) {
+ new OptionHandler(Flags.suppressHints, (String argument) {
showHints = false;
+ passThrough(argument);
}),
// TODO(sigmund): remove entirely after Dart 1.20
new OptionHandler(
@@ -353,13 +311,13 @@
new OptionHandler(Flags.version, (_) => wantVersion = true),
new OptionHandler('--library-root=.+', setLibraryRoot),
new OptionHandler('--out=.+|-o.*', setOutput, multipleArguments: true),
- new OptionHandler(Flags.allowMockCompilation, passThrough),
+ new OptionHandler(Flags.allowMockCompilation, ignoreOption),
new OptionHandler(Flags.fastStartup, passThrough),
new OptionHandler(Flags.genericMethodSyntax, ignoreOption),
new OptionHandler(Flags.syncAsync, passThrough),
new OptionHandler(Flags.initializingFormalAccess, ignoreOption),
- new OptionHandler('${Flags.minify}|-m', implyCompilation),
- new OptionHandler(Flags.preserveUris, passThrough),
+ new OptionHandler(Flags.minify, passThrough),
+ new OptionHandler(Flags.preserveUris, ignoreOption),
new OptionHandler('--force-strip=.*', setStrip),
new OptionHandler(Flags.disableDiagnosticColors, (_) {
enableColors = false;
@@ -370,35 +328,29 @@
new OptionHandler('--enable[_-]checked[_-]mode|--checked',
(_) => setCheckedMode(Flags.enableCheckedMode)),
new OptionHandler(Flags.enableAsserts, passThrough),
- new OptionHandler(Flags.trustTypeAnnotations,
- (_) => setTrustTypeAnnotations(Flags.trustTypeAnnotations)),
- new OptionHandler(Flags.trustPrimitives,
- (_) => setTrustPrimitives(Flags.trustPrimitives)),
- new OptionHandler(
- Flags.trustJSInteropTypeAnnotations,
- (_) => setTrustJSInteropTypeAnnotations(
- Flags.trustJSInteropTypeAnnotations)),
+ new OptionHandler(Flags.trustTypeAnnotations, setTrustTypeAnnotations),
+ new OptionHandler(Flags.trustPrimitives, passThrough),
+ new OptionHandler(Flags.trustJSInteropTypeAnnotations, passThrough),
new OptionHandler(r'--help|/\?|/h', (_) => wantHelp = true),
new OptionHandler('--packages=.+', setPackageConfig),
new OptionHandler('--package-root=.+|-p.+', setPackageRoot),
- new OptionHandler(Flags.analyzeAll, setAnalyzeAll),
+ new OptionHandler(Flags.analyzeAll, passThrough),
new OptionHandler(Flags.analyzeOnly, setAnalyzeOnly),
new OptionHandler(Flags.noSourceMaps, passThrough),
- new OptionHandler(Option.resolutionInput, setResolutionInput),
+ new OptionHandler(Option.resolutionInput, ignoreOption),
new OptionHandler(Option.bazelPaths, setBazelPaths),
- new OptionHandler(Flags.resolveOnly, setResolveOnly),
+ new OptionHandler(Flags.resolveOnly, ignoreOption),
new OptionHandler(Flags.analyzeSignaturesOnly, setAnalyzeOnly),
new OptionHandler(Flags.disableNativeLiveTypeAnalysis, passThrough),
new OptionHandler('--categories=.*', setCategories),
- new OptionHandler(Flags.disableInlining, implyCompilation),
- new OptionHandler(Flags.disableProgramSplit, implyCompilation),
- new OptionHandler(Flags.disableTypeInference, implyCompilation),
- new OptionHandler(Flags.disableRtiOptimization, implyCompilation),
+ new OptionHandler(Flags.disableInlining, passThrough),
+ new OptionHandler(Flags.disableProgramSplit, passThrough),
+ new OptionHandler(Flags.disableTypeInference, passThrough),
+ new OptionHandler(Flags.disableRtiOptimization, passThrough),
new OptionHandler(Flags.terse, passThrough),
- new OptionHandler('--deferred-map=.+', implyCompilation),
- new OptionHandler(Flags.dumpInfo, implyCompilation),
- new OptionHandler(
- '--disallow-unsafe-eval', (_) => hasDisallowUnsafeEval = true),
+ new OptionHandler('--deferred-map=.+', passThrough),
+ new OptionHandler(Flags.dumpInfo, passThrough),
+ new OptionHandler('--disallow-unsafe-eval', ignoreOption),
new OptionHandler(Option.showPackageWarnings, passThrough),
new OptionHandler(Flags.useContentSecurityPolicy, passThrough),
new OptionHandler(Flags.enableExperimentalMirrors, passThrough),
@@ -408,19 +360,10 @@
// TODO(floitsch): remove conditional directives flag.
// We don't provide the info-message yet, since we haven't publicly
// launched the feature yet.
- new OptionHandler(Flags.conditionalDirectives, (_) {}),
- new OptionHandler('--enable-async', (_) {
- hints.add("Option '--enable-async' is no longer needed. "
- "Async-await is supported by default.");
- }),
- new OptionHandler('--enable-null-aware-operators', (_) {
- hints.add("Option '--enable-null-aware-operators' is no longer needed. "
- "Null aware operators are supported by default.");
- }),
- new OptionHandler('--enable-enum', (_) {
- hints.add("Option '--enable-enum' is no longer needed. "
- "Enums are supported by default.");
- }),
+ new OptionHandler(Flags.conditionalDirectives, ignoreOption),
+ new OptionHandler('--enable-async', ignoreOption),
+ new OptionHandler('--enable-null-aware-operators', ignoreOption),
+ new OptionHandler('--enable-enum', ignoreOption),
new OptionHandler(Flags.allowNativeExtensions, setAllowNativeExtensions),
new OptionHandler(Flags.generateCodeWithCompileTimeErrors, passThrough),
new OptionHandler(Flags.useMultiSourceInfo, passThrough),
@@ -482,16 +425,6 @@
helpAndExit(wantHelp, wantVersion, diagnosticHandler.verbose);
}
- if (hasDisallowUnsafeEval) {
- String precompiledName = relativize(
- currentDirectory,
- RandomAccessFileOutputProvider.computePrecompiledUri(out),
- Platform.isWindows);
- helpAndFail("Option '--disallow-unsafe-eval' has been removed."
- " Instead, the compiler generates a file named"
- " '$precompiledName'.");
- }
-
if (arguments.isEmpty) {
helpAndFail('No Dart file specified.');
}
@@ -509,52 +442,12 @@
helpAndFail("Cannot specify both '--package-root' and '--packages.");
}
- List<String> optionsImplyOutput = <String>[]
- ..addAll(optionsImplyCompilation)
- ..addAll(explicitOutputArguments);
- if (resolveOnly && !optionsImplyCompilation.isEmpty) {
- diagnosticHandler.info(
- "Options $optionsImplyCompilation indicate that compilation is "
- "expected, but compilation is turned off by the option "
- "'${Flags.resolveOnly}'.",
- api.Diagnostic.INFO);
- } else if ((analyzeOnly || analyzeAll) && !optionsImplyOutput.isEmpty) {
- if (analyzeAll && !analyzeOnly) {
- diagnosticHandler.info(
- "Option '${Flags.analyzeAll}' implies '${Flags.analyzeOnly}'.",
- api.Diagnostic.INFO);
- }
- diagnosticHandler.info(
- "Options $optionsImplyOutput indicate that output is expected, "
- "but compilation is turned off by the option '${Flags.analyzeOnly}'.",
- api.Diagnostic.INFO);
- }
- if (resolveOnly) {
- if (resolutionInputs != null &&
- resolutionInputs.contains(resolutionOutput)) {
- helpAndFail("Resolution input '${resolutionOutput}' can't be used as "
- "resolution output. Use the '--out' option to specify another "
- "resolution output.");
- }
- analyzeOnly = analyzeAll = true;
- } else if (analyzeAll) {
- analyzeOnly = true;
- }
- if (!analyzeOnly) {
- if (allowNativeExtensions) {
- helpAndFail("Option '${Flags.allowNativeExtensions}' is only supported "
- "in combination with the '${Flags.analyzeOnly}' option.");
- }
- }
-
options.add('--out=$out');
options.add('--source-map=$sourceMapOut');
RandomAccessFileOutputProvider outputProvider =
new RandomAccessFileOutputProvider(out, sourceMapOut,
- onInfo: diagnosticHandler.info,
- onFailure: fail,
- resolutionOutput: resolveOnly ? resolutionOutput : null);
+ onInfo: diagnosticHandler.info, onFailure: fail);
api.CompilationResult compilationDone(api.CompilationResult result) {
if (analyzeOnly) return result;
@@ -585,7 +478,7 @@
for (String filename in outputProvider.allOutputFiles) {
print(" $filename");
}
- } else if (explicitOutputArguments.isNotEmpty) {
+ } else if (outputSpecified) {
String input = uriPathToNative(arguments[0]);
String output = relativize(currentDirectory, out, Platform.isWindows);
print('Dart file ($input) compiled to JavaScript: $output');
@@ -599,17 +492,13 @@
// TODO(sigmund): reenable hints (Issue #32111)
diagnosticHandler.showHints = showHints = false;
}
- CompilerOptions compilerOptions = new CompilerOptions.parse(
- entryPoint: script,
- libraryRoot: libraryRoot,
- packageRoot: packageRoot,
- packageConfig: packageConfig,
- platformBinaries: platformBinaries,
- packagesDiscoveryProvider: findPackages,
- resolutionInputs: resolutionInputs,
- resolutionOutput: resolveOnly ? resolutionOutput : null,
- options: options,
- environment: environment)
+ CompilerOptions compilerOptions = CompilerOptions.parse(options,
+ libraryRoot: libraryRoot, platformBinaries: platformBinaries)
+ ..entryPoint = script
+ ..packageRoot = packageRoot
+ ..packageConfig = packageConfig
+ ..environment = environment
+ ..packagesDiscoveryProvider = findPackages
..kernelInitializedCompilerState = kernelInitializedCompilerState;
return compileFunc(
compilerOptions, inputProvider, diagnosticHandler, outputProvider)
@@ -755,10 +644,6 @@
--show-package-warnings
Show warnings and hints generated from packages.
- --preserve-uris
- Preserve the source URIs in the reflection data. Without this flag the
- `uri` getter for `LibraryMirror`s is mangled in minified mode.
-
--csp
Disable dynamic generation of code in the generated output. This is
necessary to satisfy CSP restrictions (see http://www.w3.org/TR/CSP/).
@@ -1004,8 +889,9 @@
}
}
}
- options = CompilerOptions.copy(options,
- resolutionInputs: resolutionInputs, compileOnly: compileOnly);
+ options
+ ..resolutionInputs = resolutionInputs
+ ..compileOnly = compileOnly;
}
return oldCompileFunc(options, input, compilerDiagnostics, compilerOutput);
}
@@ -1019,13 +905,13 @@
api.CompilerDiagnostics compilerDiagnostics,
api.CompilerOutput compilerOutput,
[List<_SerializedData> serializedData]) {
- CompilerOptions options = CompilerOptions.copy(compilerOptions,
- entryPoint: entryPoint,
- resolutionOutput: serializedUri,
- analyzeAll: true,
- analyzeOnly: true,
- resolveOnly: true);
- return compileWithSerializedData(options, compilerInput,
+ compilerOptions
+ ..entryPoint = entryPoint
+ ..resolutionOutput = serializedUri
+ ..analyzeAll = true
+ ..analyzeOnly = true
+ ..resolveOnly = true;
+ return compileWithSerializedData(compilerOptions, compilerInput,
compilerDiagnostics, compilerOutput, serializedData);
}
diff --git a/pkg/compiler/lib/src/deferred_load.dart b/pkg/compiler/lib/src/deferred_load.dart
index e04dcab..94bc615 100644
--- a/pkg/compiler/lib/src/deferred_load.dart
+++ b/pkg/compiler/lib/src/deferred_load.dart
@@ -341,6 +341,12 @@
case TypeUseKind.CATCH_TYPE:
_collectTypeDependencies(type, elements);
break;
+ case TypeUseKind.IMPLICIT_CAST:
+ // TODO(johnniwinther): Collect implicit casts conditionally on
+ // `enableTypeAssertions`.
+ _collectTypeDependencies(type, elements);
+ break;
+ case TypeUseKind.PARAMETER_CHECK:
case TypeUseKind.CHECKED_MODE_CHECK:
if (compiler.options.enableTypeAssertions) {
_collectTypeDependencies(type, elements);
diff --git a/pkg/compiler/lib/src/elements/types.dart b/pkg/compiler/lib/src/elements/types.dart
index 3da214e..753a4af 100644
--- a/pkg/compiler/lib/src/elements/types.dart
+++ b/pkg/compiler/lib/src/elements/types.dart
@@ -746,6 +746,12 @@
return new FutureOrType(newTypeArgument);
}
+ bool get containsTypeVariables => typeArgument.containsTypeVariables;
+
+ void forEachTypeVariable(f(TypeVariableType variable)) {
+ typeArgument.forEachTypeVariable(f);
+ }
+
R accept<R, A>(DartTypeVisitor<R, A> visitor, A argument) =>
visitor.visitFutureOrType(this, argument);
diff --git a/pkg/compiler/lib/src/enqueue.dart b/pkg/compiler/lib/src/enqueue.dart
index c399c75..0c2ff92 100644
--- a/pkg/compiler/lib/src/enqueue.dart
+++ b/pkg/compiler/lib/src/enqueue.dart
@@ -356,6 +356,12 @@
case TypeUseKind.CATCH_TYPE:
_registerIsCheck(type);
break;
+ case TypeUseKind.IMPLICIT_CAST:
+ // TODO(johnniwinther): Register implicit casts conditionally on
+ // `enableTypeAssertions`.
+ _registerIsCheck(type);
+ break;
+ case TypeUseKind.PARAMETER_CHECK:
case TypeUseKind.CHECKED_MODE_CHECK:
if (_options.enableTypeAssertions) {
_registerIsCheck(type);
diff --git a/pkg/compiler/lib/src/inferrer/type_graph_nodes.dart b/pkg/compiler/lib/src/inferrer/type_graph_nodes.dart
index 326e6a0..725b37a 100644
--- a/pkg/compiler/lib/src/inferrer/type_graph_nodes.dart
+++ b/pkg/compiler/lib/src/inferrer/type_graph_nodes.dart
@@ -1963,6 +1963,9 @@
return type;
} else if (annotation.isTypedef || annotation.isFunctionType) {
otherType = closedWorld.commonMasks.functionType;
+ } else if (annotation.isFutureOr) {
+ // TODO(johnniwinther): Narrow FutureOr types.
+ return type;
} else {
assert(annotation.isTypeVariable || annotation.isFunctionTypeVariable);
// TODO(ngeoffray): Narrow to bound.
diff --git a/pkg/compiler/lib/src/js_backend/backend.dart b/pkg/compiler/lib/src/js_backend/backend.dart
index 648eba8..2cb5fcf 100644
--- a/pkg/compiler/lib/src/js_backend/backend.dart
+++ b/pkg/compiler/lib/src/js_backend/backend.dart
@@ -1024,10 +1024,8 @@
bool shouldOutput(Element element) => true;
/// Returns `true` if the `native` pseudo keyword is supported for [library].
- bool canLibraryUseNative(LibraryEntity library) {
- return native.maybeEnableNative(library.canonicalUri,
- allowNativeExtensions: compiler.options.allowNativeExtensions);
- }
+ bool canLibraryUseNative(LibraryEntity library) =>
+ native.maybeEnableNative(library.canonicalUri);
bool isTargetSpecificLibrary(LibraryElement library) {
Uri canonicalUri = library.canonicalUri;
diff --git a/pkg/compiler/lib/src/js_backend/backend_impact.dart b/pkg/compiler/lib/src/js_backend/backend_impact.dart
index 363d50f..90bc364 100644
--- a/pkg/compiler/lib/src/js_backend/backend_impact.dart
+++ b/pkg/compiler/lib/src/js_backend/backend_impact.dart
@@ -536,6 +536,13 @@
new BackendImpact(staticUses: [/*helpers.functionTypeTestMetaHelper*/]);
}
+ BackendImpact _futureOrTypeCheck;
+
+ BackendImpact get futureOrTypeCheck {
+ return _futureOrTypeCheck ??=
+ new BackendImpact(staticUses: [_commonElements.futureOrTest]);
+ }
+
BackendImpact _nativeTypeCheck;
BackendImpact get nativeTypeCheck {
diff --git a/pkg/compiler/lib/src/js_backend/checked_mode_helpers.dart b/pkg/compiler/lib/src/js_backend/checked_mode_helpers.dart
index cd59725..c2c7d83 100644
--- a/pkg/compiler/lib/src/js_backend/checked_mode_helpers.dart
+++ b/pkg/compiler/lib/src/js_backend/checked_mode_helpers.dart
@@ -89,6 +89,19 @@
}
}
+class FutureOrRepresentationCheckedModeHelper extends CheckedModeHelper {
+ const FutureOrRepresentationCheckedModeHelper(String name) : super(name);
+
+ CallStructure get callStructure => CallStructure.TWO_ARGS;
+
+ void generateAdditionalArguments(SsaCodeGenerator codegen, Namer namer,
+ HTypeConversion node, List<jsAst.Expression> arguments) {
+ assert(node.typeExpression.isFutureOr);
+ codegen.use(node.typeRepresentation);
+ arguments.add(codegen.pop());
+ }
+}
+
class SubtypeCheckedModeHelper extends CheckedModeHelper {
const SubtypeCheckedModeHelper(String name) : super(name);
@@ -149,6 +162,8 @@
const PropertyCheckedModeHelper('propertyTypeCheck'),
const FunctionTypeRepresentationCheckedModeHelper('functionTypeCast'),
const FunctionTypeRepresentationCheckedModeHelper('functionTypeCheck'),
+ const FutureOrRepresentationCheckedModeHelper('futureOrCast'),
+ const FutureOrRepresentationCheckedModeHelper('futureOrCheck'),
];
// Checked mode helpers indexed by name.
@@ -216,6 +231,10 @@
return typeCast ? 'functionTypeCast' : 'functionTypeCheck';
}
+ if (type.isFutureOr) {
+ return typeCast ? 'futureOrCast' : 'futureOrCheck';
+ }
+
assert(type.isInterfaceType,
failedAt(NO_LOCATION_SPANNABLE, "Unexpected type: $type"));
InterfaceType interfaceType = type;
diff --git a/pkg/compiler/lib/src/js_backend/enqueuer.dart b/pkg/compiler/lib/src/js_backend/enqueuer.dart
index 82dd51a..92fa232 100644
--- a/pkg/compiler/lib/src/js_backend/enqueuer.dart
+++ b/pkg/compiler/lib/src/js_backend/enqueuer.dart
@@ -186,6 +186,12 @@
case TypeUseKind.CATCH_TYPE:
_registerIsCheck(type);
break;
+ case TypeUseKind.IMPLICIT_CAST:
+ // TODO(johnniwinther): Register implicit casts conditionally on
+ // `enableTypeAssertions`.
+ _registerIsCheck(type);
+ break;
+ case TypeUseKind.PARAMETER_CHECK:
case TypeUseKind.CHECKED_MODE_CHECK:
if (_options.enableTypeAssertions) {
_registerIsCheck(type);
diff --git a/pkg/compiler/lib/src/js_backend/impact_transformer.dart b/pkg/compiler/lib/src/js_backend/impact_transformer.dart
index c83d271..21b3be9 100644
--- a/pkg/compiler/lib/src/js_backend/impact_transformer.dart
+++ b/pkg/compiler/lib/src/js_backend/impact_transformer.dart
@@ -169,6 +169,12 @@
onIsCheck(type, transformed);
hasAsCast = true;
break;
+ case TypeUseKind.IMPLICIT_CAST:
+ // TODO(johnniwinther): Register implicit casts conditionally on
+ // `enableTypeAssertions`.
+ onIsCheck(type, transformed);
+ break;
+ case TypeUseKind.PARAMETER_CHECK:
case TypeUseKind.CHECKED_MODE_CHECK:
if (_options.enableTypeAssertions) {
onIsCheck(type, transformed);
@@ -321,6 +327,9 @@
if (type is InterfaceType && _nativeBasicData.isNativeClass(type.element)) {
registerImpact(_impacts.nativeTypeCheck);
}
+ if (type is FutureOrType) {
+ registerImpact(_impacts.futureOrTypeCheck);
+ }
}
}
diff --git a/pkg/compiler/lib/src/js_backend/interceptor_data.dart b/pkg/compiler/lib/src/js_backend/interceptor_data.dart
index 35c6160..87fc04e 100644
--- a/pkg/compiler/lib/src/js_backend/interceptor_data.dart
+++ b/pkg/compiler/lib/src/js_backend/interceptor_data.dart
@@ -207,6 +207,7 @@
// is mixed-in or in an implements clause.
if (!type.treatAsRaw) return false;
+ if (type.isFutureOr) return false;
InterfaceType interfaceType = type;
ClassEntity classElement = interfaceType.element;
if (isInterceptedClass(classElement)) return false;
diff --git a/pkg/compiler/lib/src/js_backend/mirrors_data.dart b/pkg/compiler/lib/src/js_backend/mirrors_data.dart
index 07ca9c50..c128794 100644
--- a/pkg/compiler/lib/src/js_backend/mirrors_data.dart
+++ b/pkg/compiler/lib/src/js_backend/mirrors_data.dart
@@ -10,7 +10,6 @@
import '../elements/entities.dart';
import '../elements/names.dart';
import '../elements/types.dart';
-import '../options.dart';
import '../world.dart';
import '../universe/world_builder.dart';
import '../util/emptyset.dart';
@@ -39,10 +38,6 @@
/// True if a call to disableTreeShaking has been seen.
bool get isTreeShakingDisabled;
- /// True if a call to preserveUris has been seen and the preserve-uris flag
- /// is set.
- bool get mustPreserveUris;
-
/// Set of symbols that the user has requested for reflection.
Iterable<String> get symbolsUsed;
@@ -175,10 +170,6 @@
/// True if there isn't sufficient @MirrorsUsed data.
bool hasInsufficientMirrorsUsed = false;
- /// True if a call to preserveUris has been seen and the preserve-uris flag
- /// is set.
- bool mustPreserveUris = false;
-
/// Set of symbols that the user has requested for reflection.
final Set<String> symbolsUsed = new Set<String>();
@@ -197,13 +188,11 @@
// TODO(johnniwinther): Avoid the need for this.
final Compiler _compiler;
- final CompilerOptions _options;
-
final ElementEnvironment _elementEnvironment;
final CommonElements _commonElements;
- MirrorsDataImpl(this._compiler, this._options, this._elementEnvironment,
- this._commonElements);
+ MirrorsDataImpl(
+ this._compiler, this._elementEnvironment, this._commonElements);
void registerUsedMember(MemberEntity member) {
if (member == _commonElements.disableTreeShakingMarker) {
@@ -212,8 +201,6 @@
mustPreserveNames = true;
} else if (member == _commonElements.preserveMetadataMarker) {
mustRetainMetadata = true;
- } else if (member == _commonElements.preserveUrisMarker) {
- if (_options.preserveUris) mustPreserveUris = true;
} else if (member == _commonElements.preserveLibraryNamesMarker) {
mustRetainLibraryNames = true;
}
diff --git a/pkg/compiler/lib/src/js_backend/namer.dart b/pkg/compiler/lib/src/js_backend/namer.dart
index 3a02f42..5a6a574c 100644
--- a/pkg/compiler/lib/src/js_backend/namer.dart
+++ b/pkg/compiler/lib/src/js_backend/namer.dart
@@ -655,6 +655,10 @@
return asName(functionTypeOptionalParametersTag);
case JsGetName.FUNCTION_TYPE_NAMED_PARAMETERS_TAG:
return asName(functionTypeNamedParametersTag);
+ case JsGetName.FUTURE_OR_TAG:
+ return asName(futureOrTag);
+ case JsGetName.FUTURE_OR_TYPE_ARGUMENT_TAG:
+ return asName(futureOrTypeTag);
case JsGetName.IS_INDEXABLE_FIELD_NAME:
return operatorIs(_commonElements.jsIndexingBehaviorInterface);
case JsGetName.NULL_CLASS_TYPE_NAME:
@@ -663,6 +667,8 @@
return runtimeTypeName(_commonElements.objectClass);
case JsGetName.FUNCTION_CLASS_TYPE_NAME:
return runtimeTypeName(_commonElements.functionClass);
+ case JsGetName.FUTURE_CLASS_TYPE_NAME:
+ return runtimeTypeName(_commonElements.futureClass);
default:
throw failedAt(spannable, 'Error: Namer has no name for "$name".');
}
@@ -1640,6 +1646,10 @@
String get functionTypeGenericBoundsTag => r'bounds';
+ String get futureOrTag => r'futureOr';
+
+ String get futureOrTypeTag => r'type';
+
Map<ResolutionFunctionType, jsAst.Name> functionTypeNameMap =
new HashMap<ResolutionFunctionType, jsAst.Name>();
diff --git a/pkg/compiler/lib/src/js_backend/runtime_types.dart b/pkg/compiler/lib/src/js_backend/runtime_types.dart
index b655b94..ff8e492 100644
--- a/pkg/compiler/lib/src/js_backend/runtime_types.dart
+++ b/pkg/compiler/lib/src/js_backend/runtime_types.dart
@@ -616,6 +616,10 @@
/// is a function type.
jsAst.Template get templateForIsFunctionType;
+ /// Returns the JavaScript template to determine at runtime if a type object
+ /// is a FutureOr type.
+ jsAst.Template get templateForIsFutureOrType;
+
jsAst.Name get getFunctionThatReturnsNullName;
/// Returns a [jsAst.Expression] representing the given [type]. Type variables
@@ -768,11 +772,11 @@
{bool forRtiNeeds: true})
: explicitIsChecks = new Set<DartType>.from(worldBuilder.isChecks) {
_setupDependencies(elementEnvironment, commonElements, worldBuilder);
- _propagateTests(elementEnvironment, worldBuilder);
+ _propagateTests(commonElements, elementEnvironment, worldBuilder);
if (forRtiNeeds) {
_propagateLiterals(elementEnvironment, worldBuilder);
}
- _collectResults(elementEnvironment, types, worldBuilder,
+ _collectResults(commonElements, elementEnvironment, types, worldBuilder,
forRtiNeeds: forRtiNeeds);
}
@@ -902,6 +906,14 @@
void _setupDependencies(ElementEnvironment elementEnvironment,
CommonElements commonElements, WorldBuilder worldBuilder) {
+ /// Register that if `node.entity` needs type arguments then so do entities
+ /// whose type variables occur in [type].
+ ///
+ /// For instance if `A` needs type arguments then so does `B` in:
+ ///
+ /// class A<T> {}
+ /// class B<T> { m() => new A<T>(); }
+ ///
void registerDependencies(RtiNode node, DartType type) {
type.forEachTypeVariable((TypeVariableType typeVariable) {
Entity typeDeclaration = typeVariable.element.typeDeclaration;
@@ -943,18 +955,40 @@
.addDependency(_getClassNode(commonElements.mapClass));
}
- worldBuilder.isChecks.forEach((DartType type) {
+ void processCheckedType(DartType type) {
if (type is InterfaceType) {
- registerDependencies(_getClassNode(type.element), type);
+ // Register that if [cls] needs type arguments then so do the entities
+ // that declare type variables occurring in [type].
+ ClassEntity cls = type.element;
+ registerDependencies(_getClassNode(cls), type);
}
- });
+ if (type is FutureOrType) {
+ // [type] is `FutureOr<X>`.
+
+ // For the implied `is Future<X>` test, register that if `Future` needs
+ // type arguments then so do the entities that declare type variables
+ // occurring in `type.typeArgument`.
+ registerDependencies(
+ _getClassNode(commonElements.futureClass), type.typeArgument);
+ // Process `type.typeArgument` for the implied `is X` test.
+ processCheckedType(type.typeArgument);
+ }
+ }
+
+ worldBuilder.isChecks.forEach(processCheckedType);
+
worldBuilder.instantiatedTypes.forEach((InterfaceType type) {
- registerDependencies(_getClassNode(type.element), type);
+ // Register that if [cls] needs type arguments then so do the entities
+ // that declare type variables occurring in [type].
+ ClassEntity cls = type.element;
+ registerDependencies(_getClassNode(cls), type);
});
worldBuilder.forEachStaticTypeArgument(
(Entity entity, Iterable<DartType> typeArguments) {
for (DartType type in typeArguments) {
+ // Register that if [entity] needs type arguments then so do the
+ // entities that declare type variables occurring in [type].
registerDependencies(
_getMethodNode(elementEnvironment, worldBuilder, entity), type);
}
@@ -971,6 +1005,8 @@
_getMethodNode(elementEnvironment, worldBuilder, entity);
if (node.selectorApplies(selector)) {
for (DartType type in typeArguments) {
+ // Register that if `node.entity` needs type arguments then so do
+ // the entities that declare type variables occurring in [type].
registerDependencies(node, type);
}
}
@@ -982,21 +1018,26 @@
});
}
- void _propagateTests(
+ void _propagateTests(CommonElements commonElements,
ElementEnvironment elementEnvironment, WorldBuilder worldBuilder) {
- worldBuilder.isChecks.forEach((DartType type) {
+ void processType(DartType type, {bool direct: true}) {
if (type.isTypeVariable) {
TypeVariableType typeVariableType = type;
TypeVariableEntity variable = typeVariableType.element;
if (variable.typeDeclaration is ClassEntity) {
- _getClassNode(variable.typeDeclaration).markDirectTest();
+ _getClassNode(variable.typeDeclaration).markTest(direct: direct);
} else {
_getMethodNode(
elementEnvironment, worldBuilder, variable.typeDeclaration)
- .markDirectTest();
+ .markTest(direct: direct);
}
+ } else if (type is FutureOrType) {
+ _getClassNode(commonElements.futureClass).markIndirectTest();
+ processType(type.typeArgument, direct: false);
}
- });
+ }
+
+ worldBuilder.isChecks.forEach(processType);
}
void _propagateLiterals(
@@ -1014,9 +1055,36 @@
});
}
- void _collectResults(ElementEnvironment elementEnvironment, DartTypes types,
+ void _collectResults(
+ CommonElements commonElements,
+ ElementEnvironment elementEnvironment,
+ DartTypes types,
WorldBuilder worldBuilder,
{bool forRtiNeeds: true}) {
+ /// Register the implicit is-test of [type].
+ ///
+ /// If [type] is of the form `FutureOr<X>`, also register the implicit
+ /// is-tests of `Future<X>` and `X`.
+ void addImplicitCheck(DartType type) {
+ if (implicitIsChecks.add(type)) {
+ if (type is FutureOrType) {
+ addImplicitCheck(commonElements.futureType(type.typeArgument));
+ addImplicitCheck(type.typeArgument);
+ }
+ }
+ }
+
+ void addImplicitChecks(Iterable<DartType> types) {
+ types.forEach(addImplicitCheck);
+ }
+
+ worldBuilder.isChecks.forEach((DartType type) {
+ if (type is FutureOrType) {
+ addImplicitCheck(commonElements.futureType(type.typeArgument));
+ addImplicitCheck(type.typeArgument);
+ }
+ });
+
// Compute type arguments of classes that use one of their type variables in
// is-checks and add the is-checks that they imply.
_classes.forEach((ClassEntity cls, ClassNode node) {
@@ -1031,7 +1099,7 @@
InterfaceType instance = types.asInstanceOf(type, cls);
if (instance != null) {
for (DartType argument in instance.typeArguments) {
- implicitIsChecks.add(argument.unaliased);
+ addImplicitCheck(argument.unaliased);
}
}
}
@@ -1042,7 +1110,7 @@
if (!_getMethodNode(elementEnvironment, worldBuilder, function).hasTest) {
return;
}
- implicitIsChecks.addAll(typeArguments);
+ addImplicitChecks(typeArguments);
});
if (forRtiNeeds) {
@@ -1059,7 +1127,7 @@
.add(node.entity);
}
if (node.hasTest) {
- implicitIsChecks.addAll(typeArguments);
+ addImplicitChecks(typeArguments);
}
}
}
@@ -1135,6 +1203,7 @@
bool get hasUse => hasTest || hasLiteral;
+ /// Register that if [entity] needs type arguments then so does `node.entity`.
bool addDependency(RtiNode node) {
if (entity == node.entity) {
// Skip trivial dependencies; if [entity] needs type arguments so does
@@ -1145,6 +1214,10 @@
return _dependencies.add(node);
}
+ void markTest({bool direct}) {
+ setTestState(direct ? 1 : 2);
+ }
+
void markDirectTest() {
setTestState(1);
}
@@ -1393,6 +1466,10 @@
if (type.isFunctionType) {
checkClosures(potentialSubtypeOf: type);
}
+ if (type is FutureOrType) {
+ potentiallyNeedTypeArguments(
+ closedWorld.commonElements.futureClass);
+ }
}
});
}
@@ -1561,7 +1638,6 @@
classUseMapForTesting = classUseMap;
}
- Set<ClassEntity> checkedClasses = new Set<ClassEntity>();
Set<FunctionType> checkedFunctionTypes = new Set<FunctionType>();
TypeVisitor liveTypeVisitor =
@@ -1618,11 +1694,14 @@
codegenWorldBuilder.forEachStaticTypeArgument(processMethodTypeArguments);
codegenWorldBuilder.forEachDynamicTypeArgument(processMethodTypeArguments);
+ bool isFunctionChecked = false;
+
void processCheckedType(DartType t) {
if (t is FunctionType) {
checkedFunctionTypes.add(t);
} else if (t is InterfaceType) {
- checkedClasses.add(t.element);
+ isFunctionChecked =
+ isFunctionChecked || t.element == _commonElements.functionClass;
}
testedTypeVisitor.visitType(t, false);
}
@@ -1638,8 +1717,7 @@
// In Dart 2, a closure class implements the function type of its `call`
// method and needs a signature function for testing its function type
// against typedefs and function types that are used in is-checks.
- if (checkedClasses.contains(_commonElements.functionClass) ||
- checkedFunctionTypes.isNotEmpty) {
+ if (isFunctionChecked || checkedFunctionTypes.isNotEmpty) {
Set<ClassEntity> processedClasses = new Set<ClassEntity>();
void processClass(ClassEntity cls) {
@@ -1737,6 +1815,13 @@
return _representationGenerator.templateForIsFunctionType;
}
+ /// Returns the JavaScript template to determine at runtime if a type object
+ /// is a FutureOr type.
+ @override
+ jsAst.Template get templateForIsFutureOrType {
+ return _representationGenerator.templateForIsFutureOrType;
+ }
+
@override
jsAst.Expression getTypeRepresentation(
Emitter emitter, DartType type, OnVariableCallback onVariable,
@@ -1987,6 +2072,12 @@
return jsAst.js.expressionTemplateFor("'${namer.functionTypeTag}' in #");
}
+ /// Returns the JavaScript template to determine at runtime if a type object
+ /// is a FutureOr type.
+ jsAst.Template get templateForIsFutureOrType {
+ return jsAst.js.expressionTemplateFor("'${namer.futureOrTag}' in #");
+ }
+
jsAst.Expression visitFunctionType(FunctionType type, Emitter emitter) {
List<jsAst.Property> properties = <jsAst.Property>[];
@@ -2115,9 +2206,21 @@
}
@override
- jsAst.Expression visitFutureOrType(FutureOrType type, Emitter argument) {
- // TODO(johnniwinther,sigmund): Implement runtime semantics for `FutureOr`.
- return getDynamicValue();
+ jsAst.Expression visitFutureOrType(FutureOrType type, Emitter emitter) {
+ List<jsAst.Property> properties = <jsAst.Property>[];
+
+ void addProperty(String name, jsAst.Expression value) {
+ properties.add(new jsAst.Property(js.string(name), value));
+ }
+
+ // Type representations for FutureOr have a property which is a tag marking
+ // them as FutureOr types. The value is not used, so '1' is just a dummy.
+ addProperty(namer.futureOrTag, js.number(1));
+ if (!type.typeArgument.treatAsDynamic) {
+ addProperty(namer.futureOrTypeTag, visit(type.typeArgument, emitter));
+ }
+
+ return new jsAst.ObjectInitializer(properties);
}
}
diff --git a/pkg/compiler/lib/src/js_emitter/full_emitter/emitter.dart b/pkg/compiler/lib/src/js_emitter/full_emitter/emitter.dart
index 44bc1a5..bc177a0 100644
--- a/pkg/compiler/lib/src/js_emitter/full_emitter/emitter.dart
+++ b/pkg/compiler/lib/src/js_emitter/full_emitter/emitter.dart
@@ -336,6 +336,9 @@
case JsBuiltin.isFunctionType:
return backend.rtiEncoder.templateForIsFunctionType;
+ case JsBuiltin.isFutureOrType:
+ return backend.rtiEncoder.templateForIsFutureOrType;
+
case JsBuiltin.rawRtiToJsConstructorName:
return jsAst.js.expressionTemplateFor("#.$typeNameProperty");
@@ -1049,8 +1052,7 @@
jsAst.Expression generateLibraryDescriptor(
LibraryEntity library, Fragment fragment) {
dynamic uri = "";
- if (!compiler.options.enableMinification ||
- backend.mirrorsData.mustPreserveUris) {
+ if (!compiler.options.enableMinification) {
uri = library.canonicalUri;
if (uri.scheme == 'file' && compiler.options.outputUri != null) {
uri =
diff --git a/pkg/compiler/lib/src/js_emitter/startup_emitter/emitter.dart b/pkg/compiler/lib/src/js_emitter/startup_emitter/emitter.dart
index f1b2ad4..19b685b 100644
--- a/pkg/compiler/lib/src/js_emitter/startup_emitter/emitter.dart
+++ b/pkg/compiler/lib/src/js_emitter/startup_emitter/emitter.dart
@@ -126,6 +126,9 @@
case JsBuiltin.isFunctionType:
return _backend.rtiEncoder.templateForIsFunctionType;
+ case JsBuiltin.isFutureOrType:
+ return _backend.rtiEncoder.templateForIsFutureOrType;
+
case JsBuiltin.rawRtiToJsConstructorName:
return js.js.expressionTemplateFor("#.name");
diff --git a/pkg/compiler/lib/src/js_model/closure.dart b/pkg/compiler/lib/src/js_model/closure.dart
index 9ab7fc6..a56afcf 100644
--- a/pkg/compiler/lib/src/js_model/closure.dart
+++ b/pkg/compiler/lib/src/js_model/closure.dart
@@ -81,6 +81,10 @@
/// Map of the scoping information that corresponds to a particular entity.
Map<MemberEntity, ScopeInfo> _scopeMap = <MemberEntity, ScopeInfo>{};
Map<ir.Node, CapturedScope> _capturedScopesMap = <ir.Node, CapturedScope>{};
+ // Indicates the type variables (if any) that are captured in a given
+ // Signature function.
+ Map<MemberEntity, CapturedScope> _capturedScopeForSignatureMap =
+ <MemberEntity, CapturedScope>{};
Map<MemberEntity, ClosureRepresentationInfo> _memberClosureRepresentationMap =
<MemberEntity, ClosureRepresentationInfo>{};
@@ -226,6 +230,27 @@
// Add also for the call method.
_scopeMap[closureClassInfo.callMethod] = closureClassInfo;
_scopeMap[closureClassInfo.signatureMethod] = closureClassInfo;
+
+ // Set up capturedScope for signature method. This is distinct from
+ // _capturedScopesMap because there is no corresponding ir.Node for the
+ // signature.
+ if (localFunctionNeedsSignature(functionNode.parent) &&
+ model.capturedScopesMap[functionNode] != null) {
+ KernelCapturedScope capturedScope =
+ model.capturedScopesMap[functionNode];
+ assert(capturedScope is! KernelCapturedLoopScope);
+ KernelCapturedScope signatureCapturedScope =
+ new KernelCapturedScope.forSignature(capturedScope);
+ _updateScopeBasedOnRtiNeed(
+ signatureCapturedScope,
+ classNeedsTypeArguments,
+ methodNeedsTypeArguments,
+ localFunctionNeedsTypeArguments,
+ member);
+ _capturedScopeForSignatureMap[closureClassInfo.signatureMethod] =
+ new JsCapturedScope.from(
+ {}, signatureCapturedScope, localsMap, _elementMap);
+ }
callMethods.add(closureClassInfo.callMethod);
}
});
@@ -304,8 +329,9 @@
case MemberKind.constructor:
case MemberKind.constructorBody:
case MemberKind.closureCall:
- case MemberKind.signature:
return _capturedScopesMap[definition.node] ?? const CapturedScope();
+ case MemberKind.signature:
+ return _capturedScopeForSignatureMap[entity] ?? const CapturedScope();
default:
throw failedAt(entity, "Unexpected member definition $definition");
}
@@ -472,6 +498,23 @@
thisUsedAsFreeVariableIfNeedsRti,
hasThisLocal);
+ // Loops through the free variables of an existing KernelCapturedScope and
+ // creates a new KernelCapturedScope that only captures type variables.
+ KernelCapturedScope.forSignature(KernelCapturedScope scope)
+ : this(
+ _empty,
+ null,
+ _empty,
+ scope.freeVariables.where(
+ (ir.Node variable) => variable is TypeVariableTypeWithContext),
+ scope.freeVariablesForRti,
+ scope.thisUsedAsFreeVariable,
+ scope.thisUsedAsFreeVariableIfNeedsRti,
+ scope.hasThisLocal);
+
+ // Silly hack because we don't have const sets.
+ static final Set<ir.VariableDeclaration> _empty = new Set();
+
bool get requiresContextBox => boxedVariables.isNotEmpty;
}
diff --git a/pkg/compiler/lib/src/kernel/element_map_impl.dart b/pkg/compiler/lib/src/kernel/element_map_impl.dart
index e00692e..63c2d8f 100644
--- a/pkg/compiler/lib/src/kernel/element_map_impl.dart
+++ b/pkg/compiler/lib/src/kernel/element_map_impl.dart
@@ -1733,6 +1733,11 @@
// cased in the builder, nested invalid types are treated as `dynamic`.
return const DynamicType();
}
+
+ @override
+ DartType visitBottomType(ir.BottomType node) {
+ return elementMap.commonElements.nullType;
+ }
}
/// [native.BehaviorBuilder] for kernel based elements.
diff --git a/pkg/compiler/lib/src/kernel/kernel_strategy.dart b/pkg/compiler/lib/src/kernel/kernel_strategy.dart
index 8106841..ef19c0b 100644
--- a/pkg/compiler/lib/src/kernel/kernel_strategy.dart
+++ b/pkg/compiler/lib/src/kernel/kernel_strategy.dart
@@ -266,7 +266,7 @@
class MirrorsDataBuilderImpl extends MirrorsDataImpl {
MirrorsDataBuilderImpl(
ElementEnvironment elementEnvironment, CommonElements commonElements)
- : super(null, null, elementEnvironment, commonElements);
+ : super(null, elementEnvironment, commonElements);
@override
void registerUsedMember(MemberEntity member) {}
diff --git a/pkg/compiler/lib/src/native/native.dart b/pkg/compiler/lib/src/native/native.dart
index 9ba9755..5b50350 100644
--- a/pkg/compiler/lib/src/native/native.dart
+++ b/pkg/compiler/lib/src/native/native.dart
@@ -24,7 +24,7 @@
'web_sql'
];
-bool maybeEnableNative(Uri uri, {bool allowNativeExtensions: false}) {
+bool maybeEnableNative(Uri uri) {
bool allowedTestLibrary() {
String scriptName = uri.path;
return scriptName.contains('tests/compiler/dart2js_native') ||
@@ -36,5 +36,5 @@
return _allowedDartSchemePaths.contains(uri.path);
}
- return allowedTestLibrary() || allowedDartLibary() || allowNativeExtensions;
+ return allowedTestLibrary() || allowedDartLibary();
}
diff --git a/pkg/compiler/lib/src/options.dart b/pkg/compiler/lib/src/options.dart
index c42e066..4a40348 100644
--- a/pkg/compiler/lib/src/options.dart
+++ b/pkg/compiler/lib/src/options.dart
@@ -40,61 +40,58 @@
/// as few as possible.
class CompilerOptions implements DiagnosticOptions {
/// The entry point of the application that is being compiled.
- final Uri entryPoint;
+ Uri entryPoint;
/// Root location where SDK libraries are found.
- final Uri libraryRoot;
+ Uri libraryRoot;
/// Package root location.
///
/// If not null then [packageConfig] should be null.
- final Uri packageRoot;
+ Uri packageRoot;
/// Location of the package configuration file.
///
/// If not null then [packageRoot] should be null.
- final Uri packageConfig;
+ Uri packageConfig;
// TODO(sigmund): Move out of here, maybe to CompilerInput. Options should not
// hold code, just configuration options.
- final PackagesDiscoveryProvider packagesDiscoveryProvider;
+ PackagesDiscoveryProvider packagesDiscoveryProvider;
/// Resolved constant "environment" values passed to the compiler via the `-D`
/// flags.
- final Map<String, dynamic> environment;
+ Map<String, dynamic> environment = const <String, dynamic>{};
/// A possibly null state object for kernel compilation.
fe.InitializedCompilerState kernelInitializedCompilerState;
/// Whether we allow mocking compilation of libraries such as dart:io and
/// dart:html for unit testing purposes.
- final bool allowMockCompilation;
-
- /// Whether the native extension syntax is supported by the frontend.
- final bool allowNativeExtensions;
+ bool allowMockCompilation = false;
/// Whether to resolve all functions in the program, not just those reachable
/// from main. This implies [analyzeOnly] is true as well.
- final bool analyzeAll;
+ bool analyzeAll = false;
/// Whether to disable tree-shaking for the main script. This marks all
/// functions in the main script as reachable (not just a function named
/// `main`).
// TODO(sigmund): rename. The current name seems to indicate that only the
// main function is retained, which is the opposite of what this does.
- final bool analyzeMain;
+ bool analyzeMain = false;
/// Whether to run the compiler just for the purpose of analysis. That is, to
/// run resolution and type-checking alone, but otherwise do not generate any
/// code.
- final bool analyzeOnly;
+ bool analyzeOnly = false;
/// Whether to skip analysis of method bodies and field initializers. Implies
/// [analyzeOnly].
- final bool analyzeSignaturesOnly;
+ bool analyzeSignaturesOnly = false;
/// ID associated with this sdk build.
- final String buildId;
+ String buildId = _UNDETERMINED_BUILD_ID;
/// Whether there is a build-id available so we can use it on error messages
/// and in the emitted output of the compiler.
@@ -102,126 +99,123 @@
/// Whether to compile for the server category. This is used to compile to JS
/// that is intended to be run on server-side VMs like nodejs.
- final bool compileForServer;
+ bool compileForServer = false;
/// Location where to generate a map containing details of how deferred
/// libraries are subdivided.
- final Uri deferredMapUri;
+ Uri deferredMapUri;
/// Whether to disable inlining during the backend optimizations.
// TODO(sigmund): negate, so all flags are positive
- final bool disableInlining;
+ bool disableInlining = false;
/// Disable deferred loading, instead generate everything in one output unit.
/// Note: the resulting program still correctly checks that loadLibrary &
/// checkLibrary calls are correct.
- final bool disableProgramSplit;
+ bool disableProgramSplit = false;
/// Diagnostic option: If `true`, warnings cause the compilation to fail.
- final bool fatalWarnings;
+ bool fatalWarnings = false;
/// Diagnostic option: Emit terse diagnostics without howToFix.
- final bool terseDiagnostics;
+ bool terseDiagnostics = false;
/// Diagnostic option: If `true`, warnings are not reported.
- final bool suppressWarnings;
+ bool suppressWarnings = false;
/// Diagnostic option: If `true`, hints are not reported.
- final bool suppressHints;
+ bool suppressHints = false;
/// Diagnostic option: List of packages for which warnings and hints are
/// reported. If `null`, no package warnings or hints are reported. If
/// empty, all warnings and hints are reported.
- final List<String> _shownPackageWarnings;
+ List<String> shownPackageWarnings; // &&&&&
/// Whether to disable global type inference.
- final bool disableTypeInference;
+ bool disableTypeInference = false;
/// Whether to disable optimization for need runtime type information.
- final bool disableRtiOptimization;
+ bool disableRtiOptimization = false;
/// Whether to emit a .json file with a summary of the information used by the
/// compiler during optimization. This includes resolution details,
/// dependencies between elements, results of type inference, and the output
/// code for each function.
- final bool dumpInfo;
+ bool dumpInfo = false;
/// Whether we allow passing an extra argument to `assert`, containing a
/// reason for why an assertion fails. (experimental)
///
/// This is only included so that tests can pass the --assert-message flag
/// without causing dart2js to crash. The flag has no effect.
- final bool enableAssertMessage;
+ bool enableAssertMessage = true;
/// Whether the user specified a flag to allow the use of dart:mirrors. This
/// silences a warning produced by the compiler.
- final bool enableExperimentalMirrors;
+ bool enableExperimentalMirrors = false;
/// Whether to enable minification
// TODO(sigmund): rename to minify
- final bool enableMinification;
+ bool enableMinification = false;
/// Whether to model which native classes are live based on annotations on the
/// core libraries. If false, all native classes will be included by default.
- final bool enableNativeLiveTypeAnalysis;
+ bool enableNativeLiveTypeAnalysis = true;
/// Whether to generate code containing checked-mode assignability checks.
- final bool enableTypeAssertions;
+ bool enableTypeAssertions = false;
/// Whether to generate code containing user's `assert` statements.
- final bool enableUserAssertions;
+ bool enableUserAssertions = false;
/// Whether to generate output even when there are compile-time errors.
- final bool generateCodeWithCompileTimeErrors;
+ bool generateCodeWithCompileTimeErrors = false;
/// Whether to generate a source-map file together with the output program.
- final bool generateSourceMap;
+ bool generateSourceMap = true;
/// URI of the main output if the compiler is generating source maps.
- final Uri outputUri;
+ Uri outputUri;
/// Location of the platform configuration file.
// TODO(sigmund): deprecate and remove, use only [librariesSpecificationUri]
- final Uri platformConfigUri;
+ Uri platformConfigUri;
/// Location of the libraries specification file.
- final Uri librariesSpecificationUri;
+ Uri librariesSpecificationUri;
/// Location of the kernel platform `.dill` files.
- final Uri platformBinaries;
-
- /// Whether to emit URIs in the reflection metadata.
- final bool preserveUris;
+ Uri platformBinaries;
/// The locations of serialized data used for resolution.
- final List<Uri> resolutionInputs;
+ List<Uri> resolutionInputs;
/// The location of the serialized data from resolution.
- final Uri resolutionOutput;
+ Uri resolutionOutput;
/// If `true`, sources are resolved and serialized.
- final bool resolveOnly;
+ bool resolveOnly = false;
/// If `true`, sources are only available from serialized data.
- final bool compileOnly;
+ bool compileOnly = false;
/// URI where the compiler should generate the output source map file.
- final Uri sourceMapUri;
+ Uri sourceMapUri;
/// The compiler is run from the build bot.
- final bool testMode;
+ bool testMode = false;
/// Whether to trust JS-interop annotations. (experimental)
- final bool trustJSInteropTypeAnnotations;
+ bool trustJSInteropTypeAnnotations = false;
/// Whether to trust primitive types during inference and optimizations.
- final bool trustPrimitives;
+ bool trustPrimitives = false;
/// Whether to trust type annotations during inference and optimizations.
- final bool trustTypeAnnotations;
+ bool trustTypeAnnotations = false;
/// Whether to generate code compliant with content security policy (CSP).
- final bool useContentSecurityPolicy;
+ bool useContentSecurityPolicy = false;
/// Preview the unified front-end and compilation from kernel.
///
@@ -232,37 +226,37 @@
/// When this flag is on, the compiler also accepts reading .dill files from
/// disk. The compiler reads the sources differently depending on the
/// extension format.
- final bool useKernel;
+ bool useKernel = true;
/// Enables strong mode in dart2js.
///
/// This is work-in-progress and will only be supported for [useKernel].
- final bool strongMode;
+ bool strongMode = false;
/// When obfuscating for minification, whether to use the frequency of a name
/// as an heuristic to pick shorter names.
- final bool useFrequencyNamer;
+ bool useFrequencyNamer = true;
/// Whether to generate source-information from both the old and the new
/// source-information engines. (experimental)
- final bool useMultiSourceInfo;
+ bool useMultiSourceInfo = false;
/// Whether to use the new source-information implementation for source-maps.
/// (experimental)
- final bool useNewSourceInfo;
+ bool useNewSourceInfo = false;
/// Whether the user requested to use the fast startup emitter. The full
/// emitter might still be used if the program uses dart:mirrors.
- final bool useStartupEmitter;
+ bool useStartupEmitter = false;
/// Enable verbose printing during compilation. Includes progress messages
/// during each phase and a time-breakdown between phases at the end.
- final bool verbose;
+ bool verbose = false;
/// Track allocations in the JS output.
///
/// This is an experimental feature.
- final bool experimentalTrackAllocations;
+ bool experimentalTrackAllocations = false;
/// The path to the file that contains the profiled allocations.
///
@@ -270,175 +264,84 @@
/// [experimentalTrackAllocations] encoded as a JSON map.
///
/// This is an experimental feature.
- final String experimentalAllocationsPath;
+ String experimentalAllocationsPath;
// -------------------------------------------------
// Options for deprecated features
// -------------------------------------------------
// TODO(sigmund): delete these as we delete the underlying features
- /// Whether to preserve comments while scanning (only use for dart:mirrors).
- final bool preserveComments;
-
- /// Strip option used by dart2dart.
- final List<String> strips;
-
/// Whether to start `async` functions synchronously.
- final bool startAsyncSynchronously;
+ bool startAsyncSynchronously = false;
/// Create an options object by parsing flags from [options].
- factory CompilerOptions.parse(
- {Uri entryPoint,
- Uri libraryRoot,
- Uri packageRoot,
- Uri packageConfig,
- Uri platformBinaries,
- List<Uri> resolutionInputs,
- Uri resolutionOutput,
- PackagesDiscoveryProvider packagesDiscoveryProvider,
- Map<String, dynamic> environment: const <String, dynamic>{},
- List<String> options}) {
- return new CompilerOptions(
- entryPoint: entryPoint,
- libraryRoot: libraryRoot,
- packageRoot: packageRoot,
- packageConfig: packageConfig,
- packagesDiscoveryProvider: packagesDiscoveryProvider,
- environment: environment,
- allowMockCompilation: _hasOption(options, Flags.allowMockCompilation),
- allowNativeExtensions: _hasOption(options, Flags.allowNativeExtensions),
- analyzeAll: _hasOption(options, Flags.analyzeAll),
- analyzeMain: _hasOption(options, Flags.analyzeMain),
- analyzeOnly: _hasOption(options, Flags.analyzeOnly),
- analyzeSignaturesOnly: _hasOption(options, Flags.analyzeSignaturesOnly),
- buildId: _extractStringOption(
- options, '--build-id=', _UNDETERMINED_BUILD_ID),
- compileForServer: _resolveCompileForServerFromOptions(options),
- deferredMapUri: _extractUriOption(options, '--deferred-map='),
- fatalWarnings: _hasOption(options, Flags.fatalWarnings),
- terseDiagnostics: _hasOption(options, Flags.terse),
- suppressWarnings: _hasOption(options, Flags.suppressWarnings),
- suppressHints: _hasOption(options, Flags.suppressHints),
- shownPackageWarnings:
- _extractOptionalCsvOption(options, Flags.showPackageWarnings),
- disableInlining: _hasOption(options, Flags.disableInlining),
- disableProgramSplit: _hasOption(options, Flags.disableProgramSplit),
- disableTypeInference: _hasOption(options, Flags.disableTypeInference),
- disableRtiOptimization:
- _hasOption(options, Flags.disableRtiOptimization),
- dumpInfo: _hasOption(options, Flags.dumpInfo),
- enableExperimentalMirrors:
- _hasOption(options, Flags.enableExperimentalMirrors),
- enableMinification: _hasOption(options, Flags.minify),
- enableNativeLiveTypeAnalysis:
- !_hasOption(options, Flags.disableNativeLiveTypeAnalysis),
- enableTypeAssertions: _hasOption(options, Flags.enableCheckedMode),
- enableUserAssertions: _hasOption(options, Flags.enableCheckedMode) ||
- _hasOption(options, Flags.enableAsserts),
- experimentalTrackAllocations:
- _hasOption(options, Flags.experimentalTrackAllocations),
- experimentalAllocationsPath: _extractStringOption(
- options, "${Flags.experimentalAllocationsPath}=", null),
- generateCodeWithCompileTimeErrors:
- _hasOption(options, Flags.generateCodeWithCompileTimeErrors),
- generateSourceMap: !_hasOption(options, Flags.noSourceMaps),
- outputUri: _extractUriOption(options, '--out='),
- platformConfigUri:
- _resolvePlatformConfigFromOptions(libraryRoot, options),
- librariesSpecificationUri: _resolveLibrariesSpecification(libraryRoot),
- platformBinaries: platformBinaries ??
- _extractUriOption(options, '--platform-binaries='),
- preserveComments: _hasOption(options, Flags.preserveComments),
- preserveUris: _hasOption(options, Flags.preserveUris),
- resolutionInputs: resolutionInputs,
- resolutionOutput: resolutionOutput,
- resolveOnly: _hasOption(options, Flags.resolveOnly),
- sourceMapUri: _extractUriOption(options, '--source-map='),
- strips: _extractCsvOption(options, '--force-strip='),
- strongMode: _hasOption(options, Flags.strongMode),
- testMode: _hasOption(options, Flags.testMode),
- trustJSInteropTypeAnnotations:
- _hasOption(options, Flags.trustJSInteropTypeAnnotations),
- trustPrimitives: _hasOption(options, Flags.trustPrimitives),
- trustTypeAnnotations: _hasOption(options, Flags.trustTypeAnnotations),
- useContentSecurityPolicy:
- _hasOption(options, Flags.useContentSecurityPolicy),
- useKernel: !_hasOption(options, Flags.useOldFrontend),
- useFrequencyNamer:
- !_hasOption(options, Flags.noFrequencyBasedMinification),
- useMultiSourceInfo: _hasOption(options, Flags.useMultiSourceInfo),
- useNewSourceInfo: _hasOption(options, Flags.useNewSourceInfo),
- useStartupEmitter: _hasOption(options, Flags.fastStartup),
- startAsyncSynchronously: _hasOption(options, Flags.syncAsync),
- verbose: _hasOption(options, Flags.verbose));
+ static CompilerOptions parse(List<String> options,
+ {Uri libraryRoot, Uri platformBinaries}) {
+ return new CompilerOptions()
+ ..libraryRoot = libraryRoot
+ ..allowMockCompilation = _hasOption(options, Flags.allowMockCompilation)
+ ..analyzeAll = _hasOption(options, Flags.analyzeAll)
+ ..analyzeMain = _hasOption(options, Flags.analyzeMain)
+ ..analyzeOnly = _hasOption(options, Flags.analyzeOnly)
+ ..analyzeSignaturesOnly = _hasOption(options, Flags.analyzeSignaturesOnly)
+ ..buildId =
+ _extractStringOption(options, '--build-id=', _UNDETERMINED_BUILD_ID)
+ ..compileForServer = _resolveCompileForServerFromOptions(options)
+ ..deferredMapUri = _extractUriOption(options, '--deferred-map=')
+ ..fatalWarnings = _hasOption(options, Flags.fatalWarnings)
+ ..terseDiagnostics = _hasOption(options, Flags.terse)
+ ..suppressWarnings = _hasOption(options, Flags.suppressWarnings)
+ ..suppressHints = _hasOption(options, Flags.suppressHints)
+ ..shownPackageWarnings =
+ _extractOptionalCsvOption(options, Flags.showPackageWarnings)
+ ..disableInlining = _hasOption(options, Flags.disableInlining)
+ ..disableProgramSplit = _hasOption(options, Flags.disableProgramSplit)
+ ..disableTypeInference = _hasOption(options, Flags.disableTypeInference)
+ ..disableRtiOptimization =
+ _hasOption(options, Flags.disableRtiOptimization)
+ ..dumpInfo = _hasOption(options, Flags.dumpInfo)
+ ..enableExperimentalMirrors =
+ _hasOption(options, Flags.enableExperimentalMirrors)
+ ..enableMinification = _hasOption(options, Flags.minify)
+ ..enableNativeLiveTypeAnalysis =
+ !_hasOption(options, Flags.disableNativeLiveTypeAnalysis)
+ ..enableTypeAssertions = _hasOption(options, Flags.enableCheckedMode)
+ ..enableUserAssertions = _hasOption(options, Flags.enableCheckedMode) ||
+ _hasOption(options, Flags.enableAsserts)
+ ..experimentalTrackAllocations =
+ _hasOption(options, Flags.experimentalTrackAllocations)
+ ..experimentalAllocationsPath = _extractStringOption(
+ options, "${Flags.experimentalAllocationsPath}=", null)
+ ..generateCodeWithCompileTimeErrors =
+ _hasOption(options, Flags.generateCodeWithCompileTimeErrors)
+ ..generateSourceMap = !_hasOption(options, Flags.noSourceMaps)
+ ..outputUri = _extractUriOption(options, '--out=')
+ ..platformConfigUri =
+ _resolvePlatformConfigFromOptions(libraryRoot, options)
+ ..librariesSpecificationUri = _resolveLibrariesSpecification(libraryRoot)
+ ..platformBinaries =
+ platformBinaries ?? _extractUriOption(options, '--platform-binaries=')
+ ..resolveOnly = _hasOption(options, Flags.resolveOnly)
+ ..sourceMapUri = _extractUriOption(options, '--source-map=')
+ ..strongMode = _hasOption(options, Flags.strongMode)
+ ..testMode = _hasOption(options, Flags.testMode)
+ ..trustJSInteropTypeAnnotations =
+ _hasOption(options, Flags.trustJSInteropTypeAnnotations)
+ ..trustPrimitives = _hasOption(options, Flags.trustPrimitives)
+ ..trustTypeAnnotations = _hasOption(options, Flags.trustTypeAnnotations)
+ ..useContentSecurityPolicy =
+ _hasOption(options, Flags.useContentSecurityPolicy)
+ ..useKernel = !_hasOption(options, Flags.useOldFrontend)
+ ..useFrequencyNamer =
+ !_hasOption(options, Flags.noFrequencyBasedMinification)
+ ..useMultiSourceInfo = _hasOption(options, Flags.useMultiSourceInfo)
+ ..useNewSourceInfo = _hasOption(options, Flags.useNewSourceInfo)
+ ..useStartupEmitter = _hasOption(options, Flags.fastStartup)
+ ..startAsyncSynchronously = _hasOption(options, Flags.syncAsync)
+ ..verbose = _hasOption(options, Flags.verbose);
}
- /// Creates an option object for the compiler.
- ///
- /// This validates and normalizes dependent options to be consistent. For
- /// example, if [analyzeAll] is true, the resulting options object will also
- /// have [analyzeOnly] as true.
- factory CompilerOptions(
- {Uri entryPoint,
- Uri libraryRoot,
- Uri packageRoot,
- Uri packageConfig,
- PackagesDiscoveryProvider packagesDiscoveryProvider,
- Map<String, dynamic> environment: const <String, dynamic>{},
- bool allowMockCompilation: false,
- bool allowNativeExtensions: false,
- bool analyzeAll: false,
- bool analyzeMain: false,
- bool analyzeOnly: false,
- bool analyzeSignaturesOnly: false,
- String buildId: _UNDETERMINED_BUILD_ID,
- bool compileForServer: false,
- Uri deferredMapUri: null,
- bool fatalWarnings: false,
- bool terseDiagnostics: false,
- bool suppressWarnings: false,
- bool suppressHints: false,
- List<String> shownPackageWarnings: null,
- bool disableInlining: false,
- bool disableProgramSplit: false,
- bool disableTypeInference: false,
- bool disableRtiOptimization: false,
- bool dumpInfo: false,
- bool enableAssertMessage: true,
- bool enableExperimentalMirrors: false,
- bool enableMinification: false,
- bool enableNativeLiveTypeAnalysis: true,
- bool enableTypeAssertions: false,
- bool enableUserAssertions: false,
- bool experimentalTrackAllocations: false,
- String experimentalAllocationsPath: null,
- bool generateCodeWithCompileTimeErrors: false,
- bool generateSourceMap: true,
- bool kernelGlobalInference: false,
- Uri outputUri: null,
- Uri platformConfigUri: null,
- Uri librariesSpecificationUri: null,
- Uri platformBinaries: null,
- bool preserveComments: false,
- bool preserveUris: false,
- List<Uri> resolutionInputs: null,
- Uri resolutionOutput: null,
- bool resolveOnly: false,
- Uri sourceMapUri: null,
- List<String> strips: const [],
- bool strongMode: false,
- bool testMode: false,
- bool trustJSInteropTypeAnnotations: false,
- bool trustPrimitives: false,
- bool trustTypeAnnotations: false,
- bool useContentSecurityPolicy: false,
- bool useKernel: true,
- bool useFrequencyNamer: true,
- bool useMultiSourceInfo: false,
- bool useNewSourceInfo: false,
- bool useStartupEmitter: false,
- bool startAsyncSynchronously: false,
- bool verbose: false}) {
+ void validate() {
// TODO(sigmund): should entrypoint be here? should we validate it is not
// null? In unittests we use the same compiler to analyze or build multiple
// entrypoints.
@@ -455,292 +358,37 @@
if (packageRoot != null && !packageRoot.path.endsWith("/")) {
throw new ArgumentError("[packageRoot] must end with a /");
}
- if (!analyzeOnly) {
- if (allowNativeExtensions) {
- throw new ArgumentError(
- "${Flags.allowNativeExtensions} is only supported in combination "
- "with ${Flags.analyzeOnly}");
- }
- }
if (useKernel && platformBinaries == null) {
throw new ArgumentError("Missing required ${Flags.platformBinaries}");
}
- return new CompilerOptions._(entryPoint, libraryRoot, packageRoot,
- packageConfig, packagesDiscoveryProvider, environment,
- allowMockCompilation: allowMockCompilation,
- allowNativeExtensions: allowNativeExtensions,
- analyzeAll: analyzeAll || resolveOnly,
- analyzeMain: analyzeMain,
- analyzeOnly:
- analyzeOnly || analyzeSignaturesOnly || analyzeAll || resolveOnly,
- analyzeSignaturesOnly: analyzeSignaturesOnly,
- buildId: buildId,
- compileForServer: compileForServer,
- deferredMapUri: deferredMapUri,
- fatalWarnings: fatalWarnings,
- terseDiagnostics: terseDiagnostics,
- suppressWarnings: suppressWarnings,
- suppressHints: suppressHints,
- shownPackageWarnings: shownPackageWarnings,
- disableInlining: disableInlining,
- disableProgramSplit: disableProgramSplit,
- disableTypeInference: disableTypeInference,
- disableRtiOptimization: disableRtiOptimization,
- dumpInfo: dumpInfo,
- enableAssertMessage: enableAssertMessage,
- enableExperimentalMirrors: enableExperimentalMirrors,
- enableMinification: enableMinification,
- enableNativeLiveTypeAnalysis: enableNativeLiveTypeAnalysis,
- enableTypeAssertions: enableTypeAssertions,
- enableUserAssertions: enableUserAssertions,
- experimentalTrackAllocations: experimentalTrackAllocations,
- experimentalAllocationsPath: experimentalAllocationsPath,
- generateCodeWithCompileTimeErrors:
- generateCodeWithCompileTimeErrors && !useKernel,
- generateSourceMap: generateSourceMap,
- outputUri: outputUri,
- platformConfigUri: platformConfigUri ??
- _resolvePlatformConfig(libraryRoot, null, const []),
- librariesSpecificationUri: _resolveLibrariesSpecification(libraryRoot),
- platformBinaries: platformBinaries,
- preserveComments: preserveComments,
- preserveUris: preserveUris,
- resolutionInputs: resolutionInputs,
- resolutionOutput: resolutionOutput,
- resolveOnly: resolveOnly,
- sourceMapUri: sourceMapUri,
- strips: strips,
- strongMode: strongMode,
- testMode: testMode,
- trustJSInteropTypeAnnotations: trustJSInteropTypeAnnotations,
- trustPrimitives: trustPrimitives,
- trustTypeAnnotations: trustTypeAnnotations,
- useContentSecurityPolicy: useContentSecurityPolicy,
- useKernel: useKernel,
- useFrequencyNamer: useFrequencyNamer,
- useMultiSourceInfo: useMultiSourceInfo,
- useNewSourceInfo: useNewSourceInfo,
- useStartupEmitter: useStartupEmitter,
- startAsyncSynchronously: startAsyncSynchronously,
- verbose: verbose);
}
- CompilerOptions._(this.entryPoint, this.libraryRoot, this.packageRoot,
- this.packageConfig, this.packagesDiscoveryProvider, this.environment,
- {this.allowMockCompilation: false,
- this.allowNativeExtensions: false,
- this.analyzeAll: false,
- this.analyzeMain: false,
- this.analyzeOnly: false,
- this.analyzeSignaturesOnly: false,
- this.buildId: _UNDETERMINED_BUILD_ID,
- this.compileForServer: false,
- this.deferredMapUri: null,
- this.fatalWarnings: false,
- this.terseDiagnostics: false,
- this.suppressWarnings: false,
- this.suppressHints: false,
- List<String> shownPackageWarnings: null,
- this.disableInlining: false,
- this.disableProgramSplit: false,
- this.disableTypeInference: false,
- this.disableRtiOptimization: false,
- this.dumpInfo: false,
- this.enableAssertMessage: true,
- this.enableExperimentalMirrors: false,
- this.enableMinification: false,
- this.enableNativeLiveTypeAnalysis: false,
- this.enableTypeAssertions: false,
- this.enableUserAssertions: false,
- this.experimentalTrackAllocations: false,
- this.experimentalAllocationsPath: null,
- this.generateCodeWithCompileTimeErrors: false,
- this.generateSourceMap: true,
- this.outputUri: null,
- this.platformConfigUri: null,
- this.librariesSpecificationUri: null,
- this.platformBinaries: null,
- this.preserveComments: false,
- this.preserveUris: false,
- this.resolutionInputs: null,
- this.resolutionOutput: null,
- this.resolveOnly: false,
- this.compileOnly: false,
- this.sourceMapUri: null,
- this.strips: const [],
- this.strongMode: false,
- this.testMode: false,
- this.trustJSInteropTypeAnnotations: false,
- this.trustPrimitives: false,
- this.trustTypeAnnotations: false,
- this.useContentSecurityPolicy: false,
- this.useKernel: true,
- this.useFrequencyNamer: false,
- this.useMultiSourceInfo: false,
- this.useNewSourceInfo: false,
- this.useStartupEmitter: false,
- this.startAsyncSynchronously: false,
- this.verbose: false})
- : _shownPackageWarnings = shownPackageWarnings;
-
- /// Creates a copy of the [CompilerOptions] where the provided non-null
- /// option values replace existing.
- static CompilerOptions copy(CompilerOptions options,
- {entryPoint,
- libraryRoot,
- packageRoot,
- packageConfig,
- packagesDiscoveryProvider,
- environment,
- allowMockCompilation,
- allowNativeExtensions,
- analyzeAll,
- analyzeMain,
- analyzeOnly,
- analyzeSignaturesOnly,
- buildId,
- compileForServer,
- deferredMapUri,
- fatalWarnings,
- terseDiagnostics,
- suppressWarnings,
- suppressHints,
- List<String> shownPackageWarnings,
- disableInlining,
- disableProgramSplit,
- disableTypeInference,
- disableRtiOptimization,
- dumpInfo,
- enableAssertMessage,
- enableExperimentalMirrors,
- enableMinification,
- enableNativeLiveTypeAnalysis,
- enableTypeAssertions,
- enableUserAssertions,
- experimentalTrackAllocations,
- experimentalAllocationsPath,
- generateCodeWithCompileTimeErrors,
- generateSourceMap,
- kernelGlobalInference,
- outputUri,
- platformConfigUri,
- librariesSpecificationUri,
- platformBinaries,
- preserveComments,
- preserveUris,
- resolutionInputs,
- resolutionOutput,
- resolveOnly,
- compileOnly,
- sourceMapUri,
- strips,
- strongMode,
- testMode,
- trustJSInteropTypeAnnotations,
- trustPrimitives,
- trustTypeAnnotations,
- useContentSecurityPolicy,
- useKernel,
- useFrequencyNamer,
- useMultiSourceInfo,
- useNewSourceInfo,
- useStartupEmitter,
- verbose}) {
- return new CompilerOptions._(
- entryPoint ?? options.entryPoint,
- libraryRoot ?? options.libraryRoot,
- packageRoot ?? options.packageRoot,
- packageConfig ?? options.packageConfig,
- packagesDiscoveryProvider ?? options.packagesDiscoveryProvider,
- environment ?? options.environment,
- allowMockCompilation:
- allowMockCompilation ?? options.allowMockCompilation,
- allowNativeExtensions:
- allowNativeExtensions ?? options.allowNativeExtensions,
- analyzeAll: analyzeAll ?? options.analyzeAll,
- analyzeMain: analyzeMain ?? options.analyzeMain,
- analyzeOnly: analyzeOnly ?? options.analyzeOnly,
- analyzeSignaturesOnly:
- analyzeSignaturesOnly ?? options.analyzeSignaturesOnly,
- buildId: buildId ?? options.buildId,
- compileForServer: compileForServer ?? options.compileForServer,
- deferredMapUri: deferredMapUri ?? options.deferredMapUri,
- fatalWarnings: fatalWarnings ?? options.fatalWarnings,
- terseDiagnostics: terseDiagnostics ?? options.terseDiagnostics,
- suppressWarnings: suppressWarnings ?? options.suppressWarnings,
- suppressHints: suppressHints ?? options.suppressHints,
- shownPackageWarnings:
- shownPackageWarnings ?? options._shownPackageWarnings,
- disableInlining: disableInlining ?? options.disableInlining,
- disableProgramSplit: disableProgramSplit ?? options.disableProgramSplit,
- disableTypeInference:
- disableTypeInference ?? options.disableTypeInference,
- disableRtiOptimization:
- disableRtiOptimization ?? options.disableRtiOptimization,
- dumpInfo: dumpInfo ?? options.dumpInfo,
- enableAssertMessage: enableAssertMessage ?? options.enableAssertMessage,
- enableExperimentalMirrors:
- enableExperimentalMirrors ?? options.enableExperimentalMirrors,
- enableMinification: enableMinification ?? options.enableMinification,
- enableNativeLiveTypeAnalysis: enableNativeLiveTypeAnalysis ??
- options.enableNativeLiveTypeAnalysis,
- enableTypeAssertions:
- enableTypeAssertions ?? options.enableTypeAssertions,
- enableUserAssertions:
- enableUserAssertions ?? options.enableUserAssertions,
- experimentalTrackAllocations: experimentalTrackAllocations ??
- options.experimentalTrackAllocations,
- experimentalAllocationsPath:
- experimentalAllocationsPath ?? options.experimentalAllocationsPath,
- generateCodeWithCompileTimeErrors: generateCodeWithCompileTimeErrors ??
- options.generateCodeWithCompileTimeErrors,
- generateSourceMap: generateSourceMap ?? options.generateSourceMap,
- outputUri: outputUri ?? options.outputUri,
- platformConfigUri: platformConfigUri ?? options.platformConfigUri,
- librariesSpecificationUri:
- librariesSpecificationUri ?? options.librariesSpecificationUri,
- platformBinaries: platformBinaries ?? options.platformBinaries,
- preserveComments: preserveComments ?? options.preserveComments,
- preserveUris: preserveUris ?? options.preserveUris,
- resolutionInputs: resolutionInputs ?? options.resolutionInputs,
- resolutionOutput: resolutionOutput ?? options.resolutionOutput,
- resolveOnly: resolveOnly ?? options.resolveOnly,
- compileOnly: compileOnly ?? options.compileOnly,
- sourceMapUri: sourceMapUri ?? options.sourceMapUri,
- strips: strips ?? options.strips,
- strongMode: strongMode ?? options.strongMode,
- testMode: testMode ?? options.testMode,
- trustJSInteropTypeAnnotations: trustJSInteropTypeAnnotations ??
- options.trustJSInteropTypeAnnotations,
- trustPrimitives: trustPrimitives ?? options.trustPrimitives,
- trustTypeAnnotations:
- trustTypeAnnotations ?? options.trustTypeAnnotations,
- useContentSecurityPolicy:
- useContentSecurityPolicy ?? options.useContentSecurityPolicy,
- useKernel: useKernel ?? options.useKernel,
- useFrequencyNamer: useFrequencyNamer ?? options.useFrequencyNamer,
- useMultiSourceInfo: useMultiSourceInfo ?? options.useMultiSourceInfo,
- useNewSourceInfo: useNewSourceInfo ?? options.useNewSourceInfo,
- useStartupEmitter: useStartupEmitter ?? options.useStartupEmitter,
- verbose: verbose ?? options.verbose);
+ void deriveOptions() {
+ if (resolveOnly) analyzeAll = true;
+ if (analyzeSignaturesOnly || analyzeAll || resolveOnly) analyzeOnly = true;
+ if (useKernel) generateCodeWithCompileTimeErrors = false;
+ if (platformConfigUri == null) {
+ platformConfigUri = _resolvePlatformConfig(libraryRoot, null, const []);
+ }
+ librariesSpecificationUri = _resolveLibrariesSpecification(libraryRoot);
}
/// Returns `true` if warnings and hints are shown for all packages.
bool get showAllPackageWarnings {
- return _shownPackageWarnings != null && _shownPackageWarnings.isEmpty;
+ return shownPackageWarnings != null && shownPackageWarnings.isEmpty;
}
/// Returns `true` if warnings and hints are hidden for all packages.
- bool get hidePackageWarnings => _shownPackageWarnings == null;
+ bool get hidePackageWarnings => shownPackageWarnings == null;
/// Returns `true` if warnings should be should for [uri].
bool showPackageWarningsFor(Uri uri) {
if (showAllPackageWarnings) {
return true;
}
- if (_shownPackageWarnings != null) {
+ if (shownPackageWarnings != null) {
return uri.scheme == 'package' &&
- _shownPackageWarnings.contains(uri.pathSegments.first);
+ shownPackageWarnings.contains(uri.pathSegments.first);
}
return false;
}
diff --git a/pkg/compiler/lib/src/resolution/resolution_strategy.dart b/pkg/compiler/lib/src/resolution/resolution_strategy.dart
index f425600..7691c5a 100644
--- a/pkg/compiler/lib/src/resolution/resolution_strategy.dart
+++ b/pkg/compiler/lib/src/resolution/resolution_strategy.dart
@@ -37,7 +37,6 @@
import '../library_loader.dart';
import '../native/enqueue.dart' show NativeResolutionEnqueuer;
import '../native/resolver.dart';
-import '../options.dart';
import '../patch_parser.dart';
import '../resolved_uri_translator.dart';
import '../serialization/task.dart';
@@ -121,7 +120,7 @@
MirrorsDataBuilder createMirrorsDataBuilder() {
return new ResolutionMirrorsData(
- _compiler, _compiler.options, elementEnvironment, commonElements);
+ _compiler, elementEnvironment, commonElements);
}
MirrorsResolutionAnalysis createMirrorsResolutionAnalysis(
@@ -647,8 +646,8 @@
}
if (member == null && required) {
failedAt(
- member,
- "The library '${library.libraryName}' does not "
+ library,
+ "The library '${library.canonicalUri}' does not "
"contain required member: '$name'.");
}
return member?.declaration;
@@ -1038,9 +1037,9 @@
}
class ResolutionMirrorsData extends MirrorsDataImpl {
- ResolutionMirrorsData(Compiler compiler, CompilerOptions options,
+ ResolutionMirrorsData(Compiler compiler,
ElementEnvironment elementEnvironment, CommonElements commonElements)
- : super(compiler, options, elementEnvironment, commonElements);
+ : super(compiler, elementEnvironment, commonElements);
@override
bool isClassInjected(covariant ClassElement cls) => cls.isInjected;
diff --git a/pkg/compiler/lib/src/scanner/scanner_task.dart b/pkg/compiler/lib/src/scanner/scanner_task.dart
index c49621e..6e3b3e9 100644
--- a/pkg/compiler/lib/src/scanner/scanner_task.dart
+++ b/pkg/compiler/lib/src/scanner/scanner_task.dart
@@ -11,27 +11,14 @@
import '../script.dart' show Script;
import 'package:front_end/src/fasta/scanner.dart'
show Scanner, StringScanner, Token, Utf8BytesScanner;
-import 'package:front_end/src/fasta/scanner/token_constants.dart' as Tokens
- show COMMENT_TOKEN, EOF_TOKEN;
-import '../tokens/token_map.dart' show TokenMap;
import '../io/source_file.dart';
class ScannerTask extends CompilerTask {
final DietParserTask _dietParser;
- final bool _preserveComments;
- final TokenMap _commentMap;
final DiagnosticReporter reporter;
- ScannerTask(this._dietParser, this.reporter, Measurer measurer,
- {bool preserveComments: false, TokenMap commentMap})
- : _preserveComments = preserveComments,
- _commentMap = commentMap,
- super(measurer) {
- if (_preserveComments && _commentMap == null) {
- throw new ArgumentError(
- "commentMap must be provided if preserveComments is true");
- }
- }
+ ScannerTask(this._dietParser, this.reporter, Measurer measurer)
+ : super(measurer);
String get name => 'Scanner';
@@ -63,10 +50,7 @@
void scanElements(CompilationUnitElement compilationUnit) {
Script script = compilationUnit.script;
- Token tokens = scanFile(script.file, includeComments: _preserveComments);
- if (_preserveComments) {
- tokens = processAndStripComments(tokens);
- }
+ Token tokens = scanFile(script.file);
_dietParser.dietParse(compilationUnit, tokens);
}
@@ -82,26 +66,4 @@
return new StringScanner(source, includeComments: false).tokenize();
});
}
-
- Token processAndStripComments(Token currentToken) {
- Token firstToken = currentToken;
- Token prevToken;
- while (currentToken.kind != Tokens.EOF_TOKEN) {
- if (identical(currentToken.kind, Tokens.COMMENT_TOKEN)) {
- Token firstCommentToken = currentToken;
- while (identical(currentToken.kind, Tokens.COMMENT_TOKEN)) {
- currentToken = currentToken.next;
- }
- _commentMap[currentToken] = firstCommentToken;
- if (prevToken == null) {
- firstToken = currentToken;
- } else {
- prevToken.next = currentToken;
- }
- }
- prevToken = currentToken;
- currentToken = currentToken.next;
- }
- return firstToken;
- }
}
diff --git a/pkg/compiler/lib/src/source_file_provider.dart b/pkg/compiler/lib/src/source_file_provider.dart
index 9ff9a5a..15281c8 100644
--- a/pkg/compiler/lib/src/source_file_provider.dart
+++ b/pkg/compiler/lib/src/source_file_provider.dart
@@ -324,17 +324,6 @@
RandomAccessFileOutputProvider(this.out, this.sourceMapOut,
{this.onInfo, this.onFailure, this.resolutionOutput});
- static Uri computePrecompiledUri(Uri out) {
- String extension = 'precompiled.js';
- String outPath = out.path;
- if (outPath.endsWith('.js')) {
- outPath = outPath.substring(0, outPath.length - 3);
- return out.resolve('$outPath.$extension');
- } else {
- return out.resolve(extension);
- }
- }
-
Uri createUri(String name, String extension, OutputType type) {
Uri uri;
// TODO(johnniwinther): Unify handle of [name] and [extension] to prepare
diff --git a/pkg/compiler/lib/src/ssa/builder_kernel.dart b/pkg/compiler/lib/src/ssa/builder_kernel.dart
index a475ae1..44b5a21 100644
--- a/pkg/compiler/lib/src/ssa/builder_kernel.dart
+++ b/pkg/compiler/lib/src/ssa/builder_kernel.dart
@@ -900,7 +900,7 @@
/// that no corresponding ir.Node actually exists for it. We just use the
/// targetElement.
void buildMethodSignature(ir.FunctionNode originalClosureNode) {
- openFunction(targetElement, originalClosureNode);
+ openFunction(targetElement);
List<HInstruction> typeArguments = <HInstruction>[];
// Add function type variables.
@@ -1843,7 +1843,9 @@
HInstruction converted = typeBuilder.buildTypeConversion(
expressionInstruction,
localsHandler.substInContext(type),
- HTypeConversion.CAST_TYPE_CHECK,
+ node.isTypeError
+ ? HTypeConversion.CHECKED_MODE_CHECK
+ : HTypeConversion.CAST_TYPE_CHECK,
sourceInformation: sourceInformation);
if (converted != expressionInstruction) {
add(converted);
@@ -4362,14 +4364,14 @@
return;
}
- if (type is ir.DynamicType) {
+ DartType typeValue =
+ localsHandler.substInContext(_elementMap.getDartType(type));
+
+ if (typeValue.treatAsDynamic) {
stack.add(graph.addConstantBool(true, closedWorld));
return;
}
- DartType typeValue =
- localsHandler.substInContext(_elementMap.getDartType(type));
-
if (typeValue is FunctionType) {
HInstruction representation =
typeBuilder.analyzeTypeArgument(typeValue, sourceElement);
@@ -4386,6 +4388,22 @@
return;
}
+ if (typeValue is FutureOrType) {
+ HInstruction representation =
+ typeBuilder.analyzeTypeArgument(typeValue, sourceElement);
+ List<HInstruction> inputs = <HInstruction>[
+ expression,
+ representation,
+ ];
+ _pushStaticInvocation(_commonElements.futureOrTest, inputs,
+ commonMasks.boolType, const <DartType>[],
+ sourceInformation: sourceInformation);
+ HInstruction call = pop();
+ push(new HIs.compound(typeValue, expression, call, commonMasks.boolType,
+ sourceInformation));
+ return;
+ }
+
if (typeValue is TypeVariableType) {
HInstruction runtimeType =
typeBuilder.addTypeVariableReference(typeValue, sourceElement);
diff --git a/pkg/compiler/lib/src/ssa/codegen.dart b/pkg/compiler/lib/src/ssa/codegen.dart
index 8654584..fed6eaf 100644
--- a/pkg/compiler/lib/src/ssa/codegen.dart
+++ b/pkg/compiler/lib/src/ssa/codegen.dart
@@ -3062,7 +3062,10 @@
_emitter.emitter,
node.dartType,
(TypeVariableType variable) => arguments[index++]);
- assert(index == node.inputs.length);
+ assert(
+ index == node.inputs.length,
+ "Not all input is read for type ${node.dartType}: "
+ "$index of ${node.inputs}.");
push(result);
return;
diff --git a/pkg/compiler/lib/src/ssa/kernel_impact.dart b/pkg/compiler/lib/src/ssa/kernel_impact.dart
index 3498027..5e3c51f 100644
--- a/pkg/compiler/lib/src/ssa/kernel_impact.dart
+++ b/pkg/compiler/lib/src/ssa/kernel_impact.dart
@@ -55,10 +55,22 @@
CommonElements get commonElements => elementMap.commonElements;
/// Add a checked-mode type use of [type] if it is not `dynamic`.
- DartType checkType(ir.DartType irType) {
+ DartType checkType(ir.DartType irType, TypeUseKind kind) {
DartType type = elementMap.getDartType(irType);
- if (!type.isDynamic) {
- impactBuilder.registerTypeUse(new TypeUse.checkedModeCheck(type));
+ if (kind != null && !type.isDynamic) {
+ switch (kind) {
+ case TypeUseKind.CHECKED_MODE_CHECK:
+ impactBuilder.registerTypeUse(new TypeUse.checkedModeCheck(type));
+ break;
+ case TypeUseKind.PARAMETER_CHECK:
+ impactBuilder.registerTypeUse(new TypeUse.parameterCheck(type));
+ break;
+ case TypeUseKind.IMPLICIT_CAST:
+ impactBuilder.registerTypeUse(new TypeUse.implicitCast(type));
+ break;
+ default:
+ throw new UnsupportedError("Unexpected type check kind: $kind");
+ }
}
return type;
}
@@ -71,7 +83,11 @@
/// Add checked-mode type use for the parameter type and constant for the
/// default value of [parameter].
void handleParameter(ir.VariableDeclaration parameter) {
- checkType(parameter.type);
+ checkType(
+ parameter.type,
+ _options.strongMode
+ ? TypeUseKind.PARAMETER_CHECK
+ : TypeUseKind.CHECKED_MODE_CHECK);
registerSeenClasses(parameter.type);
visitNode(parameter.initializer);
}
@@ -79,8 +95,8 @@
/// Add checked-mode type use for parameter and return types, and add
/// constants for default values.
void handleSignature(ir.FunctionNode node, {bool checkReturnType: true}) {
- if (checkReturnType) {
- checkType(node.returnType);
+ if (checkReturnType && !_options.strongMode) {
+ checkType(node.returnType, TypeUseKind.CHECKED_MODE_CHECK);
}
registerSeenClasses(node.returnType);
node.positionalParameters.forEach(handleParameter);
@@ -88,7 +104,11 @@
}
ResolutionImpact buildField(ir.Field field) {
- checkType(field.type);
+ checkType(
+ field.type,
+ _options.strongMode
+ ? TypeUseKind.PARAMETER_CHECK
+ : TypeUseKind.CHECKED_MODE_CHECK);
registerSeenClasses(field.type);
if (field.initializer != null) {
visitNode(field.initializer);
@@ -223,7 +243,8 @@
@override
void visitListLiteral(ir.ListLiteral literal) {
visitNodes(literal.expressions);
- DartType elementType = checkType(literal.typeArgument);
+ DartType elementType = checkType(literal.typeArgument,
+ _options.strongMode ? null : TypeUseKind.CHECKED_MODE_CHECK);
registerSeenClasses(literal.typeArgument);
impactBuilder.registerListLiteral(new ListLiteralUse(
@@ -235,8 +256,10 @@
@override
void visitMapLiteral(ir.MapLiteral literal) {
visitNodes(literal.entries);
- DartType keyType = checkType(literal.keyType);
- DartType valueType = checkType(literal.valueType);
+ DartType keyType = checkType(literal.keyType,
+ _options.strongMode ? null : TypeUseKind.CHECKED_MODE_CHECK);
+ DartType valueType = checkType(literal.valueType,
+ _options.strongMode ? null : TypeUseKind.CHECKED_MODE_CHECK);
registerSeenClasses(literal.keyType);
registerSeenClasses(literal.valueType);
impactBuilder.registerMapLiteral(new MapLiteralUse(
@@ -571,7 +594,9 @@
@override
void visitVariableDeclaration(ir.VariableDeclaration node) {
- checkType(node.type);
+ if (!_options.strongMode) {
+ checkType(node.type, TypeUseKind.CHECKED_MODE_CHECK);
+ }
registerSeenClasses(node.type);
if (node.initializer != null) {
visitNode(node.initializer);
@@ -590,8 +615,12 @@
@override
void visitAsExpression(ir.AsExpression node) {
- impactBuilder
- .registerTypeUse(new TypeUse.asCast(elementMap.getDartType(node.type)));
+ DartType type = elementMap.getDartType(node.type);
+ if (node.isTypeError) {
+ impactBuilder.registerTypeUse(new TypeUse.implicitCast(type));
+ } else {
+ impactBuilder.registerTypeUse(new TypeUse.asCast(type));
+ }
registerSeenClasses(node.type);
visitNode(node.operand);
}
diff --git a/pkg/compiler/lib/src/ssa/nodes.dart b/pkg/compiler/lib/src/ssa/nodes.dart
index 9bdd008..e9db66c 100644
--- a/pkg/compiler/lib/src/ssa/nodes.dart
+++ b/pkg/compiler/lib/src/ssa/nodes.dart
@@ -1345,12 +1345,9 @@
if (type.isDynamic) return this;
if (type.isVoid) return this;
if (type == closedWorld.commonElements.objectType) return this;
- if (type.isFunctionType || type.isMalformed) {
+ if (type.isFunctionType || type.isMalformed || type.isFutureOr) {
return new HTypeConversion(type, kind,
closedWorld.commonMasks.dynamicType, this, sourceInformation);
- } else if (type.isFutureOr) {
- // TODO(johnniwinther): Handle conversion to FutureOr.
- return this;
}
assert(type.isInterfaceType);
if (kind == HTypeConversion.BOOLEAN_CONVERSION_CHECK) {
@@ -2995,14 +2992,19 @@
typeExpression, [expression], RAW_CHECK, type, sourceInformation,
useInstanceOf: true);
- HIs.raw(
+ factory HIs.raw(
DartType typeExpression,
HInstruction expression,
HInterceptor interceptor,
TypeMask type,
- SourceInformation sourceInformation)
- : this.internal(typeExpression, [expression, interceptor], RAW_CHECK,
- type, sourceInformation);
+ SourceInformation sourceInformation) {
+ assert(
+ (typeExpression.isFunctionType || typeExpression.isInterfaceType) &&
+ typeExpression.treatAsRaw,
+ "Unexpected raw is-test type: $typeExpression");
+ return new HIs.internal(typeExpression, [expression, interceptor],
+ RAW_CHECK, type, sourceInformation);
+ }
HIs.compound(DartType typeExpression, HInstruction expression,
HInstruction call, TypeMask type, SourceInformation sourceInformation)
@@ -3171,6 +3173,10 @@
checkedType == other.checkedType &&
receiverTypeCheckSelector == other.receiverTypeCheckSelector;
}
+
+ String toString() => 'HTypeConversion(type=$typeExpression,kind=$kind,'
+ '${hasTypeRepresentation ? 'representation=$typeRepresentation,' : ''}'
+ 'checkedInput=$checkedInput)';
}
/// The [HTypeKnown] instruction marks a value with a refined type.
diff --git a/pkg/compiler/lib/src/ssa/optimize.dart b/pkg/compiler/lib/src/ssa/optimize.dart
index b5cfb5b..6f4f726 100644
--- a/pkg/compiler/lib/src/ssa/optimize.dart
+++ b/pkg/compiler/lib/src/ssa/optimize.dart
@@ -847,6 +847,8 @@
return node;
} else if (type.isFunctionType) {
return node;
+ } else if (type.isFutureOr) {
+ return node;
}
if (type == commonElements.objectType || type.treatAsDynamic) {
@@ -921,6 +923,13 @@
if (type.isTypeVariable) {
return node;
}
+ if (type.isFutureOr) {
+ HInstruction input = node.checkedInput;
+ // `null` always passes type conversion.
+ if (input.isNull()) return input;
+ // TODO(johnniwinther): Optimize FutureOr type conversions.
+ return node;
+ }
if (!type.treatAsRaw) {
HInstruction input = node.checkedInput;
// `null` always passes type conversion.
@@ -2468,6 +2477,8 @@
return;
} else if (type.isTypedef) {
return;
+ } else if (type.isFutureOr) {
+ return;
}
InterfaceType interfaceType = type;
ClassEntity cls = interfaceType.element;
diff --git a/pkg/compiler/lib/src/ssa/type_builder.dart b/pkg/compiler/lib/src/ssa/type_builder.dart
index 5a87372..58b5b3d 100644
--- a/pkg/compiler/lib/src/ssa/type_builder.dart
+++ b/pkg/compiler/lib/src/ssa/type_builder.dart
@@ -279,10 +279,10 @@
return new HTypeConversion.withTypeRepresentation(
type, kind, subtype, original, typeVariable)
..sourceInformation = sourceInformation;
- } else if (type.isFunctionType) {
+ } else if (type.isFunctionType || type.isFutureOr) {
HInstruction reifiedType =
analyzeTypeArgument(type, builder.sourceElement);
- // TypeMasks don't encode function types.
+ // TypeMasks don't encode function types or FutureOr types.
TypeMask refinedMask = original.instructionType;
return new HTypeConversion.withTypeRepresentation(
type, kind, refinedMask, original, reifiedType)
diff --git a/pkg/compiler/lib/src/tokens/token_map.dart b/pkg/compiler/lib/src/tokens/token_map.dart
deleted file mode 100644
index 4d5da67..0000000
--- a/pkg/compiler/lib/src/tokens/token_map.dart
+++ /dev/null
@@ -1,46 +0,0 @@
-// Copyright (c) 2012, 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 dart2js.tokens.token_map;
-
-import 'package:front_end/src/fasta/scanner.dart' show Token;
-
-/**
- * Key class used in [TokenMap] in which the hash code for a token is based
- * on the [charOffset].
- */
-class TokenKey {
- final Token token;
- TokenKey(this.token);
- int get hashCode => token.charOffset;
- operator ==(other) => other is TokenKey && token == other.token;
-}
-
-/// Map of tokens and the first associated comment.
-/*
- * This implementation was chosen among several candidates for its space/time
- * efficiency by empirical tests of running dartdoc on dartdoc itself. Time
- * measurements for the use of [Compiler.commentMap]:
- *
- * 1) Using [TokenKey] as key (this class): ~80 msec
- * 2) Using [TokenKey] as key + storing a separate map in each script: ~120 msec
- * 3) Using [Token] as key in a [Map]: ~38000 msec
- * 4) Storing comments is new field in [Token]: ~20 msec
- * (Abandoned due to the increased memory usage)
- * 5) Storing comments in an [Expando]: ~14000 msec
- * 6) Storing token/comments pairs in a linked list: ~5400 msec
- */
-class TokenMap {
- Map<TokenKey, Token> comments = new Map<TokenKey, Token>();
-
- Token operator [](Token key) {
- if (key == null) return null;
- return comments[new TokenKey(key)];
- }
-
- void operator []=(Token key, Token value) {
- if (key == null) return;
- comments[new TokenKey(key)] = value;
- }
-}
diff --git a/pkg/compiler/lib/src/universe/use.dart b/pkg/compiler/lib/src/universe/use.dart
index 43958f0..9e105084 100644
--- a/pkg/compiler/lib/src/universe/use.dart
+++ b/pkg/compiler/lib/src/universe/use.dart
@@ -512,6 +512,8 @@
INSTANTIATION,
MIRROR_INSTANTIATION,
NATIVE_INSTANTIATION,
+ IMPLICIT_CAST,
+ PARAMETER_CHECK,
}
/// Use of a [DartType].
@@ -535,11 +537,29 @@
return new TypeUse.internal(type, TypeUseKind.AS_CAST);
}
- /// [type] used as a type annotation, like `T foo;`.
+ /// [type] used as a type annotation in Dart 1, like `T foo;`.
factory TypeUse.checkedModeCheck(DartType type) {
return new TypeUse.internal(type, TypeUseKind.CHECKED_MODE_CHECK);
}
+ /// [type] used as a parameter type or field type in Dart 2, like `T` in:
+ ///
+ /// method(T t) {}
+ /// T field;
+ ///
+ factory TypeUse.parameterCheck(DartType type) {
+ return new TypeUse.internal(type, TypeUseKind.PARAMETER_CHECK);
+ }
+
+ /// [type] used in an implicit cast in Dart 2, like `T` in
+ ///
+ /// dynamic foo = new Object();
+ /// T bar = foo; // Implicitly `T bar = foo as T`.
+ ///
+ factory TypeUse.implicitCast(DartType type) {
+ return new TypeUse.internal(type, TypeUseKind.IMPLICIT_CAST);
+ }
+
/// [type] used in a on type catch clause, like `try {} on T catch (e) {}`.
factory TypeUse.catchType(DartType type) {
return new TypeUse.internal(type, TypeUseKind.CATCH_TYPE);
diff --git a/pkg/compiler/testing_dart.json b/pkg/compiler/testing_dart.json
index b0fb40c3a..17a04e0 100644
--- a/pkg/compiler/testing_dart.json
+++ b/pkg/compiler/testing_dart.json
@@ -50,6 +50,14 @@
"^tests/compiler/dart2js/old_frontend/resolution_test\\.dart",
"^tests/compiler/dart2js/quarantined/http_launch_data/http_launch_main_package\\.dart",
"^tests/compiler/dart2js/quarantined/http_test\\.dart",
+ "^tests/compiler/dart2js/rti/data/future_or_future_or_generic_strong\\.dart",
+ "^tests/compiler/dart2js/rti/data/future_or_future_or_strong\\.dart",
+ "^tests/compiler/dart2js/rti/data/future_or_generic2_strong\\.dart",
+ "^tests/compiler/dart2js/rti/data/future_or_generic_strong\\.dart",
+ "^tests/compiler/dart2js/rti/data/future_or_strong\\.dart",
+ "^tests/compiler/dart2js/rti/emission/future_or_future_or_generic_strong\\.dart",
+ "^tests/compiler/dart2js/rti/emission/future_or_future_or_strong\\.dart",
+ "^tests/compiler/dart2js/rti/emission/future_or_generic2_strong\\.dart",
"^tests/compiler/dart2js/serialization/analysis_test_helper\\.dart",
"^tests/compiler/dart2js/serialization/compilation_test_helper\\.dart",
"^tests/compiler/dart2js/serialization/duplicate_library_test\\.dart",
diff --git a/pkg/dev_compiler/lib/src/analyzer/code_generator.dart b/pkg/dev_compiler/lib/src/analyzer/code_generator.dart
index 43580d4..0a871b8 100644
--- a/pkg/dev_compiler/lib/src/analyzer/code_generator.dart
+++ b/pkg/dev_compiler/lib/src/analyzer/code_generator.dart
@@ -2874,15 +2874,16 @@
JS.Block _emitFunctionScopedBody(
FunctionBody body, ExecutableElement element) {
var block = body.accept(this) as JS.Block;
- if (!body.isAsynchronous && !body.isGenerator) {
+ if (element.parameters.isNotEmpty) {
// Handle shadowing of parameters by local varaibles, which is allowed in
// Dart but not in JS.
//
- // We only handle this for normal (sync) functions. Generator-based
- // functions (sync*, async, and async*) have their bodies placed
- // in an inner function scope that is a separate scope from the
- // parameters, so they avoid this problem.
- var parameterNames = element.parameters.map((e) => e.name).toSet();
+ // We need this for all function types, including generator-based ones
+ // (sync*/async/async*). Our code generator assumes it can emit names for
+ // named argument initialization, and sync* functions also emit locally
+ // modified parameters into the function's scope.
+ var parameterNames =
+ new HashSet<String>.from(element.parameters.map((e) => e.name));
return block.toScopedBlock(parameterNames);
}
return block;
diff --git a/pkg/dev_compiler/lib/src/kernel/compiler.dart b/pkg/dev_compiler/lib/src/kernel/compiler.dart
index 143c646..a5f1b25 100644
--- a/pkg/dev_compiler/lib/src/kernel/compiler.dart
+++ b/pkg/dev_compiler/lib/src/kernel/compiler.dart
@@ -1215,9 +1215,11 @@
}
}
- for (var member in c.procedures) {
- if (member.isAbstract) continue;
-
+ var classProcedures = c.procedures.where((p) => !p.isAbstract).toList();
+ for (var m in _classProperties.mockMembers.values) {
+ if (m is Procedure) classProcedures.add(m);
+ }
+ for (var member in classProcedures) {
// Static getters/setters cannot be called with dynamic dispatch, nor
// can they be torn off.
// TODO(jmesserly): can we attach static method type info at the tearoff
@@ -1228,7 +1230,7 @@
}
var name = member.name.name;
- var reifiedType = _getMemberRuntimeType(member);
+ var reifiedType = _getMemberRuntimeType(member, c);
// Don't add redundant signatures for inherited methods whose signature
// did not change. If we are not overriding, or if the thing we are
@@ -1241,15 +1243,10 @@
: null;
var needsSignature = memberOverride == null ||
- reifiedType !=
- Substitution
- .fromSupertype(hierarchy.getClassAsInstanceOf(
- c, memberOverride.enclosingClass))
- .substituteType(_getMemberRuntimeType(memberOverride));
+ reifiedType != _getMemberRuntimeType(memberOverride, c);
if (needsSignature) {
- var type = _emitAnnotatedFunctionType(reifiedType, member.annotations,
- function: member.function);
+ var type = _emitAnnotatedFunctionType(reifiedType, member);
var property = new JS.Property(_declareMemberName(member), type);
var signatures = getSignatureList(member);
signatures.add(property);
@@ -1269,14 +1266,18 @@
var instanceFields = <JS.Property>[];
var staticFields = <JS.Property>[];
- for (var field in c.fields) {
+
+ var classFields = c.fields.toList();
+ for (var m in _classProperties.mockMembers.values) {
+ if (m is Field) classFields.add(m);
+ }
+ for (var field in classFields) {
// Only instance fields need to be saved for dynamic dispatch.
var isStatic = field.isStatic;
if (!emitMetadata && isStatic) continue;
var memberName = _declareMemberName(field);
- var fieldSig = _emitFieldSignature(field.type,
- metadata: field.annotations, isFinal: field.isFinal);
+ var fieldSig = _emitFieldSignature(field, c);
(isStatic ? staticFields : instanceFields)
.add(new JS.Property(memberName, fieldSig));
}
@@ -1288,8 +1289,7 @@
for (var ctor in c.constructors) {
var memberName = _constructorName(ctor.name.name);
var type = _emitAnnotatedFunctionType(
- ctor.function.functionType.withoutTypeParameters, ctor.annotations,
- function: ctor.function, nameType: false, definite: true);
+ ctor.function.functionType.withoutTypeParameters, ctor);
constructors.add(new JS.Property(memberName, type));
}
}
@@ -1303,41 +1303,54 @@
}
}
- JS.Expression _emitFieldSignature(DartType type,
- {List<Expression> metadata, bool isFinal: true}) {
+ JS.Expression _emitFieldSignature(Field field, Class fromClass) {
+ var type = _getTypeFromClass(field.type, field.enclosingClass, fromClass);
var args = [_emitType(type)];
- if (emitMetadata && metadata != null && metadata.isNotEmpty) {
+ var annotations = field.annotations;
+ if (emitMetadata && annotations != null && annotations.isNotEmpty) {
+ var savedUri = _currentUri;
+ _currentUri = field.enclosingClass.fileUri;
args.add(new JS.ArrayInitializer(
- metadata.map(_instantiateAnnotation).toList()));
+ annotations.map(_instantiateAnnotation).toList()));
+ _currentUri = savedUri;
}
- return _callHelper(isFinal ? 'finalFieldType(#)' : 'fieldType(#)', [args]);
+ return _callHelper(
+ field.isFinal ? 'finalFieldType(#)' : 'fieldType(#)', [args]);
}
- FunctionType _getMemberRuntimeType(Member member) {
+ FunctionType _getMemberRuntimeType(Member member, Class fromClass) {
var f = member.function;
if (f == null) {
- assert(member is Field);
- return new FunctionType([], member.getterType);
+ return (member as Field).type;
}
-
+ FunctionType result;
if (!f.positionalParameters.any(isCovariant) &&
!f.namedParameters.any(isCovariant)) {
- return f.functionType;
+ result = f.functionType;
+ } else {
+ reifyParameter(VariableDeclaration p) =>
+ isCovariant(p) ? coreTypes.objectClass.thisType : p.type;
+ reifyNamedParameter(VariableDeclaration p) =>
+ new NamedType(p.name, reifyParameter(p));
+
+ // TODO(jmesserly): do covariant type parameter bounds also need to be
+ // reified as `Object`?
+ result = new FunctionType(
+ f.positionalParameters.map(reifyParameter).toList(), f.returnType,
+ namedParameters: f.namedParameters.map(reifyNamedParameter).toList()
+ ..sort(),
+ typeParameters: f.functionType.typeParameters,
+ requiredParameterCount: f.requiredParameterCount);
}
+ return _getTypeFromClass(result, member.enclosingClass, fromClass)
+ as FunctionType;
+ }
- reifyParameter(VariableDeclaration p) =>
- isCovariant(p) ? coreTypes.objectClass.thisType : p.type;
- reifyNamedParameter(VariableDeclaration p) =>
- new NamedType(p.name, reifyParameter(p));
-
- // TODO(jmesserly): do covariant type parameter bounds also need to be
- // reified as `Object`?
- return new FunctionType(
- f.positionalParameters.map(reifyParameter).toList(), f.returnType,
- namedParameters: f.namedParameters.map(reifyNamedParameter).toList()
- ..sort(),
- typeParameters: f.functionType.typeParameters,
- requiredParameterCount: f.requiredParameterCount);
+ DartType _getTypeFromClass(DartType type, Class superclass, Class subclass) {
+ if (identical(superclass, subclass)) return type;
+ return Substitution
+ .fromSupertype(hierarchy.getClassAsInstanceOf(subclass, superclass))
+ .substituteType(type);
}
JS.Expression _emitConstructor(Constructor node, List<Field> fields,
@@ -1704,8 +1717,9 @@
if (superMember == null) return [];
- var superSubstition = Substitution.fromSupertype(hierarchy
- .getClassAsInstanceOf(enclosingClass, superMember.enclosingClass));
+ substituteType(DartType t) {
+ return _getTypeFromClass(t, superMember.enclosingClass, enclosingClass);
+ }
var name = _declareMemberName(member);
if (member.isSetter) {
@@ -1717,10 +1731,8 @@
return [
new JS.Method(
name,
- js.fun('function(x) { return super.# = #._check(x); }', [
- name,
- _emitType(superSubstition.substituteType(superMember.setterType))
- ]),
+ js.fun('function(x) { return super.# = #._check(x); }',
+ [name, _emitType(substituteType(superMember.setterType))]),
isSetter: true),
new JS.Method(name, js.fun('function() { return super.#; }', [name]),
isGetter: true)
@@ -1728,8 +1740,8 @@
}
assert(!member.isAccessor);
- var superMethodType = superSubstition
- .substituteType(superMember.function.functionType) as FunctionType;
+ var superMethodType =
+ substituteType(superMember.function.functionType) as FunctionType;
var function = member.function;
var body = <JS.Statement>[];
@@ -1881,6 +1893,7 @@
new JS.ObjectInitializer(invocationProps)
]);
+ returnType = _getTypeFromClass(returnType, member.enclosingClass, c);
if (!types.isTop(returnType)) {
fnBody = js.call('#._check(#)', [_emitType(returnType), fnBody]);
}
@@ -1898,32 +1911,17 @@
}
if (member is Field) {
- jsMethods.add(implementMockMember(
- const <TypeParameter>[],
- const <VariableDeclaration>[],
- ProcedureKind.Getter,
- Substitution
- .fromSupertype(
- hierarchy.getClassAsInstanceOf(c, member.enclosingClass))
- .substituteType(member.type)));
+ jsMethods
+ .add(implementMockMember([], [], ProcedureKind.Getter, member.type));
if (!member.isFinal) {
jsMethods.add(implementMockMember(
- const <TypeParameter>[],
- const <VariableDeclaration>[],
- ProcedureKind.Setter,
- new DynamicType()));
+ [], [], ProcedureKind.Setter, new DynamicType()));
}
} else {
- Procedure procedure = member as Procedure;
- FunctionNode function = procedure.function;
+ var procedure = member as Procedure;
+ var f = procedure.function;
jsMethods.add(implementMockMember(
- function.typeParameters,
- function.namedParameters,
- procedure.kind,
- Substitution
- .fromSupertype(
- hierarchy.getClassAsInstanceOf(c, member.enclosingClass))
- .substituteType(function.returnType)));
+ f.typeParameters, f.namedParameters, procedure.kind, f.returnType));
}
}
@@ -2680,11 +2678,19 @@
return _nameType(type, _callHelper(helperCall, [typeParts]));
}
- JS.Expression _emitAnnotatedFunctionType(
- FunctionType type, List<Expression> metadata,
- {FunctionNode function, bool nameType: true, bool definite: false}) {
- var result = visitFunctionType(type, function: function);
- return _emitAnnotatedResult(result, metadata);
+ JS.Expression _emitAnnotatedFunctionType(FunctionType type, Member member) {
+ var result = visitFunctionType(type, function: member.function);
+
+ var annotations = member.annotations;
+ if (emitMetadata && annotations != null && annotations.isNotEmpty) {
+ // TODO(jmesserly): should we disable source info for annotations?
+ var savedUri = _currentUri;
+ _currentUri = member.enclosingClass.fileUri;
+ result = new JS.ArrayInitializer(
+ [result]..addAll(annotations.map(_instantiateAnnotation)));
+ _currentUri = savedUri;
+ }
+ return result;
}
/// Emits an expression that lets you access statics on a [type] from code.
@@ -3093,14 +3099,14 @@
JS.Statement _emitFunctionScopedBody(FunctionNode f) {
var jsBody = _visitStatement(f.body);
- if (f.asyncMarker == AsyncMarker.Sync) {
+ if (f.positionalParameters.isNotEmpty || f.namedParameters.isNotEmpty) {
// Handle shadowing of parameters by local varaibles, which is allowed in
// Dart but not in JS.
//
- // We only handle this for normal (sync) functions. Generator-based
- // functions (sync*, async, and async*) have their bodies placed
- // in an inner function scope that is a separate scope from the
- // parameters, so they avoid this problem.
+ // We need this for all function types, including generator-based ones
+ // (sync*/async/async*). Our code generator assumes it can emit names for
+ // named argument initialization, and sync* functions also emit locally
+ // modified parameters into the function's scope.
var parameterNames = new HashSet<String>()
..addAll(f.positionalParameters.map((p) => p.name))
..addAll(f.namedParameters.map((p) => p.name));
diff --git a/pkg/front_end/lib/src/api_prototype/incremental_kernel_generator.dart b/pkg/front_end/lib/src/api_prototype/incremental_kernel_generator.dart
index c60a782..460e203 100644
--- a/pkg/front_end/lib/src/api_prototype/incremental_kernel_generator.dart
+++ b/pkg/front_end/lib/src/api_prototype/incremental_kernel_generator.dart
@@ -22,9 +22,8 @@
bootstrapDill);
}
- /// Returns a component whose libraries are the recompiled libraries,
- /// or - in the case of [fullComponent] - a full Component.
- Future<Component> computeDelta({Uri entryPoint, bool fullComponent});
+ /// Returns a component whose libraries are the recompiled libraries.
+ Future<Component> computeDelta({Uri entryPoint});
/// Remove the file associated with the given file [uri] from the set of
/// valid files. This guarantees that those files will be re-read on the
diff --git a/pkg/front_end/lib/src/base/libraries_specification.dart b/pkg/front_end/lib/src/base/libraries_specification.dart
index 28c95fe..addde5e 100644
--- a/pkg/front_end/lib/src/base/libraries_specification.dart
+++ b/pkg/front_end/lib/src/base/libraries_specification.dart
@@ -32,11 +32,9 @@
/// }
/// "mirrors": {
/// "uri": "mirrors/mirrors.dart",
+/// "supported": false
/// }
/// }
-/// "environment_overrides": {
-/// "mirrors": false
-/// }
/// }
/// }
///
@@ -44,8 +42,8 @@
/// - a top level entry for each target. Keys are target names (e.g. "vm"
/// above), and values contain the entire specification of a target.
///
-/// - each target specification is a map. Today two keys are supported:
-/// "libraries" and "environment_overrides".
+/// - each target specification is a map. Today, only one key is supported on
+/// this map: "libraries".
///
/// - The "libraries" entry contains details for how each platform library is
/// implemented. The entry is a map, where keys are the name of the platform
@@ -63,20 +61,21 @@
/// which will be resolved relative to the location of the library
/// specification file.
///
-/// - The "environment_overrides" entry contains rules to override the value
-/// of environment variables that are derived from the platform libraries.
+/// - The "supported" entry on the library information is optional. The value
+/// is a boolean indicating whether the library is supported in the
+/// underlying target. However, since the libraries are assumed to be
+/// supported by default, we only expect users to use `false`.
///
-/// By default every platform library that is available in the "libraries"
-/// section implicitly defines an environment variable `dart.library.name`
-/// as `"true"`, to indicate that the library is supported. Some backends
-/// override this to allow imports to a platform library, but still report
-/// that the library is not supported in conditional imports and const
-/// `fromEnvironment` expressions.
+/// The purpose of this value is to configure conditional imports and
+/// environment constants. By default every platform library that is
+/// available in the "libraries" section implicitly defines an environment
+/// variable `dart.library.name` as `"true"`, to indicate that the library
+/// is supported. Some backends allow imports to an unsupported platform
+/// library (turning a static error into a runtime error when the library is
+/// eventually accessed). These backends can use `supported: false` to
+/// report that such library is still not supported in conditional imports
+/// and const `fromEnvironment` expressions.
///
-/// A name key listed in the "environment_overrides" section must match the
-/// name of a library in the "libraries" section. The value is a bool,
-/// however, since the libraries are assumed to be supported by default, we
-/// only expect users to use `false`.
///
/// Note: we currently have several different files that need to be updated
/// when changing libraries, sources, and patch files:
@@ -88,9 +87,6 @@
/// https://github.com/dart-lang/sdk/issues/28836), but for now we need to pay
/// close attention to change them consistently.
-// TODO(sigmund): consider moving the overrides directly into the libraries
-// section (e.g. add a "supported: false" entry).
-
// TODO(sigmund): move this file to a shared package.
import 'dart:convert' show JSON;
@@ -112,7 +108,7 @@
var targetSpec = _targets[target];
if (targetSpec == null) {
throw new LibrariesSpecificationException(
- 'No library specification for target "$target"');
+ 'No library specification for target "$target"');
}
return targetSpec;
}
@@ -179,30 +175,17 @@
return _reportError(
"patches entry for '$name' is not a list or a string");
}
- libraries[name] = new LibraryInfo(name, uri, patches);
- });
- Map<String, bool> environmentOverrides = <String, bool>{};
- if (targetData.containsKey("environment_overrides")) {
- var overridesData = targetData["environment_overrides"];
- if (overridesData is! Map) {
- return _reportError(
- "environment_overrides entry for '$targetName' is not a map");
+
+ var supported = data['supported'] ?? true;
+ if (supported is! bool) {
+ return _reportError("\"supported\" entry: expected a 'bool' but "
+ "got a '${supported.runtimeType}' ('$supported')");
}
- overridesData.forEach((String name, value) {
- if (!libraries.containsKey(name)) {
- return _reportError(
- "entry '$name' does not correspond to an existing library "
- "in '$targetName'");
- }
- if (value is bool) {
- environmentOverrides[name] = value;
- } else {
- return _reportError("entry '$name' is not a bool");
- }
- });
- }
- targets[targetName] = new TargetLibrariesSpecification(
- targetName, libraries, environmentOverrides);
+ libraries[name] =
+ new LibraryInfo(name, uri, patches, isSupported: supported);
+ });
+ targets[targetName] =
+ new TargetLibrariesSpecification(targetName, libraries);
});
return new LibrariesSpecification(targets);
}
@@ -226,12 +209,11 @@
'uri': pathFor(lib.uri),
'patches': lib.patches.map(pathFor).toList(),
};
+ if (!lib.isSupported) {
+ libraries[name]['supported'] = false;
+ }
});
result[targetName] = {'libraries': libraries};
- if (target._environmentOverrides.isNotEmpty) {
- result[targetName]['environment_overrides'] =
- target._environmentOverrides;
- }
});
return result;
}
@@ -244,21 +226,11 @@
final Map<String, LibraryInfo> _libraries;
- final Map<String, bool> _environmentOverrides;
-
const TargetLibrariesSpecification(this.targetName,
- [this._libraries = const <String, LibraryInfo>{},
- this._environmentOverrides = const <String, bool>{}]);
+ [this._libraries = const <String, LibraryInfo>{}]);
/// Details about a library whose import is `dart:$name`.
LibraryInfo libraryInfoFor(String name) => _libraries[name];
-
- /// Environment override for a library whose import is `dart:$name`. The value
- /// can be "true", "false", or null if no override was given.
- String environmentOverrideFor(String name) {
- var override = _environmentOverrides[name];
- return override == null ? null : "$override";
- }
}
/// Information about a `dart:` library in a specific target platform.
@@ -273,7 +245,12 @@
/// Patch files used for this library in the target platform, if any.
final List<Uri> patches;
- const LibraryInfo(this.name, this.uri, this.patches);
+ /// Whether the library is supported and thus `dart.library.name` is "true"
+ /// for conditional imports and fromEnvironment constants.
+ final bool isSupported;
+
+ const LibraryInfo(this.name, this.uri, this.patches,
+ {this.isSupported: true});
}
class LibrariesSpecificationException {
diff --git a/pkg/front_end/lib/src/fasta/builder_graph.dart b/pkg/front_end/lib/src/fasta/builder_graph.dart
index b4350b1..b78d5f9 100644
--- a/pkg/front_end/lib/src/fasta/builder_graph.dart
+++ b/pkg/front_end/lib/src/fasta/builder_graph.dart
@@ -4,8 +4,6 @@
library fasta.builder_graph;
-import 'package:kernel/kernel.dart' show LibraryDependency, LibraryPart;
-
import 'package:kernel/util/graph.dart' show Graph;
import 'builder/builder.dart' show LibraryBuilder;
@@ -51,15 +49,22 @@
}
} else if (library is DillLibraryBuilder) {
// Imports and exports
- for (LibraryDependency dependency in library.library.dependencies) {
- Uri uri = dependency.targetLibrary.importUri;
+ for (var dependency in library.library.dependencies) {
+ var uriString;
+ if (dependency.importedLibraryReference.node != null) {
+ uriString = '${dependency.targetLibrary.importUri}';
+ } else {
+ uriString =
+ '${dependency.importedLibraryReference.canonicalName.name}';
+ }
+ Uri uri = Uri.parse(uriString);
if (builders.containsKey(uri)) {
yield uri;
}
}
// Parts
- for (LibraryPart part in library.library.parts) {
+ for (var part in library.library.parts) {
Uri uri = part.fileUri;
if (builders.containsKey(uri)) {
yield uri;
diff --git a/pkg/front_end/lib/src/fasta/compiler_context.dart b/pkg/front_end/lib/src/fasta/compiler_context.dart
index 54d8af3..77ab869 100644
--- a/pkg/front_end/lib/src/fasta/compiler_context.dart
+++ b/pkg/front_end/lib/src/fasta/compiler_context.dart
@@ -125,8 +125,7 @@
return current.enableColorsCached ??= computeEnableColors(current);
}
- void clear() {
+ static void clear() {
StringToken.canonicalizer.clear();
- errors.clear();
}
}
diff --git a/pkg/front_end/lib/src/fasta/incremental_compiler.dart b/pkg/front_end/lib/src/fasta/incremental_compiler.dart
index 3d7d04b..4d1dc68 100644
--- a/pkg/front_end/lib/src/fasta/incremental_compiler.dart
+++ b/pkg/front_end/lib/src/fasta/incremental_compiler.dart
@@ -26,8 +26,7 @@
import 'dill/dill_target.dart' show DillTarget;
-import 'kernel/kernel_incremental_target.dart'
- show KernelIncrementalTarget, KernelIncrementalTargetErroneousComponent;
+import 'kernel/kernel_target.dart' show KernelTarget;
import 'library_graph.dart' show LibraryGraph;
@@ -50,14 +49,13 @@
final Uri initializeFromDillUri;
bool initializedFromDill = false;
- KernelIncrementalTarget userCode;
+ KernelTarget userCode;
IncrementalCompiler(this.context, [this.initializeFromDillUri])
: ticker = context.options.ticker;
@override
- Future<Component> computeDelta(
- {Uri entryPoint, bool fullComponent: false}) async {
+ Future<Component> computeDelta({Uri entryPoint}) async {
ticker.reset();
entryPoint ??= context.options.inputs.single;
return context.runInContext<Future<Component>>((CompilerContext c) async {
@@ -120,13 +118,11 @@
ticker.logMs("Decided to reuse ${reusedLibraries.length}"
" of ${userCode.loader.builders.length} libraries");
}
- reusedLibraries.addAll(platformBuilders);
- KernelIncrementalTarget userCodeOld = userCode;
- userCode = new KernelIncrementalTarget(
+ reusedLibraries.addAll(platformBuilders);
+ userCode = new KernelTarget(
c.fileSystem, false, dillLoadedData, dillLoadedData.uriTranslator,
uriToSource: c.uriToSource);
-
for (LibraryBuilder library in reusedLibraries) {
userCode.loader.builders[library.uri] = library;
if (library.uri.scheme == "dart" && library.uri.path == "core") {
@@ -134,30 +130,14 @@
}
}
- Component componentWithDill;
- try {
- userCode.read(entryPoint);
- await userCode.buildOutlines();
+ userCode.read(entryPoint);
- // This is not the full component. It is the component including all
- // libraries loaded from .dill files.
- componentWithDill =
- await userCode.buildComponent(verify: c.options.verify);
- } on KernelIncrementalTargetErroneousComponent {
- List<Library> librariesWithSdk = userCode.component.libraries;
- List<Library> libraries = <Library>[];
- for (Library lib in librariesWithSdk) {
- if (lib.fileUri.scheme == "dart") continue;
- libraries.add(lib);
- break;
- }
- userCode.loader.builders.clear();
- userCode = userCodeOld;
- return new Component(
- libraries: libraries, uriToSource: data.uriToSource);
- }
- userCodeOld?.loader?.builders?.clear();
- userCodeOld = null;
+ await userCode.buildOutlines();
+
+ // This is not the full component. It is the component including all
+ // libraries loaded from .dill files.
+ Component componentWithDill =
+ await userCode.buildComponent(verify: c.options.verify);
List<Library> libraries =
new List<Library>.from(userCode.loader.libraries);
@@ -165,20 +145,17 @@
Procedure mainMethod = componentWithDill == null
? data.userLoadedUriMain
: componentWithDill.mainMethod;
- if (data.includeUserLoadedLibraries || fullComponent) {
- addReusedLibraries(libraries, mainMethod, reusedLibraries, data);
+ if (data.includeUserLoadedLibraries) {
+ addUserLoadedLibraries(libraries, mainMethod, reusedLibraries, data);
}
- // Clean up.
- userCode.loader.releaseAncillaryResources();
-
// This is the incremental component.
return new Component(libraries: libraries, uriToSource: data.uriToSource)
..mainMethod = mainMethod;
});
}
- void addReusedLibraries(List<Library> libraries, Procedure mainMethod,
+ void addUserLoadedLibraries(List<Library> libraries, Procedure mainMethod,
List<LibraryBuilder> reusedLibraries, IncrementalCompilerData data) {
Map<Uri, Library> libraryMap = <Uri, Library>{};
for (Library library in libraries) {
@@ -187,31 +164,29 @@
List<Uri> worklist = new List<Uri>.from(libraryMap.keys);
worklist.add(mainMethod?.enclosingLibrary?.fileUri);
- Map<Uri, Library> potentiallyReferencedLibraries = <Uri, Library>{};
+ Map<Uri, Library> potentialLibraries = <Uri, Library>{};
for (LibraryBuilder library in reusedLibraries) {
if (library.fileUri.scheme == "dart") continue;
- Library lib = library.target;
- potentiallyReferencedLibraries[library.fileUri] = lib;
+ assert(library is DillLibraryBuilder);
+ Library lib = (library as DillLibraryBuilder).library;
+ potentialLibraries[library.fileUri] = lib;
libraryMap[library.fileUri] = lib;
}
LibraryGraph graph = new LibraryGraph(libraryMap);
- while (worklist.isNotEmpty && potentiallyReferencedLibraries.isNotEmpty) {
+ while (worklist.isNotEmpty) {
Uri uri = worklist.removeLast();
if (libraryMap.containsKey(uri)) {
for (Uri neighbor in graph.neighborsOf(uri)) {
worklist.add(neighbor);
}
libraryMap.remove(uri);
- Library library = potentiallyReferencedLibraries.remove(uri);
+ Library library = potentialLibraries[uri];
if (library != null) {
libraries.add(library);
}
}
}
- for (Uri uri in potentiallyReferencedLibraries.keys) {
- userCode.loader.builders.remove(uri);
- }
// For now ensure original order of libraries to produce bit-perfect
// output.
diff --git a/pkg/front_end/lib/src/fasta/kernel/kernel_class_builder.dart b/pkg/front_end/lib/src/fasta/kernel/kernel_class_builder.dart
index 5ead269..9d4fa71 100644
--- a/pkg/front_end/lib/src/fasta/kernel/kernel_class_builder.dart
+++ b/pkg/front_end/lib/src/fasta/kernel/kernel_class_builder.dart
@@ -320,6 +320,7 @@
}
Set<Name> existingForwardersNames = new Set<Name>();
+ Set<Name> existingSetterForwardersNames = new Set<Name>();
if (cls.superclass != null &&
hasUserDefinedNoSuchMethod(cls.superclass, hierarchy)) {
List<Member> concrete = hierarchy.getDispatchTargets(cls.superclass);
@@ -328,6 +329,16 @@
existingForwardersNames.add(member.name);
}
}
+
+ List<Member> concreteSetters =
+ hierarchy.getDispatchTargets(cls.superclass, setters: true);
+ for (Member member
+ in hierarchy.getInterfaceMembers(cls.superclass, setters: true)) {
+ if (ClassHierarchy.findMemberByName(concreteSetters, member.name) ==
+ null) {
+ existingSetterForwardersNames.add(member.name);
+ }
+ }
}
if (cls.mixedInClass != null &&
hasUserDefinedNoSuchMethod(cls.mixedInClass, hierarchy)) {
@@ -337,12 +348,22 @@
existingForwardersNames.add(member.name);
}
}
+
+ List<Member> concreteSetters =
+ hierarchy.getDispatchTargets(cls.superclass, setters: true);
+ for (Member member
+ in hierarchy.getInterfaceMembers(cls.superclass, setters: true)) {
+ if (ClassHierarchy.findMemberByName(concreteSetters, member.name) ==
+ null) {
+ existingSetterForwardersNames.add(member.name);
+ }
+ }
}
List<Member> concrete = hierarchy.getDispatchTargets(cls);
List<Member> declared = hierarchy.getDeclaredMembers(cls);
for (Member member in hierarchy.getInterfaceMembers(cls)) {
- if ((member is Procedure) &&
+ if (member is Procedure &&
ClassHierarchy.findMemberByName(concrete, member.name) == null &&
!existingForwardersNames.contains(member.name)) {
if (ClassHierarchy.findMemberByName(declared, member.name) != null) {
@@ -353,6 +374,25 @@
existingForwardersNames.add(member.name);
}
}
+
+ List<Member> concreteSetters =
+ hierarchy.getDispatchTargets(cls, setters: true);
+ List<Member> declaredSetters =
+ hierarchy.getDeclaredMembers(cls, setters: true);
+ for (Member member in hierarchy.getInterfaceMembers(cls, setters: true)) {
+ if (member is Procedure &&
+ ClassHierarchy.findMemberByName(concreteSetters, member.name) ==
+ null &&
+ !existingSetterForwardersNames.contains(member.name)) {
+ if (ClassHierarchy.findMemberByName(declaredSetters, member.name) !=
+ null) {
+ member.isNoSuchMethodForwarder = true;
+ } else {
+ addNoSuchMethodForwarderForProcedure(member, hierarchy);
+ }
+ existingSetterForwardersNames.add(member.name);
+ }
+ }
}
Uri _getMemberUri(Member member) {
diff --git a/pkg/front_end/lib/src/fasta/kernel/kernel_incremental_target.dart b/pkg/front_end/lib/src/fasta/kernel/kernel_incremental_target.dart
deleted file mode 100644
index d83c9ae..0000000
--- a/pkg/front_end/lib/src/fasta/kernel/kernel_incremental_target.dart
+++ /dev/null
@@ -1,35 +0,0 @@
-// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-library fasta.kernel_incremental_target;
-
-import 'package:kernel/ast.dart' show Component, Source;
-
-import '../../api_prototype/file_system.dart' show FileSystem;
-
-import '../dill/dill_target.dart' show DillTarget;
-
-import '../uri_translator.dart' show UriTranslator;
-
-import 'kernel_target.dart' show KernelTarget;
-
-class KernelIncrementalTarget extends KernelTarget {
- Component component;
-
- KernelIncrementalTarget(FileSystem fileSystem, bool includeComments,
- DillTarget dillTarget, UriTranslator uriTranslator,
- {Map<Uri, Source> uriToSource})
- : super(fileSystem, includeComments, dillTarget, uriTranslator,
- uriToSource: uriToSource);
-
- @override
- Component erroneousComponent(bool isFullComponent) {
- component = super.erroneousComponent(isFullComponent);
- throw const KernelIncrementalTargetErroneousComponent();
- }
-}
-
-class KernelIncrementalTargetErroneousComponent {
- const KernelIncrementalTargetErroneousComponent();
-}
diff --git a/pkg/front_end/lib/src/fasta/kernel/kernel_target.dart b/pkg/front_end/lib/src/fasta/kernel/kernel_target.dart
index 778e898..1eff9b7 100644
--- a/pkg/front_end/lib/src/fasta/kernel/kernel_target.dart
+++ b/pkg/front_end/lib/src/fasta/kernel/kernel_target.dart
@@ -242,9 +242,7 @@
objectType.bind(loader.coreLibrary["Object"]);
bottomType.bind(loader.coreLibrary["Null"]);
loader.resolveTypes();
- if (loader.target.strongMode) {
- loader.instantiateToBound(dynamicType, bottomType, objectClassBuilder);
- }
+ loader.instantiateToBound(dynamicType, bottomType, objectClassBuilder);
List<SourceClassBuilder> myClasses = collectMyClasses();
loader.checkSemantics(myClasses);
loader.finishTypeVariables(objectClassBuilder);
@@ -264,9 +262,7 @@
loader.performTopLevelInference(myClasses);
}
loader.checkOverrides(myClasses);
- if (backendTarget.enableNoSuchMethodForwarders) {
- loader.addNoSuchMethodForwarders(myClasses);
- }
+ loader.addNoSuchMethodForwarders(myClasses);
} on deprecated_InputError catch (e) {
ticker.logMs("Got deprecated_InputError");
handleInputError(e, isFullComponent: false);
diff --git a/pkg/front_end/lib/src/fasta/library_graph.dart b/pkg/front_end/lib/src/fasta/library_graph.dart
index 0d7ab6f..6036c6f 100644
--- a/pkg/front_end/lib/src/fasta/library_graph.dart
+++ b/pkg/front_end/lib/src/fasta/library_graph.dart
@@ -4,7 +4,8 @@
library fasta.library_graph;
-import 'package:kernel/kernel.dart' show Library, LibraryDependency;
+import 'package:kernel/kernel.dart'
+ show Library, LibraryDependency, LibraryPart;
import 'package:kernel/util/graph.dart' show Graph;
@@ -20,17 +21,25 @@
if (library == null) {
throw "Library not found: $vertex";
}
-
// Imports and exports
for (LibraryDependency dependency in library.dependencies) {
- Uri uri1 = dependency.targetLibrary.importUri;
- Uri uri2 = dependency.targetLibrary.fileUri;
- if (libraries.containsKey(uri1)) {
- yield uri1;
- } else if (uri2 != null) {
- if (libraries.containsKey(uri2)) {
- yield uri2;
- }
+ String uriString;
+ if (dependency.importedLibraryReference.node != null) {
+ uriString = '${dependency.targetLibrary.importUri}';
+ } else {
+ uriString = '${dependency.importedLibraryReference.canonicalName.name}';
+ }
+ Uri uri = Uri.parse(uriString);
+ if (libraries.containsKey(uri)) {
+ yield uri;
+ }
+ }
+
+ // Parts
+ for (LibraryPart part in library.parts) {
+ Uri uri = part.fileUri;
+ if (libraries.containsKey(uri)) {
+ yield uri;
}
}
}
diff --git a/pkg/front_end/lib/src/fasta/parser/identifier_context_impl.dart b/pkg/front_end/lib/src/fasta/parser/identifier_context_impl.dart
index 54aeabe..3b096fb 100644
--- a/pkg/front_end/lib/src/fasta/parser/identifier_context_impl.dart
+++ b/pkg/front_end/lib/src/fasta/parser/identifier_context_impl.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 '../../scanner/token.dart' show SyntheticStringToken, Token, TokenType;
+import '../../scanner/token.dart' show Token;
import '../fasta_codes.dart' as fasta;
@@ -12,6 +12,8 @@
import 'parser.dart' show Parser;
+import 'type_info.dart' show insertSyntheticIdentifierAfter;
+
import 'util.dart' show optional;
/// See [IdentifierContext].libraryName
@@ -64,10 +66,3 @@
optional('var', token) ||
optional('void', token);
}
-
-Token insertSyntheticIdentifierAfter(Token token, Parser parser) {
- Token identifier =
- new SyntheticStringToken(TokenType.IDENTIFIER, '', token.charOffset, 0);
- parser.rewriter.insertTokenAfter(token, identifier);
- return identifier;
-}
diff --git a/pkg/front_end/lib/src/fasta/parser/parser.dart b/pkg/front_end/lib/src/fasta/parser/parser.dart
index 2840816..d0e1de3 100644
--- a/pkg/front_end/lib/src/fasta/parser/parser.dart
+++ b/pkg/front_end/lib/src/fasta/parser/parser.dart
@@ -2748,10 +2748,19 @@
listener.beginTypeArguments(begin);
int count = 0;
do {
- token = parseType(token.next);
+ token = parseType(next);
+ next = token.next;
++count;
- } while (optional(',', token.next));
- token = begin.endToken = ensureGt(token);
+ } while (optional(',', next));
+ if (next == begin.endToken) {
+ token = next;
+ } else if (begin.endToken != null) {
+ reportRecoverableError(
+ next, fasta.templateExpectedToken.withArguments('>'));
+ token = begin.endToken;
+ } else {
+ token = begin.endToken = ensureGt(token);
+ }
listener.endTypeArguments(count, begin, token);
} else {
listener.handleNoTypeArguments(next);
@@ -3043,6 +3052,14 @@
reportRecoverableError(token, fasta.messageGetterWithFormals);
}
} else if (!isGetter) {
+ if (optional('operator', name)) {
+ Token next = name.next;
+ if (next.isOperator) {
+ name = next;
+ } else if (isUnaryMinus(next)) {
+ name = next.next;
+ }
+ }
reportRecoverableError(name, missingParameterMessage(kind));
}
}
@@ -3462,6 +3479,11 @@
bool isModifierOrFactory(Token next) =>
optional('factory', next) || isModifier(next);
+ bool isUnaryMinus(Token token) =>
+ token.kind == IDENTIFIER_TOKEN &&
+ token.lexeme == 'unary' &&
+ optional('-', token.next);
+
/// Parse a class member.
///
/// This method is only invoked from outside the parser. As a result, this
@@ -3542,14 +3564,8 @@
listener.beginMember();
Token beforeType = token;
- // TODO(danrubel): Consider changing the listener contract
- // so that the type reference can be parsed immediately
- // rather than skipped now and parsed later.
- token = skipTypeReferenceOpt(token, true);
- if (token == beforeType) {
- // There is no type reference.
- beforeType = null;
- }
+ TypeInfo typeInfo = computeType(token, false);
+ token = typeInfo.skipType(token);
next = token.next;
Token getOrSet;
@@ -3559,12 +3575,6 @@
if (next.next.isIdentifier) {
getOrSet = token = next;
next = token.next;
- if (!next.isIdentifier) {
- // Recovery
- insertSyntheticIdentifier(
- token, IdentifierContext.methodDeclaration);
- next = token.next;
- }
}
// Fall through to continue parsing `get` or `set` as an identifier.
} else if (identical(value, 'factory')) {
@@ -3580,20 +3590,39 @@
// `operator` can be used as an identifier as in
// `int operator<T>()` or `int operator = 2`
if (next2.isUserDefinableOperator && next2.endGroup == null) {
- token = parseMethod(beforeStart, externalToken, staticToken,
- covariantToken, varFinalOrConst, beforeType, getOrSet, token);
+ token = parseMethod(
+ beforeStart,
+ externalToken,
+ staticToken,
+ covariantToken,
+ varFinalOrConst,
+ beforeType,
+ typeInfo,
+ getOrSet,
+ token);
listener.endMember();
return token;
} else if (optional('===', next2) ||
(next2.isOperator &&
!optional('=', next2) &&
!optional('<', next2))) {
+ // Recovery: Invalid operator
+ return parseInvalidOperatorDeclaration(beforeStart, externalToken,
+ staticToken, covariantToken, varFinalOrConst, beforeType);
+ } else if (isUnaryMinus(next2)) {
// Recovery
- token = next2;
- insertSyntheticIdentifier(token, IdentifierContext.methodDeclaration,
- message: fasta.templateInvalidOperator.withArguments(token),
- messageOnToken: token);
- next = token.next;
+ token = parseMethod(
+ beforeStart,
+ externalToken,
+ staticToken,
+ covariantToken,
+ varFinalOrConst,
+ beforeType,
+ typeInfo,
+ getOrSet,
+ token);
+ listener.endMember();
+ return token;
}
// Fall through to continue parsing `operator` as an identifier.
} else if (!next.isIdentifier ||
@@ -3609,12 +3638,25 @@
covariantToken,
varFinalOrConst,
beforeType,
+ typeInfo,
getOrSet,
typeContinuation);
}
+ } else if (typeInfo == noTypeInfo && varFinalOrConst == null) {
+ Token next2 = next.next;
+ if (next2.isUserDefinableOperator && next2.endGroup == null) {
+ String value = next2.next.stringValue;
+ if (identical(value, '(') ||
+ identical(value, '{') ||
+ identical(value, '=>')) {
+ // Recovery: Missing `operator` keyword
+ return parseInvalidOperatorDeclaration(beforeStart, externalToken,
+ staticToken, covariantToken, varFinalOrConst, beforeType);
+ }
+ }
}
- // At this point, token is before the name, and next is the name
+ // At this point, token is before the name, and next is the name
next = next.next;
String value = next.stringValue;
if (getOrSet != null ||
@@ -3623,13 +3665,22 @@
identical(value, '<') ||
identical(value, '.') ||
identical(value, '=>')) {
- token = parseMethod(beforeStart, externalToken, staticToken,
- covariantToken, varFinalOrConst, beforeType, getOrSet, token);
+ token = parseMethod(
+ beforeStart,
+ externalToken,
+ staticToken,
+ covariantToken,
+ varFinalOrConst,
+ beforeType,
+ typeInfo,
+ getOrSet,
+ token);
} else {
if (getOrSet != null) {
reportRecoverableErrorWithToken(
getOrSet, fasta.templateExtraneousModifier);
}
+ // TODO(danrubel): Use typeInfo when parsing fields.
token = parseFields(
beforeStart,
externalToken,
@@ -3654,6 +3705,7 @@
Token covariantToken,
Token varFinalOrConst,
Token beforeType,
+ TypeInfo typeInfo,
Token getOrSet,
Token beforeName) {
bool isOperator = getOrSet == null && optional('operator', beforeName.next);
@@ -3692,11 +3744,7 @@
listener.beginMethod(externalToken, staticToken, covariantToken,
varFinalOrConst, beforeName.next);
- if (beforeType == null) {
- listener.handleNoType(beforeName);
- } else {
- parseType(beforeType, TypeContinuation.Optional);
- }
+ typeInfo.parseType(beforeType, this);
Token token;
if (isOperator) {
@@ -3823,6 +3871,12 @@
}
} else if (optional('(', next)) {
return ensureIdentifier(beforeToken, IdentifierContext.operatorName);
+ } else if (isUnaryMinus(next)) {
+ // Recovery
+ reportRecoverableErrorWithToken(next, fasta.templateUnexpectedToken);
+ next = next.next;
+ listener.handleOperatorName(token, next);
+ return next;
} else {
// Recovery
// The user has specified an invalid operator name.
@@ -5328,7 +5382,7 @@
if (optional('!', token.next)) {
not = token = token.next;
}
- token = parseType(token);
+ token = computeType(token, true).ensureTypeNotVoid(token, this);
Token next = token.next;
listener.handleIsOperator(operator, not, next);
String value = next.stringValue;
@@ -5348,7 +5402,7 @@
Token parseAsOperatorRest(Token token) {
Token operator = token = token.next;
assert(optional('as', operator));
- token = parseType(token);
+ token = computeType(token, true).ensureTypeNotVoid(token, this);
Token next = token.next;
listener.handleAsOperator(operator, next);
String value = next.stringValue;
@@ -6274,6 +6328,51 @@
return beforeToken;
}
+ /// Recover from finding an operator declaration missing the `operator`
+ /// keyword. The metadata for the member, if any, has already been parsed
+ /// (and events have already been generated).
+ Token parseInvalidOperatorDeclaration(
+ Token beforeStart,
+ Token externalToken,
+ Token staticToken,
+ Token covariantToken,
+ Token varFinalOrConst,
+ Token beforeType) {
+ TypeInfo typeInfo = computeType(beforeType, true);
+
+ Token beforeName = typeInfo.skipType(beforeType);
+ Token next = beforeName.next;
+
+ if (optional('operator', next)) {
+ next = next.next;
+ } else {
+ reportRecoverableError(next, fasta.messageMissingOperatorKeyword);
+ rewriter.insertTokenAfter(
+ beforeName, new SyntheticToken(Keyword.OPERATOR, next.offset));
+ }
+
+ assert((next.isOperator && next.endGroup == null) || optional('===', next));
+ if (!next.isUserDefinableOperator) {
+ beforeName = next;
+ insertSyntheticIdentifier(beforeName, IdentifierContext.methodDeclaration,
+ message: fasta.templateInvalidOperator.withArguments(next),
+ messageOnToken: next);
+ }
+
+ Token token = parseMethod(
+ beforeStart,
+ externalToken,
+ staticToken,
+ covariantToken,
+ varFinalOrConst,
+ beforeType,
+ typeInfo,
+ null,
+ beforeName);
+ listener.endMember();
+ return token;
+ }
+
/// Recover from finding an invalid class member. The metadata for the member,
/// if any, has already been parsed (and events have already been generated).
/// The member was expected to start with the token after [token].
@@ -6285,6 +6384,7 @@
Token covariantToken,
Token varFinalOrConst,
Token beforeType,
+ TypeInfo typeInfo,
Token getOrSet,
TypeContinuation typeContinuation) {
Token next = token.next;
@@ -6296,13 +6396,15 @@
return reportAndSkipEnumInClass(next);
} else if (identical(value, 'typedef')) {
return reportAndSkipTypedefInClass(next);
+ } else if (next.isOperator) {
+ return parseInvalidOperatorDeclaration(beforeStart, externalToken,
+ staticToken, covariantToken, varFinalOrConst, beforeType);
}
bool looksLikeMethod = getOrSet != null ||
identical(value, '(') ||
identical(value, '=>') ||
- identical(value, '{') ||
- next.isOperator;
+ identical(value, '{');
if (token == beforeStart && !looksLikeMethod) {
// Ensure we make progress.
// TODO(danrubel): Provide a more specific error message for extra ';'.
@@ -6311,35 +6413,30 @@
token = next;
} else {
// Looks like a partial declaration.
- if (next.isUserDefinableOperator) {
- reportRecoverableError(next, fasta.messageMissingOperatorKeyword);
- // Insert a synthetic 'operator'.
+ reportRecoverableError(
+ next, fasta.templateExpectedIdentifier.withArguments(next));
+ // Insert a synthetic identifier and continue parsing.
+ if (!next.isIdentifier) {
rewriter.insertTokenAfter(
- token, new SyntheticToken(Keyword.OPERATOR, next.offset));
- } else {
- if (next.isOperator) {
- reportRecoverableErrorWithToken(next, fasta.templateInvalidOperator);
- token = next;
- next = token.next;
- } else {
- reportRecoverableError(
- next, fasta.templateExpectedIdentifier.withArguments(next));
- }
- // Insert a synthetic identifier and continue parsing.
- if (!next.isIdentifier) {
- rewriter.insertTokenAfter(
- token,
- new SyntheticStringToken(
- TokenType.IDENTIFIER,
- '#synthetic_identifier_${next.charOffset}',
- next.charOffset,
- 0));
- }
+ token,
+ new SyntheticStringToken(
+ TokenType.IDENTIFIER,
+ '#synthetic_identifier_${next.charOffset}',
+ next.charOffset,
+ 0));
}
if (looksLikeMethod) {
- token = parseMethod(beforeStart, externalToken, staticToken,
- covariantToken, varFinalOrConst, beforeType, getOrSet, token);
+ token = parseMethod(
+ beforeStart,
+ externalToken,
+ staticToken,
+ covariantToken,
+ varFinalOrConst,
+ beforeType,
+ typeInfo,
+ getOrSet,
+ token);
} else {
token = parseFields(
beforeStart,
diff --git a/pkg/front_end/lib/src/fasta/parser/type_info.dart b/pkg/front_end/lib/src/fasta/parser/type_info.dart
index 704ca9b9..5723020 100644
--- a/pkg/front_end/lib/src/fasta/parser/type_info.dart
+++ b/pkg/front_end/lib/src/fasta/parser/type_info.dart
@@ -4,7 +4,7 @@
library fasta.parser.type_info;
-import '../../scanner/token.dart' show Token, TokenType;
+import '../../scanner/token.dart' show SyntheticStringToken, Token, TokenType;
import '../scanner/token_constants.dart' show IDENTIFIER_TOKEN, KEYWORD_TOKEN;
@@ -39,7 +39,20 @@
/// or as expressions, while `A<T>` only looks like a type reference.
bool get couldBeExpression;
- /// Call this function when it's known that the token after [token] is a type.
+ /// Call this function when the token after [token] must be a type (not void).
+ /// This function will call the appropriate event methods on the [Parser]'s
+ /// listener to handle the type, inserting a synthetic type reference if
+ /// necessary. This may modify the token stream when parsing `>>` in valid
+ /// code or during recovery.
+ Token ensureTypeNotVoid(Token token, Parser parser);
+
+ /// Call this function to parse an optional type (not void) after [token].
+ /// This function will call the appropriate event methods on the [Parser]'s
+ /// listener to handle the type. This may modify the token stream
+ /// when parsing `>>` in valid code or during recovery.
+ Token parseTypeNotVoid(Token token, Parser parser);
+
+ /// Call this function to parse an optional type or void after [token].
/// This function will call the appropriate event methods on the [Parser]'s
/// listener to handle the type. This may modify the token stream
/// when parsing `>>` in valid code or during recovery.
@@ -72,6 +85,13 @@
/// identifier `<` identifier `>`.
const TypeInfo simpleTypeArgumentsInfo = const SimpleTypeArgumentsInfo();
+Token insertSyntheticIdentifierAfter(Token token, Parser parser) {
+ Token identifier = new SyntheticStringToken(
+ TokenType.IDENTIFIER, '', token.next.charOffset, 0);
+ parser.rewriter.insertTokenAfter(token, identifier);
+ return identifier;
+}
+
bool isGeneralizedFunctionType(Token token) {
return optional('Function', token) &&
(optional('<', token.next) || optional('(', token.next));
@@ -96,6 +116,17 @@
TypeInfo computeType(final Token token, bool required) {
Token next = token.next;
if (!isValidTypeReference(next)) {
+ if (next.type.isBuiltIn) {
+ Token afterType = next.next;
+ if (optional('<', afterType) && afterType.endGroup != null) {
+ // Recovery: built-in used as a type
+ return new ComplexTypeInfo(token)
+ .computeSimpleWithTypeArguments(required);
+ } else if (isGeneralizedFunctionType(afterType)) {
+ // Recovery: built-in used as a type
+ return new ComplexTypeInfo(token).computeIdentifierGFT(required);
+ }
+ }
return noTypeInfo;
}
@@ -206,6 +237,14 @@
bool get couldBeExpression => false;
@override
+ Token ensureTypeNotVoid(Token token, Parser parser) =>
+ parseType(token, parser);
+
+ @override
+ Token parseTypeNotVoid(Token token, Parser parser) =>
+ parseType(token, parser);
+
+ @override
Token parseType(Token token, Parser parser) {
assert(identical(token.next, start));
Listener listener = parser.listener;
@@ -219,7 +258,7 @@
// A function type without return type.
// Push the non-existing return type first. The loop below will
// generate the full type.
- noTypeInfo.parseType(token, parser);
+ noTypeInfo.parseTypeNotVoid(token, parser);
} else if (optional('void', token.next)) {
token = voidTypeInfo.parseType(token, parser);
} else {
@@ -290,7 +329,7 @@
/// Given identifier `Function` non-identifier, compute the type
/// and return the receiver or one of the [TypeInfo] constants.
TypeInfo computeIdentifierGFT(bool required) {
- assert(isValidTypeReference(start));
+ assert(isValidTypeReference(start) || start.type.isBuiltIn);
assert(optional('Function', start.next));
computeRest(start.next, required);
@@ -300,7 +339,7 @@
/// Given identifier `<` ... `>`, compute the type
/// and return the receiver or one of the [TypeInfo] constants.
TypeInfo computeSimpleWithTypeArguments(bool required) {
- assert(isValidTypeReference(start));
+ assert(isValidTypeReference(start) || start.type.isBuiltIn);
typeArguments = start.next;
assert(optional('<', typeArguments));
diff --git a/pkg/front_end/lib/src/fasta/parser/type_info_impl.dart b/pkg/front_end/lib/src/fasta/parser/type_info_impl.dart
index 811672b..1a4c75b 100644
--- a/pkg/front_end/lib/src/fasta/parser/type_info_impl.dart
+++ b/pkg/front_end/lib/src/fasta/parser/type_info_impl.dart
@@ -6,13 +6,16 @@
import '../../scanner/token.dart' show Token;
+import '../fasta_codes.dart' as fasta;
+
import 'identifier_context.dart' show IdentifierContext;
import 'listener.dart' show Listener;
import 'parser.dart' show Parser;
-import 'type_info.dart' show TypeInfo, simpleTypeInfo;
+import 'type_info.dart'
+ show insertSyntheticIdentifierAfter, simpleTypeInfo, TypeInfo;
import 'util.dart' show optional;
@@ -24,6 +27,18 @@
bool get couldBeExpression => false;
@override
+ Token ensureTypeNotVoid(Token token, Parser parser) {
+ parser.reportRecoverableErrorWithToken(
+ token.next, fasta.templateExpectedType);
+ insertSyntheticIdentifierAfter(token, parser);
+ return simpleTypeInfo.parseTypeNotVoid(token, parser);
+ }
+
+ @override
+ Token parseTypeNotVoid(Token token, Parser parser) =>
+ parseType(token, parser);
+
+ @override
Token parseType(Token token, Parser parser) {
parser.listener.handleNoType(token);
return token;
@@ -43,6 +58,14 @@
bool get couldBeExpression => true;
@override
+ Token ensureTypeNotVoid(Token token, Parser parser) =>
+ parseType(token, parser);
+
+ @override
+ Token parseTypeNotVoid(Token token, Parser parser) =>
+ parseType(token, parser);
+
+ @override
Token parseType(Token token, Parser parser) {
Token start = token = token.next;
assert(token.isKeywordOrIdentifier);
@@ -77,6 +100,14 @@
bool get couldBeExpression => false;
@override
+ Token ensureTypeNotVoid(Token token, Parser parser) =>
+ parseType(token, parser);
+
+ @override
+ Token parseTypeNotVoid(Token token, Parser parser) =>
+ parseType(token, parser);
+
+ @override
Token parseType(Token token, Parser parser) {
Token start = token = token.next;
assert(token.isKeywordOrIdentifier);
@@ -87,7 +118,7 @@
assert(optional('<', token));
listener.beginTypeArguments(token);
- token = simpleTypeInfo.parseType(token, parser);
+ token = simpleTypeInfo.parseTypeNotVoid(token, parser);
token = token.next;
assert(optional('>', token));
@@ -112,6 +143,14 @@
bool get couldBeExpression => true;
@override
+ Token ensureTypeNotVoid(Token token, Parser parser) =>
+ parseType(token, parser);
+
+ @override
+ Token parseTypeNotVoid(Token token, Parser parser) =>
+ parseType(token, parser);
+
+ @override
Token parseType(Token token, Parser parser) {
token = token.next;
assert(token.isKeywordOrIdentifier);
@@ -136,6 +175,17 @@
bool get couldBeExpression => false;
@override
+ Token ensureTypeNotVoid(Token token, Parser parser) {
+ // Report an error, then parse `void` as if it were a type name.
+ parser.reportRecoverableError(token.next, fasta.messageInvalidVoid);
+ return simpleTypeInfo.parseTypeNotVoid(token, parser);
+ }
+
+ @override
+ Token parseTypeNotVoid(Token token, Parser parser) =>
+ ensureTypeNotVoid(token, parser);
+
+ @override
Token parseType(Token token, Parser parser) {
token = token.next;
parser.listener.handleVoidKeyword(token);
diff --git a/pkg/front_end/lib/src/fasta/source/source_library_builder.dart b/pkg/front_end/lib/src/fasta/source/source_library_builder.dart
index 79e0664..c82040d 100644
--- a/pkg/front_end/lib/src/fasta/source/source_library_builder.dart
+++ b/pkg/front_end/lib/src/fasta/source/source_library_builder.dart
@@ -244,9 +244,7 @@
const String prefix = "dart.library.";
if (!dottedName.startsWith(prefix)) return "";
dottedName = dottedName.substring(prefix.length);
- String override =
- loader.target.uriTranslator.environmentOverrideFor(dottedName);
- if (override != null) return override;
+ if (!loader.target.uriTranslator.isLibrarySupported(dottedName)) return "";
LibraryBuilder imported =
loader.builders[new Uri(scheme: "dart", path: dottedName)];
diff --git a/pkg/front_end/lib/src/fasta/source/source_loader.dart b/pkg/front_end/lib/src/fasta/source/source_loader.dart
index e15d994..bc185c8 100644
--- a/pkg/front_end/lib/src/fasta/source/source_loader.dart
+++ b/pkg/front_end/lib/src/fasta/source/source_loader.dart
@@ -360,6 +360,8 @@
void instantiateToBound(TypeBuilder dynamicType, TypeBuilder bottomType,
ClassBuilder objectClass) {
+ if (!target.strongMode) return;
+
int count = 0;
builders.forEach((Uri uri, LibraryBuilder library) {
if (library.loader == this) {
@@ -633,6 +635,8 @@
}
void addNoSuchMethodForwarders(List<SourceClassBuilder> sourceClasses) {
+ if (!target.backendTarget.enableNoSuchMethodForwarders) return;
+
for (SourceClassBuilder builder in sourceClasses) {
if (builder.library.loader == this) {
builder.addNoSuchMethodForwarders(hierarchy);
@@ -811,9 +815,4 @@
new InstrumentationValueLiteral(context.code.name));
}
}
-
- void releaseAncillaryResources() {
- hierarchy = null;
- typeInferenceEngine = null;
- }
}
diff --git a/pkg/front_end/lib/src/fasta/uri_translator.dart b/pkg/front_end/lib/src/fasta/uri_translator.dart
index 135ad73..7a0c8ff 100644
--- a/pkg/front_end/lib/src/fasta/uri_translator.dart
+++ b/pkg/front_end/lib/src/fasta/uri_translator.dart
@@ -29,7 +29,6 @@
/// [CompilerContext.current].
Uri translate(Uri uri, [bool reportMessage = true]);
- /// Return the value of `dart.library.name`, if it was overriden in the
- /// library specification file, otherwise return null.
- String environmentOverrideFor(String libraryName);
+ /// Whether the given [libraryName] is supported by the underlying target.
+ bool isLibrarySupported(String libraryName);
}
diff --git a/pkg/front_end/lib/src/fasta/uri_translator_impl.dart b/pkg/front_end/lib/src/fasta/uri_translator_impl.dart
index 5c52e50..a97d0ef 100644
--- a/pkg/front_end/lib/src/fasta/uri_translator_impl.dart
+++ b/pkg/front_end/lib/src/fasta/uri_translator_impl.dart
@@ -46,8 +46,11 @@
}
@override
- String environmentOverrideFor(String libraryName) =>
- dartLibraries.environmentOverrideFor(libraryName);
+ bool isLibrarySupported(String libraryName) {
+ // TODO(sigmund): change this to `?? false` when all backends provide the
+ // `libraries.json` file by default (Issue #32657).
+ return dartLibraries.libraryInfoFor(libraryName)?.isSupported ?? true;
+ }
/// Return the file URI that corresponds to the given `dart` URI, or `null`
/// if there is no corresponding Dart library registered.
diff --git a/pkg/front_end/test/fasta/parser/type_info_test.dart b/pkg/front_end/test/fasta/parser/type_info_test.dart
index 4bbac1c..331eb7e 100644
--- a/pkg/front_end/test/fasta/parser/type_info_test.dart
+++ b/pkg/front_end/test/fasta/parser/type_info_test.dart
@@ -26,8 +26,24 @@
expect(typeInfo.skipType(start), expectedEnd);
TypeInfoListener listener = new TypeInfoListener();
+ expect(typeInfo.ensureTypeNotVoid(start, new Parser(listener)),
+ new isInstanceOf<SyntheticStringToken>());
+ expect(listener.calls, [
+ 'handleIdentifier typeReference',
+ 'handleNoTypeArguments ;',
+ 'handleType ;',
+ ]);
+ expect(listener.errors, [new ExpectedError(codeExpectedType, 7, 1)]);
+
+ listener = new TypeInfoListener();
+ expect(typeInfo.parseTypeNotVoid(start, new Parser(listener)), expectedEnd);
+ expect(listener.calls, ['handleNoType before']);
+ expect(listener.errors, isNull);
+
+ listener = new TypeInfoListener();
expect(typeInfo.parseType(start, new Parser(listener)), expectedEnd);
expect(listener.calls, ['handleNoType before']);
+ expect(listener.errors, isNull);
}
void test_voidType() {
@@ -38,8 +54,28 @@
expect(typeInfo.couldBeExpression, isFalse);
TypeInfoListener listener = new TypeInfoListener();
+ expect(
+ typeInfo.ensureTypeNotVoid(start, new Parser(listener)), expectedEnd);
+ expect(listener.calls, [
+ 'handleIdentifier void typeReference',
+ 'handleNoTypeArguments ;',
+ 'handleType void ;',
+ ]);
+ expect(listener.errors, [new ExpectedError(codeInvalidVoid, 7, 4)]);
+
+ listener = new TypeInfoListener();
+ expect(typeInfo.parseTypeNotVoid(start, new Parser(listener)), expectedEnd);
+ expect(listener.calls, [
+ 'handleIdentifier void typeReference',
+ 'handleNoTypeArguments ;',
+ 'handleType void ;',
+ ]);
+ expect(listener.errors, [new ExpectedError(codeInvalidVoid, 7, 4)]);
+
+ listener = new TypeInfoListener();
expect(typeInfo.parseType(start, new Parser(listener)), expectedEnd);
expect(listener.calls, ['handleVoidKeyword void']);
+ expect(listener.errors, isNull);
}
void test_prefixedTypeInfo() {
@@ -49,15 +85,27 @@
expect(typeInfo.skipType(start), expectedEnd);
expect(typeInfo.couldBeExpression, isTrue);
- TypeInfoListener listener = new TypeInfoListener();
- expect(typeInfo.parseType(start, new Parser(listener)), expectedEnd);
- expect(listener.calls, [
- 'handleIdentifier C prefixedTypeReference',
- 'handleIdentifier a typeReferenceContinuation',
- 'handleQualified .',
- 'handleNoTypeArguments ;',
- 'handleType C ;',
- ]);
+ TypeInfoListener listener;
+ assertResult(Token actualEnd) {
+ expect(actualEnd, expectedEnd);
+ expect(listener.calls, [
+ 'handleIdentifier C prefixedTypeReference',
+ 'handleIdentifier a typeReferenceContinuation',
+ 'handleQualified .',
+ 'handleNoTypeArguments ;',
+ 'handleType C ;',
+ ]);
+ expect(listener.errors, isNull);
+ }
+
+ listener = new TypeInfoListener();
+ assertResult(typeInfo.ensureTypeNotVoid(start, new Parser(listener)));
+
+ listener = new TypeInfoListener();
+ assertResult(typeInfo.parseTypeNotVoid(start, new Parser(listener)));
+
+ listener = new TypeInfoListener();
+ assertResult(typeInfo.parseType(start, new Parser(listener)));
}
void test_simpleTypeInfo() {
@@ -67,13 +115,25 @@
expect(typeInfo.skipType(start), expectedEnd);
expect(typeInfo.couldBeExpression, isTrue);
- TypeInfoListener listener = new TypeInfoListener();
- expect(typeInfo.parseType(start, new Parser(listener)), expectedEnd);
- expect(listener.calls, [
- 'handleIdentifier C typeReference',
- 'handleNoTypeArguments ;',
- 'handleType C ;',
- ]);
+ TypeInfoListener listener;
+ assertResult(Token actualEnd) {
+ expect(actualEnd, expectedEnd);
+ expect(listener.calls, [
+ 'handleIdentifier C typeReference',
+ 'handleNoTypeArguments ;',
+ 'handleType C ;',
+ ]);
+ expect(listener.errors, isNull);
+ }
+
+ listener = new TypeInfoListener();
+ assertResult(typeInfo.ensureTypeNotVoid(start, new Parser(listener)));
+
+ listener = new TypeInfoListener();
+ assertResult(typeInfo.parseTypeNotVoid(start, new Parser(listener)));
+
+ listener = new TypeInfoListener();
+ assertResult(typeInfo.parseType(start, new Parser(listener)));
}
void test_simpleTypeArgumentsInfo() {
@@ -83,17 +143,29 @@
expect(typeInfo.skipType(start), expectedEnd);
expect(typeInfo.couldBeExpression, isFalse);
- TypeInfoListener listener = new TypeInfoListener();
- expect(typeInfo.parseType(start, new Parser(listener)), expectedEnd);
- expect(listener.calls, [
- 'handleIdentifier C typeReference',
- 'beginTypeArguments <',
- 'handleIdentifier T typeReference',
- 'handleNoTypeArguments >',
- 'handleType T >',
- 'endTypeArguments 1 < >',
- 'handleType C ;',
- ]);
+ TypeInfoListener listener;
+ assertResult(Token actualEnd) {
+ expect(actualEnd, expectedEnd);
+ expect(listener.calls, [
+ 'handleIdentifier C typeReference',
+ 'beginTypeArguments <',
+ 'handleIdentifier T typeReference',
+ 'handleNoTypeArguments >',
+ 'handleType T >',
+ 'endTypeArguments 1 < >',
+ 'handleType C ;',
+ ]);
+ expect(listener.errors, isNull);
+ }
+
+ listener = new TypeInfoListener();
+ assertResult(typeInfo.ensureTypeNotVoid(start, new Parser(listener)));
+
+ listener = new TypeInfoListener();
+ assertResult(typeInfo.parseTypeNotVoid(start, new Parser(listener)));
+
+ listener = new TypeInfoListener();
+ assertResult(typeInfo.parseType(start, new Parser(listener)));
}
void test_computeType_basic() {
@@ -346,7 +418,7 @@
'handleNoTypeArguments double',
'handleType int double',
'endTypeArguments 1 < >',
- 'handleType G double',
+ 'handleType G g',
],
expectedErrors: [
error(codeExpectedToken, 6, 6)
@@ -592,24 +664,29 @@
TypeInfo typeInfo = computeType(start, required);
expect(typeInfo, expectedInfo, reason: source);
if (typeInfo is ComplexTypeInfo) {
- TypeInfoListener listener = new TypeInfoListener();
- Parser parser = new Parser(listener);
expect(typeInfo.start, start.next, reason: source);
expect(typeInfo.couldBeExpression, isFalse);
expectEnd(expectedAfter, typeInfo.skipType(start));
- expectEnd(expectedAfter, typeInfo.parseType(start, parser));
- if (expectedCalls != null) {
- // TypeInfoListener listener2 = new TypeInfoListener();
- // new Parser(listener2).parseType(start, TypeContinuation.Required);
- // print('[');
- // for (String call in listener2.calls) {
- // print("'$call',");
- // }
- // print(']');
- expect(listener.calls, expectedCalls, reason: source);
+ TypeInfoListener listener;
+ assertResult(Token actualEnd) {
+ expectEnd(expectedAfter, actualEnd);
+ if (expectedCalls != null) {
+ // TypeInfoListener listener2 = new TypeInfoListener();
+ // new Parser(listener2).parseType(start, TypeContinuation.Required);
+ // print('[');
+ // for (String call in listener2.calls) {
+ // print("'$call',");
+ // }
+ // print(']');
+
+ expect(listener.calls, expectedCalls, reason: source);
+ }
+ expect(listener.errors, expectedErrors, reason: source);
}
- expect(listener.errors, expectedErrors, reason: source);
+
+ listener = new TypeInfoListener();
+ assertResult(typeInfo.parseType(start, new Parser(listener)));
} else {
assert(expectedErrors == null);
}
diff --git a/pkg/front_end/test/incremental_bulk_compiler_full.dart b/pkg/front_end/test/incremental_bulk_compiler_full.dart
deleted file mode 100644
index 6f4e489..0000000
--- a/pkg/front_end/test/incremental_bulk_compiler_full.dart
+++ /dev/null
@@ -1,155 +0,0 @@
-// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-import 'dart:async' show Future;
-
-import 'package:expect/expect.dart' show Expect;
-
-import 'package:front_end/src/api_prototype/compiler_options.dart'
- show CompilerOptions;
-
-import 'package:front_end/src/api_prototype/incremental_kernel_generator.dart'
- show IncrementalKernelGenerator;
-
-import 'package:front_end/src/compute_platform_binaries_location.dart'
- show computePlatformBinariesLocation;
-
-import 'package:front_end/src/fasta/fasta_codes.dart' show LocatedMessage;
-
-import 'package:front_end/src/fasta/incremental_compiler.dart'
- show IncrementalCompiler;
-
-import 'package:front_end/src/fasta/kernel/utils.dart' show serializeComponent;
-
-import 'package:front_end/src/fasta/severity.dart' show Severity;
-
-import 'package:kernel/kernel.dart' show Component, Library, Reference;
-
-import 'package:kernel/text/ast_to_text.dart'
- show globalDebuggingNames, NameSystem;
-
-import 'package:testing/testing.dart'
- show Chain, ChainContext, Result, Step, TestDescription, runMe;
-
-main([List<String> arguments = const []]) =>
- runMe(arguments, createContext, "../testing.json");
-
-Future<Context> createContext(
- Chain suite, Map<String, String> environment) async {
- return new Context();
-}
-
-class Context extends ChainContext {
- final List<Step> steps = const <Step>[
- const RunTest(),
- ];
-
- // Override special handling of negative tests.
- @override
- Result processTestResult(
- TestDescription description, Result result, bool last) {
- return result;
- }
-
- IncrementalCompiler compiler;
-}
-
-CompilerOptions getOptions(bool strong) {
- final Uri sdkRoot = computePlatformBinariesLocation();
- var options = new CompilerOptions()
- ..sdkRoot = sdkRoot
- ..librariesSpecificationUri = Uri.base.resolve("sdk/lib/libraries.json")
- ..onProblem = (LocatedMessage message, Severity severity, String formatted,
- int line, int column) {
- // ignore
- }
- ..strongMode = strong;
- if (strong) {
- options.sdkSummary =
- computePlatformBinariesLocation().resolve("vm_platform_strong.dill");
- } else {
- options.sdkSummary =
- computePlatformBinariesLocation().resolve("vm_platform.dill");
- }
- return options;
-}
-
-class RunTest extends Step<TestDescription, TestDescription, Context> {
- const RunTest();
-
- String get name => "run test";
-
- Future<Result<TestDescription>> run(
- TestDescription description, Context context) async {
- Uri uri = description.uri;
-
- // "One shot compile"
- bool oneShotFailed = false;
- List<int> oneShotSerialized;
- try {
- IncrementalCompiler compiler =
- new IncrementalKernelGenerator(getOptions(true), uri);
- oneShotSerialized = postProcess(await compiler.computeDelta());
- } catch (e) {
- oneShotFailed = true;
- }
-
- // Bulk
- bool bulkFailed = false;
- List<int> bulkSerialized;
- try {
- globalDebuggingNames = new NameSystem();
- if (context.compiler == null) {
- context.compiler =
- new IncrementalKernelGenerator(getOptions(true), uri);
- }
- Component bulkCompiledComponent = await context.compiler
- .computeDelta(entryPoint: uri, fullComponent: true);
- bulkSerialized = postProcess(bulkCompiledComponent);
- } catch (e) {
- bulkFailed = true;
- }
-
- if (bulkFailed || oneShotFailed) {
- if (bulkFailed != oneShotFailed) {
- throw "Bulk-compiler failed: $bulkFailed; "
- "one-shot failed: $oneShotFailed";
- }
- } else {
- checkIsEqual(oneShotSerialized, bulkSerialized);
- }
-
- return pass(description);
- }
-
- List<int> postProcess(Component c) {
- c.libraries.sort((l1, l2) {
- return l1.fileUri.toString().compareTo(l2.fileUri.toString());
- });
-
- c.computeCanonicalNames();
- for (Library library in c.libraries) {
- library.additionalExports.sort((Reference r1, Reference r2) {
- return r1.canonicalName
- .toString()
- .compareTo(r2.canonicalName.toString());
- });
- }
-
- return serializeComponent(c);
- }
-
- void checkIsEqual(List<int> a, List<int> b) {
- int length = a.length;
- if (b.length < length) {
- length = b.length;
- }
- for (int i = 0; i < length; ++i) {
- if (a[i] != b[i]) {
- Expect.fail("Data differs at byte ${i+1}.");
- }
- }
- Expect.equals(a.length, b.length);
- }
-}
diff --git a/pkg/front_end/test/incremental_bulk_compiler_smoke_test.dart b/pkg/front_end/test/incremental_bulk_compiler_smoke_test.dart
deleted file mode 100644
index 5399635..0000000
--- a/pkg/front_end/test/incremental_bulk_compiler_smoke_test.dart
+++ /dev/null
@@ -1,17 +0,0 @@
-// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-import 'dart:async' show Future;
-
-import 'package:testing/testing.dart' show Chain, runMe;
-
-import 'incremental_bulk_compiler_full.dart' show Context;
-
-main([List<String> arguments = const []]) =>
- runMe(arguments, createContext, "../testing.json");
-
-Future<Context> createContext(
- Chain suite, Map<String, String> environment) async {
- return new Context();
-}
diff --git a/pkg/front_end/test/src/base/libraries_specification_test.dart b/pkg/front_end/test/src/base/libraries_specification_test.dart
index 60315e2..9d488aa 100644
--- a/pkg/front_end/test/src/base/libraries_specification_test.dart
+++ b/pkg/front_end/test/src/base/libraries_specification_test.dart
@@ -198,41 +198,54 @@
Uri.parse('org-dartlang-test:///one/two/c/main.dart'));
});
- test('environment_overrides entry must be a map', () async {
- var jsonString = '{"vm" : {"libraries": {"core": {"uri": "main.dart"}},'
- '"environment_overrides": []}}';
+ test('supported entry must be bool', () async {
+ var jsonString = '{"vm" : {"libraries": {"core": '
+ '{"uri": "main.dart", "supported": 3}},';
expect(
() => LibrariesSpecification.parse(
Uri.parse('org-dartlang-test:///f.json'), jsonString),
throwsA((e) => e is LibrariesSpecificationException));
});
- test('environment_overrides values must be bool', () async {
- var jsonString = '{"vm" : {"libraries": {"core": {"uri": "main.dart"}},'
- '"environment_overrides": {"core": 3}}}';
- expect(
- () => LibrariesSpecification.parse(
- Uri.parse('org-dartlang-test:///f.json'), jsonString),
- throwsA((e) => e is LibrariesSpecificationException));
- });
+ test('supported entry is copied correctly when parsing', () async {
+ var jsonString = '''
+ {
+ "vm": {
+ "libraries": {
+ "foo" : {
+ "uri": "a/main.dart",
+ "patches": [
+ "a/p1.dart",
+ "a/p2.dart"
+ ],
+ "supported": false
- test('environment_overrides correspond to existing libraries', () async {
- var jsonString = '{"vm" : {"libraries": {"core": {"uri": "main.dart"}},'
- '"environment_overrides": {"ui": false}}}';
- expect(
- () => LibrariesSpecification.parse(
- Uri.parse('org-dartlang-test:///f.json'), jsonString),
- throwsA((e) => e is LibrariesSpecificationException));
- });
-
- test('environment_overrides can be read from the public API', () async {
- var jsonString = '{"vm" : {"libraries": {"core": {"uri": "main.dart"}},'
- '"environment_overrides": {"core": false}}}';
+ },
+ "bar" : {
+ "uri": "b/main.dart",
+ "patches": [
+ "b/p3.dart"
+ ],
+ "supported": true
+ },
+ "baz" : {
+ "uri": "b/main.dart",
+ "patches": [
+ "b/p3.dart"
+ ]
+ }
+ }
+ }
+ }
+ ''';
var spec = LibrariesSpecification.parse(
Uri.parse('org-dartlang-test:///one/two/f.json'), jsonString);
expect(
- spec.specificationFor('vm').environmentOverrideFor('core'), "false");
- expect(spec.specificationFor('vm').environmentOverrideFor('ui'), null);
+ spec.specificationFor('vm').libraryInfoFor('foo').isSupported, false);
+ expect(
+ spec.specificationFor('vm').libraryInfoFor('bar').isSupported, true);
+ expect(
+ spec.specificationFor('vm').libraryInfoFor('baz').isSupported, true);
});
});
@@ -247,7 +260,8 @@
"patches": [
"a/p1.dart",
"a/p2.dart"
- ]
+ ],
+ "supported": false
},
"bar" : {
"uri": "b/main.dart",
@@ -263,9 +277,6 @@
"uri": "c/main.dart",
"patches": []
}
- },
- "environment_overrides": {
- "c" : false
}
}
}
diff --git a/pkg/front_end/testcases/incremental_bulk_compiler_full.status b/pkg/front_end/testcases/incremental_bulk_compiler_full.status
deleted file mode 100644
index acb1629..0000000
--- a/pkg/front_end/testcases/incremental_bulk_compiler_full.status
+++ /dev/null
@@ -1,3 +0,0 @@
-# Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
-# for details. All rights reserved. Use of this source code is governed by a
-# BSD-style license that can be found in the LICENSE.md file.
diff --git a/pkg/front_end/testcases/incremental_bulk_compiler_smoke.status b/pkg/front_end/testcases/incremental_bulk_compiler_smoke.status
deleted file mode 100644
index acb1629..0000000
--- a/pkg/front_end/testcases/incremental_bulk_compiler_smoke.status
+++ /dev/null
@@ -1,3 +0,0 @@
-# Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
-# for details. All rights reserved. Use of this source code is governed by a
-# BSD-style license that can be found in the LICENSE.md file.
diff --git a/pkg/front_end/testcases/regress/issue_31183.dart.direct.expect b/pkg/front_end/testcases/regress/issue_31183.dart.direct.expect
index 3911009..af19179 100644
--- a/pkg/front_end/testcases/regress/issue_31183.dart.direct.expect
+++ b/pkg/front_end/testcases/regress/issue_31183.dart.direct.expect
@@ -3,22 +3,15 @@
import "dart:core" as core;
class C extends core::Object {
- field dynamic operator = null;
synthetic constructor •() → void
: super core::Object::•()
;
operator unary-() → dynamic
return 0;
}
-static const field dynamic #errors = const <dynamic>["pkg/front_end/testcases/regress/issue_31183.dart:6:3: Error: Variables must be declared using the keywords 'const', 'final', 'var' or a type name.
-Try adding the name of the type of the variable or the keyword 'var'.
+static const field dynamic #errors = const <dynamic>["pkg/front_end/testcases/regress/issue_31183.dart:6:12: Error: Unexpected token 'unary'.
operator unary- => 0;
- ^^^^^^^^", "pkg/front_end/testcases/regress/issue_31183.dart:6:12: Error: Expected ';' before this.
- operator unary- => 0;
- ^^^^^", "pkg/front_end/testcases/regress/issue_31183.dart:6:17: Error: Operator declarations must be preceeded by the keyword 'operator'.
-Try adding the keyword 'operator'.
- operator unary- => 0;
- ^", "pkg/front_end/testcases/regress/issue_31183.dart:6:17: Error: A method declaration needs an explicit list of parameters.
+ ^^^^^", "pkg/front_end/testcases/regress/issue_31183.dart:6:17: Error: A method declaration needs an explicit list of parameters.
Try adding a parameter list to the method declaration.
operator unary- => 0;
^"]/* from null */;
diff --git a/pkg/front_end/testcases/regress/issue_31183.dart.direct.transformed.expect b/pkg/front_end/testcases/regress/issue_31183.dart.direct.transformed.expect
index 3911009..af19179 100644
--- a/pkg/front_end/testcases/regress/issue_31183.dart.direct.transformed.expect
+++ b/pkg/front_end/testcases/regress/issue_31183.dart.direct.transformed.expect
@@ -3,22 +3,15 @@
import "dart:core" as core;
class C extends core::Object {
- field dynamic operator = null;
synthetic constructor •() → void
: super core::Object::•()
;
operator unary-() → dynamic
return 0;
}
-static const field dynamic #errors = const <dynamic>["pkg/front_end/testcases/regress/issue_31183.dart:6:3: Error: Variables must be declared using the keywords 'const', 'final', 'var' or a type name.
-Try adding the name of the type of the variable or the keyword 'var'.
+static const field dynamic #errors = const <dynamic>["pkg/front_end/testcases/regress/issue_31183.dart:6:12: Error: Unexpected token 'unary'.
operator unary- => 0;
- ^^^^^^^^", "pkg/front_end/testcases/regress/issue_31183.dart:6:12: Error: Expected ';' before this.
- operator unary- => 0;
- ^^^^^", "pkg/front_end/testcases/regress/issue_31183.dart:6:17: Error: Operator declarations must be preceeded by the keyword 'operator'.
-Try adding the keyword 'operator'.
- operator unary- => 0;
- ^", "pkg/front_end/testcases/regress/issue_31183.dart:6:17: Error: A method declaration needs an explicit list of parameters.
+ ^^^^^", "pkg/front_end/testcases/regress/issue_31183.dart:6:17: Error: A method declaration needs an explicit list of parameters.
Try adding a parameter list to the method declaration.
operator unary- => 0;
^"]/* from null */;
diff --git a/pkg/front_end/testcases/regress/issue_31183.dart.outline.expect b/pkg/front_end/testcases/regress/issue_31183.dart.outline.expect
index 1b80db7..626dcfc 100644
--- a/pkg/front_end/testcases/regress/issue_31183.dart.outline.expect
+++ b/pkg/front_end/testcases/regress/issue_31183.dart.outline.expect
@@ -3,7 +3,6 @@
import "dart:core" as core;
class C extends core::Object {
- field dynamic operator;
synthetic constructor •() → void
;
operator unary-() → dynamic
diff --git a/pkg/front_end/testcases/regress/issue_31183.dart.strong.expect b/pkg/front_end/testcases/regress/issue_31183.dart.strong.expect
index 3911009..af19179 100644
--- a/pkg/front_end/testcases/regress/issue_31183.dart.strong.expect
+++ b/pkg/front_end/testcases/regress/issue_31183.dart.strong.expect
@@ -3,22 +3,15 @@
import "dart:core" as core;
class C extends core::Object {
- field dynamic operator = null;
synthetic constructor •() → void
: super core::Object::•()
;
operator unary-() → dynamic
return 0;
}
-static const field dynamic #errors = const <dynamic>["pkg/front_end/testcases/regress/issue_31183.dart:6:3: Error: Variables must be declared using the keywords 'const', 'final', 'var' or a type name.
-Try adding the name of the type of the variable or the keyword 'var'.
+static const field dynamic #errors = const <dynamic>["pkg/front_end/testcases/regress/issue_31183.dart:6:12: Error: Unexpected token 'unary'.
operator unary- => 0;
- ^^^^^^^^", "pkg/front_end/testcases/regress/issue_31183.dart:6:12: Error: Expected ';' before this.
- operator unary- => 0;
- ^^^^^", "pkg/front_end/testcases/regress/issue_31183.dart:6:17: Error: Operator declarations must be preceeded by the keyword 'operator'.
-Try adding the keyword 'operator'.
- operator unary- => 0;
- ^", "pkg/front_end/testcases/regress/issue_31183.dart:6:17: Error: A method declaration needs an explicit list of parameters.
+ ^^^^^", "pkg/front_end/testcases/regress/issue_31183.dart:6:17: Error: A method declaration needs an explicit list of parameters.
Try adding a parameter list to the method declaration.
operator unary- => 0;
^"]/* from null */;
diff --git a/pkg/front_end/testcases/regress/issue_31183.dart.strong.transformed.expect b/pkg/front_end/testcases/regress/issue_31183.dart.strong.transformed.expect
index 3911009..af19179 100644
--- a/pkg/front_end/testcases/regress/issue_31183.dart.strong.transformed.expect
+++ b/pkg/front_end/testcases/regress/issue_31183.dart.strong.transformed.expect
@@ -3,22 +3,15 @@
import "dart:core" as core;
class C extends core::Object {
- field dynamic operator = null;
synthetic constructor •() → void
: super core::Object::•()
;
operator unary-() → dynamic
return 0;
}
-static const field dynamic #errors = const <dynamic>["pkg/front_end/testcases/regress/issue_31183.dart:6:3: Error: Variables must be declared using the keywords 'const', 'final', 'var' or a type name.
-Try adding the name of the type of the variable or the keyword 'var'.
+static const field dynamic #errors = const <dynamic>["pkg/front_end/testcases/regress/issue_31183.dart:6:12: Error: Unexpected token 'unary'.
operator unary- => 0;
- ^^^^^^^^", "pkg/front_end/testcases/regress/issue_31183.dart:6:12: Error: Expected ';' before this.
- operator unary- => 0;
- ^^^^^", "pkg/front_end/testcases/regress/issue_31183.dart:6:17: Error: Operator declarations must be preceeded by the keyword 'operator'.
-Try adding the keyword 'operator'.
- operator unary- => 0;
- ^", "pkg/front_end/testcases/regress/issue_31183.dart:6:17: Error: A method declaration needs an explicit list of parameters.
+ ^^^^^", "pkg/front_end/testcases/regress/issue_31183.dart:6:17: Error: A method declaration needs an explicit list of parameters.
Try adding a parameter list to the method declaration.
operator unary- => 0;
^"]/* from null */;
diff --git a/pkg/front_end/testing.json b/pkg/front_end/testing.json
index af4b8b4..d16fa77 100644
--- a/pkg/front_end/testing.json
+++ b/pkg/front_end/testing.json
@@ -161,35 +161,6 @@
},
{
- "name": "incremental_bulk_compiler_smoke",
- "kind": "Chain",
- "source": "test/incremental_bulk_compiler_smoke_test.dart",
- "path": "../../tests/",
- "status": "testcases/incremental_bulk_compiler_smoke.status",
- "pattern": [
- "/language_2/accessor_conflict_export2_test\\.dart$",
- "/language_2/accessor_conflict_export_test\\.dart$",
- "/language_2/regress_14348_test\\.dart$",
- "/language_2/regress_18535_test\\.dart$"
- ],
- "exclude": [
- ]
- },
-
- {
- "name": "incremental_bulk_compiler_full",
- "kind": "Chain",
- "source": "test/incremental_bulk_compiler_full.dart",
- "path": "../../tests/",
- "status": "testcases/incremental_bulk_compiler_full.status",
- "pattern": [
- "language_2/.*_test\\.dart$"
- ],
- "exclude": [
- ]
- },
-
- {
"name": "sdk",
"kind": "Chain",
"source": "test/fasta/sdk_test.dart",
diff --git a/pkg/vm/lib/frontend_server.dart b/pkg/vm/lib/frontend_server.dart
index 341207f..15ee47f 100644
--- a/pkg/vm/lib/frontend_server.dart
+++ b/pkg/vm/lib/frontend_server.dart
@@ -256,6 +256,7 @@
printer.writeComponentFile(component);
await sink.close();
_outputStream.writeln('$boundaryKey $_kernelBinaryFilename');
+
final String depfile = options['depfile'];
if (depfile != null) {
await _writeDepfile(component, _kernelBinaryFilename, depfile);
@@ -269,10 +270,6 @@
Future<Null> invalidateIfBootstrapping() async {
if (_kernelBinaryFilename != _kernelBinaryFilenameFull) return null;
- // If the generator is initialized bootstrapping is not in effect anyway,
- // so there's no reason to spend time invalidating what should be
- // invalidated by the normal approach anyway.
- if (_generator.initialized) return null;
try {
final File f = new File(_kernelBinaryFilenameFull);
@@ -345,7 +342,7 @@
@override
void resetIncrementalCompiler() {
- _generator.resetDeltaState();
+ _generator = _createGenerator(new Uri.file(_kernelBinaryFilenameFull));
_kernelBinaryFilename = _kernelBinaryFilenameFull;
}
diff --git a/pkg/vm/lib/incremental_compiler.dart b/pkg/vm/lib/incremental_compiler.dart
index 91d9426..bfe5919 100644
--- a/pkg/vm/lib/incremental_compiler.dart
+++ b/pkg/vm/lib/incremental_compiler.dart
@@ -17,8 +17,6 @@
IncrementalKernelGenerator _generator;
List<Component> _pendingDeltas;
CompilerOptions _compilerOptions;
- bool initialized = false;
- bool fullComponent = false;
IncrementalCompiler(this._compilerOptions, Uri entryPoint,
{Uri bootstrapDill}) {
@@ -32,10 +30,7 @@
/// If [entryPoint] is specified, that points to new entry point for the
/// compilation. Otherwise, previously set entryPoint is used.
Future<Component> compile({Uri entryPoint}) async {
- Component component = await _generator.computeDelta(
- entryPoint: entryPoint, fullComponent: fullComponent);
- initialized = true;
- fullComponent = false;
+ Component component = await _generator.computeDelta(entryPoint: entryPoint);
final bool firstDelta = _pendingDeltas.isEmpty;
_pendingDeltas.add(component);
if (firstDelta) {
@@ -69,9 +64,4 @@
invalidate(Uri uri) {
_generator.invalidate(uri);
}
-
- resetDeltaState() {
- _pendingDeltas.clear();
- fullComponent = true;
- }
}
diff --git a/pkg/vm/lib/transformations/type_flow/summary_collector.dart b/pkg/vm/lib/transformations/type_flow/summary_collector.dart
index 11af8c3..493eaf2 100644
--- a/pkg/vm/lib/transformations/type_flow/summary_collector.dart
+++ b/pkg/vm/lib/transformations/type_flow/summary_collector.dart
@@ -804,7 +804,7 @@
.getDispatchTarget(_superclass, node.name, setter: true);
if (target != null) {
assertx((target is Field) || ((target is Procedure) && target.isSetter));
- return _makeCall(node,
+ _makeCall(node,
new DirectSelector(target, callKind: CallKind.PropertySet), args);
}
return value;
diff --git a/pkg/vm/test/frontend_server_test.dart b/pkg/vm/test/frontend_server_test.dart
index bc18e95..3279881 100644
--- a/pkg/vm/test/frontend_server_test.dart
+++ b/pkg/vm/test/frontend_server_test.dart
@@ -377,7 +377,6 @@
final _MockedIncrementalCompiler generator =
new _MockedIncrementalCompiler();
- when(generator.initialized).thenAnswer((_) => false);
when(generator.compile())
.thenAnswer((_) => new Future<Component>.value(new Component()));
final _MockedBinaryPrinterFactory printerFactory =
diff --git a/pkg/vm/testcases/transformations/type_flow/summary_collector/setter_result.dart b/pkg/vm/testcases/transformations/type_flow/summary_collector/setter_result.dart
new file mode 100644
index 0000000..f7bba1d
--- /dev/null
+++ b/pkg/vm/testcases/transformations/type_flow/summary_collector/setter_result.dart
@@ -0,0 +1,35 @@
+// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+class T {}
+
+void use(x) {}
+
+class A {
+ dynamic foo;
+}
+
+class B extends A {
+ set foo(x) {}
+
+ static dynamic bar;
+
+ void testPropertySet(x) {
+ use(foo = x);
+ }
+
+ void testDynamicPropertySet(x, y) {
+ use(x.foo = y);
+ }
+
+ void testSuperPropertySet(x) {
+ use(super.foo = x);
+ }
+
+ void testStaticPropertySet(x) {
+ use(bar = x);
+ }
+}
+
+main() {}
diff --git a/pkg/vm/testcases/transformations/type_flow/summary_collector/setter_result.dart.expect b/pkg/vm/testcases/transformations/type_flow/summary_collector/setter_result.dart.expect
new file mode 100644
index 0000000..608ebfa
--- /dev/null
+++ b/pkg/vm/testcases/transformations/type_flow/summary_collector/setter_result.dart.expect
@@ -0,0 +1,53 @@
+------------ #lib::T:: ------------
+%this = _Parameter #0 [_T (#lib::T)+]
+t1 = _Call direct [dart.core::Object::] (%this)
+RESULT: _T {}?
+------------ #lib::A:: ------------
+%this = _Parameter #0 [_T (#lib::A)+]
+t1 = _Call direct [dart.core::Object::] (%this)
+RESULT: _T {}?
+------------ #lib::A::foo ------------
+
+RESULT: _T {}?
+------------ #lib::B:: ------------
+%this = _Parameter #0 [_T (#lib::B)+]
+t1 = _Call direct [#lib::A::] (%this)
+RESULT: _T {}?
+------------ #lib::B::foo ------------
+%this = _Parameter #0 [_T (#lib::B)+]
+%x = _Parameter #1 [_T ANY?]
+RESULT: _T {}?
+------------ #lib::B::testPropertySet ------------
+%this = _Parameter #0 [_T (#lib::B)+]
+%x = _Parameter #1 [_T ANY?]
+t2 = _Call set [#lib::B::foo] (%this, %x)
+t3 = _Call direct [#lib::use] (%x)
+RESULT: _T {}?
+------------ #lib::B::testDynamicPropertySet ------------
+%this = _Parameter #0 [_T (#lib::B)+]
+%x = _Parameter #1 [_T ANY?]
+%y = _Parameter #2 [_T ANY?]
+t3 = _Call dynamic set [foo] (%x, %y)
+t4 = _Call direct [#lib::use] (%y)
+RESULT: _T {}?
+------------ #lib::B::testSuperPropertySet ------------
+%this = _Parameter #0 [_T (#lib::B)+]
+%x = _Parameter #1 [_T ANY?]
+t2 = _Call direct set [#lib::A::foo] (%this, %x)
+t3 = _Call direct [#lib::use] (%x)
+RESULT: _T {}?
+------------ #lib::B::testStaticPropertySet ------------
+%this = _Parameter #0 [_T (#lib::B)+]
+%x = _Parameter #1 [_T ANY?]
+t2 = _Call direct set [#lib::B::bar] (%x)
+t3 = _Call direct [#lib::use] (%x)
+RESULT: _T {}?
+------------ #lib::B::bar ------------
+
+RESULT: _T {}?
+------------ #lib::use ------------
+%x = _Parameter #0 [_T ANY?]
+RESULT: _T {}?
+------------ #lib::main ------------
+
+RESULT: _T {}?
diff --git a/runtime/bin/console_posix.cc b/runtime/bin/console_posix.cc
index 1abbe05..61fd677 100644
--- a/runtime/bin/console_posix.cc
+++ b/runtime/bin/console_posix.cc
@@ -49,7 +49,7 @@
static void SaveMode(intptr_t fd, tcflag_t* flag) {
ASSERT(flag != NULL);
struct termios term;
- int status = NO_RETRY_EXPECTED(tcgetattr(fd, &term));
+ int status = TEMP_FAILURE_RETRY(tcgetattr(fd, &term));
if (status != 0) {
return;
}
@@ -61,12 +61,12 @@
return;
}
struct termios term;
- int status = NO_RETRY_EXPECTED(tcgetattr(fd, &term));
+ int status = TEMP_FAILURE_RETRY(tcgetattr(fd, &term));
if (status != 0) {
return;
}
term.c_lflag = flag;
- NO_RETRY_EXPECTED(tcsetattr(fd, TCSANOW, &term));
+ VOID_TEMP_FAILURE_RETRY(tcsetattr(fd, TCSANOW, &term));
}
DISALLOW_ALLOCATION();
diff --git a/runtime/tests/vm/vm.status b/runtime/tests/vm/vm.status
index 0521a33..aab86f8 100644
--- a/runtime/tests/vm/vm.status
+++ b/runtime/tests/vm/vm.status
@@ -171,9 +171,6 @@
cc/DartAPI_LoadSource: Crash
cc/DartAPI_LoadSource_LateLoad: Crash
cc/DartAPI_ParsePatchLibrary: Crash
-cc/DartAPI_StackOverflowStackTraceInfoArrowFunction: Fail
-cc/DartAPI_StackOverflowStackTraceInfoBraceFunction1: Fail
-cc/DartAPI_StackOverflowStackTraceInfoBraceFunction2: Fail
cc/DebuggerAPI_BreakpointStubPatching: Fail
cc/DebuggerAPI_GetClosureInfo: Fail
cc/DebuggerAPI_InterruptIsolate: SkipSlow
@@ -257,10 +254,6 @@
[ $compiler == dartk && $strong ]
cc/DartAPI_ImportLibrary3: Fail # Issue 32190
cc/DartAPI_LazyLoadDeoptimizes: Crash # Issue 32190
-cc/DartAPI_NativePortPostInteger: Crash # Issue 32190
-cc/DartAPI_NativePortReceiveInteger: Timeout # Issue 32190
-cc/DartAPI_NativePortReceiveNull: Timeout # Issue 32190
-cc/DartAPI_NewNativePort: Crash, Timeout # Issue 32190
cc/DartGeneratedArrayLiteralMessages: Crash # Issue 32190
cc/FullSnapshot1: Crash # Issue 32190
cc/IsolateReload_LibraryImportAdded: Crash # Issue 32190
diff --git a/runtime/vm/clustered_snapshot.cc b/runtime/vm/clustered_snapshot.cc
index 38a1b58..dcf5f7b 100644
--- a/runtime/vm/clustered_snapshot.cc
+++ b/runtime/vm/clustered_snapshot.cc
@@ -596,8 +596,7 @@
s->Write<int32_t>(func->ptr()->kernel_offset_);
}
#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()->packed_fields_);
s->Write<uint32_t>(func->ptr()->kind_tag_);
}
}
@@ -660,8 +659,7 @@
func->ptr()->kernel_offset_ = d->Read<int32_t>();
}
#endif
- func->ptr()->num_fixed_parameters_ = d->Read<int16_t>();
- func->ptr()->num_optional_parameters_ = d->Read<int16_t>();
+ func->ptr()->packed_fields_ = d->Read<uint32_t>();
func->ptr()->kind_tag_ = d->Read<uint32_t>();
if (kind == Snapshot::kFullAOT) {
// Omit fields used to support de/reoptimization.
diff --git a/runtime/vm/compiler/frontend/flow_graph_builder.cc b/runtime/vm/compiler/frontend/flow_graph_builder.cc
index f22532f..3c801f0 100644
--- a/runtime/vm/compiler/frontend/flow_graph_builder.cc
+++ b/runtime/vm/compiler/frontend/flow_graph_builder.cc
@@ -3872,12 +3872,9 @@
// if we inline or not.
if (!function.IsImplicitGetterFunction() &&
!function.IsImplicitSetterFunction()) {
- // We want the stack overlow error to be reported at the opening '{' or
- // at the '=>' location. So, we get the sequence node corresponding to the
- // body inside |node| and use its token position.
- ASSERT(node->length() > 0);
+ // Stack overflow error is reported at the function token position.
CheckStackOverflowInstr* check = new (Z) CheckStackOverflowInstr(
- node->NodeAt(0)->token_pos(), 0, owner()->GetNextDeoptId());
+ function.token_pos(), 0, owner()->GetNextDeoptId());
// If we are inlining don't actually attach the stack check. We must still
// create the stack check in order to allocate a deopt id.
if (!owner()->IsInlining()) {
diff --git a/runtime/vm/compiler/frontend/flow_graph_builder_test.cc b/runtime/vm/compiler/frontend/flow_graph_builder_test.cc
index 3e2e01b..84eb098 100644
--- a/runtime/vm/compiler/frontend/flow_graph_builder_test.cc
+++ b/runtime/vm/compiler/frontend/flow_graph_builder_test.cc
@@ -292,7 +292,7 @@
SourcePositionTest spt(thread, kScript);
spt.BuildGraphFor("main");
spt.FuzzyInstructionMatchAt("DebugStepCheck", 3, 5);
- spt.FuzzyInstructionMatchAt("CheckStackOverflow", 3, 8);
+ spt.FuzzyInstructionMatchAt("CheckStackOverflow", 3, 1);
spt.InstanceCallAt(4, 13, Token::kADD);
spt.FuzzyInstructionMatchAt("DebugStepCheck", 5, 3);
spt.FuzzyInstructionMatchAt("Return", 5, 3);
@@ -314,7 +314,7 @@
SourcePositionTest spt(thread, kScript);
spt.BuildGraphFor("main");
spt.FuzzyInstructionMatchAt("DebugStepCheck", 3, 5);
- spt.FuzzyInstructionMatchAt("CheckStackOverflow", 3, 8);
+ spt.FuzzyInstructionMatchAt("CheckStackOverflow", 3, 1);
spt.FuzzyInstructionMatchAt("LoadStaticField", 4, 7);
spt.InstanceCallAt(4, 9, Token::kEQ);
spt.FuzzyInstructionMatchAt("Branch if StrictCompare", 4, 9);
@@ -342,7 +342,7 @@
SourcePositionTest spt(thread, kScript);
spt.BuildGraphFor("main");
spt.FuzzyInstructionMatchAt("DebugStepCheck", 3, 5);
- spt.FuzzyInstructionMatchAt("CheckStackOverflow", 3, 8);
+ spt.FuzzyInstructionMatchAt("CheckStackOverflow", 3, 1);
spt.FuzzyInstructionMatchAt("StoreLocal", 4, 14);
spt.FuzzyInstructionMatchAt("LoadLocal", 4, 19);
spt.InstanceCallAt(4, 21, Token::kLT);
@@ -375,7 +375,7 @@
SourcePositionTest spt(thread, kScript);
spt.BuildGraphFor("main");
spt.FuzzyInstructionMatchAt("DebugStepCheck", 3, 5);
- spt.FuzzyInstructionMatchAt("CheckStackOverflow", 3, 8);
+ spt.FuzzyInstructionMatchAt("CheckStackOverflow", 3, 1);
spt.FuzzyInstructionMatchAt("CheckStackOverflow", 4, 3);
spt.FuzzyInstructionMatchAt("Constant", 4, 10);
@@ -423,7 +423,7 @@
SourcePositionTest spt(thread, kScript);
spt.BuildGraphFor("main");
spt.FuzzyInstructionMatchAt("DebugStepCheck", 3, 5);
- spt.FuzzyInstructionMatchAt("CheckStackOverflow", 3, 8);
+ spt.FuzzyInstructionMatchAt("CheckStackOverflow", 3, 1);
spt.FuzzyInstructionMatchAt("CheckStackOverflow", 4, 3);
spt.FuzzyInstructionMatchAt("Constant(#Field", 4, 10);
@@ -458,7 +458,7 @@
spt.BuildGraphFor("main");
spt.FuzzyInstructionMatchAt("DebugStepCheck", 3, 5);
- spt.FuzzyInstructionMatchAt("CheckStackOverflow", 3, 8);
+ spt.FuzzyInstructionMatchAt("CheckStackOverflow", 3, 1);
spt.StaticCallAt("get:z", 4, 3);
spt.FuzzyInstructionMatchAt("Constant(#0)", 4, 5);
spt.InstanceCallAt(4, 4, Token::kINDEX);
@@ -496,7 +496,7 @@
spt.BuildGraphFor("main");
spt.FuzzyInstructionMatchAt("DebugStepCheck", 3, 5);
- spt.FuzzyInstructionMatchAt("CheckStackOverflow", 3, 8);
+ spt.FuzzyInstructionMatchAt("CheckStackOverflow", 3, 1);
spt.StaticCallAt("get:z", 4, 3);
spt.FuzzyInstructionMatchAt("Constant(#0)", 4, 5);
spt.InstanceCallAt(4, 4, Token::kINDEX);
@@ -543,7 +543,7 @@
spt.BuildGraphFor("main");
spt.FuzzyInstructionMatchAt("DebugStepCheck", 3, 5);
- spt.FuzzyInstructionMatchAt("CheckStackOverflow", 3, 8);
+ spt.FuzzyInstructionMatchAt("CheckStackOverflow", 3, 1);
spt.FuzzyInstructionMatchAt("DebugStepCheck", 4, 7);
spt.FuzzyInstructionMatchAt("Constant(#null", 4, 7);
@@ -590,7 +590,7 @@
SourcePositionTest spt(thread, kScript);
spt.BuildGraphFor("main");
spt.FuzzyInstructionMatchAt("DebugStepCheck", 3, 5);
- spt.FuzzyInstructionMatchAt("CheckStackOverflow", 3, 8);
+ spt.FuzzyInstructionMatchAt("CheckStackOverflow", 3, 1);
spt.FuzzyInstructionMatchAt("LoadStaticField", 4, 7);
spt.InstanceCallAt(4, 9, Token::kEQ);
spt.FuzzyInstructionMatchAt("Branch if StrictCompare", 4, 9);
@@ -620,7 +620,7 @@
spt.BuildGraphFor("main");
spt.FuzzyInstructionMatchAt("DebugStepCheck", 3, 5);
- spt.FuzzyInstructionMatchAt("CheckStackOverflow", 3, 8);
+ spt.FuzzyInstructionMatchAt("CheckStackOverflow", 3, 1);
spt.FuzzyInstructionMatchAt("Constant(#Field", 4, 11);
spt.FuzzyInstructionMatchAt("LoadStaticField", 4, 11);
spt.FuzzyInstructionMatchAt("StoreLocal(:switch_expr", 4, 11);
@@ -667,7 +667,7 @@
spt.BuildGraphFor("main");
spt.FuzzyInstructionMatchAt("DebugStepCheck", 3, 5);
- spt.FuzzyInstructionMatchAt("CheckStackOverflow", 3, 8);
+ spt.FuzzyInstructionMatchAt("CheckStackOverflow", 3, 1);
spt.FuzzyInstructionMatchAt("LoadLocal(:current_context", 4, 3); // 't'
spt.FuzzyInstructionMatchAt("StoreLocal(:saved_try_context", 4, 3);
diff --git a/runtime/vm/compiler/frontend/kernel_binary_flowgraph.cc b/runtime/vm/compiler/frontend/kernel_binary_flowgraph.cc
index 3a7ad08..4761c27 100644
--- a/runtime/vm/compiler/frontend/kernel_binary_flowgraph.cc
+++ b/runtime/vm/compiler/frontend/kernel_binary_flowgraph.cc
@@ -1088,7 +1088,7 @@
case RawFunction::kIrregexpFunction:
UNREACHABLE();
}
- if (needs_expr_temp_ || parsed_function_->is_no_such_method_forwarder()) {
+ if (needs_expr_temp_ || function.is_no_such_method_forwarder()) {
scope_->AddVariable(parsed_function_->EnsureExpressionTemp());
}
parsed_function_->AllocateVariables();
@@ -2991,8 +2991,8 @@
}
void StreamingConstantEvaluator::EvaluatePropertyGet() {
- TokenPosition position = builder_->ReadPosition(); // read position.
- builder_->ReadFlags(); // read flags.
+ const TokenPosition position = builder_->ReadPosition(); // read position.
+ builder_->ReadFlags(); // read flags.
intptr_t expression_offset = builder_->ReaderOffset();
builder_->SkipExpression(); // read receiver.
StringIndex name = builder_->ReadNameAsStringIndex(); // read name.
@@ -3751,7 +3751,7 @@
}
}
-bool StreamingFlowGraphBuilder::ReadUntilFunctionNode(
+void StreamingFlowGraphBuilder::ReadUntilFunctionNode(
ParsedFunction* parsed_function) {
const Tag tag = PeekTag();
if (tag == kProcedure) {
@@ -3767,16 +3767,10 @@
parsed_function->MarkForwardingStub(
procedure_helper.forwarding_stub_super_target_);
}
- if (parsed_function != NULL && flow_graph_builder_ != nullptr &&
- procedure_helper.IsNoSuchMethodForwarder()) {
- parsed_function->set_is_no_such_method_forwarder(true);
- }
- return procedure_helper.IsNoSuchMethodForwarder();
// Now at start of FunctionNode.
} else if (tag == kConstructor) {
ConstructorHelper constructor_helper(this);
constructor_helper.ReadUntilExcluding(ConstructorHelper::kFunction);
- return false;
// Now at start of FunctionNode.
// Notice that we also have a list of initializers after that!
} else if (tag == kFunctionNode) {
@@ -3785,7 +3779,6 @@
ReportUnexpectedTag("a procedure, a constructor or a function node", tag);
UNREACHABLE();
}
- return false;
}
StringIndex StreamingFlowGraphBuilder::GetNameFromVariableDeclaration(
@@ -3819,7 +3812,8 @@
*parsed_function(), normal_entry, Compiler::kNoOSRDeoptId);
Fragment body(normal_entry);
- body += flow_graph_builder_->CheckStackOverflowInPrologue();
+ body +=
+ flow_graph_builder_->CheckStackOverflowInPrologue(field_helper.position_);
if (field_helper.IsConst()) {
// this will (potentially) read the initializer, but reset the position.
body += Constant(constant_evaluator_.EvaluateExpression(ReaderOffset()));
@@ -4191,7 +4185,8 @@
*parsed_function(), normal_entry, Compiler::kNoOSRDeoptId);
Fragment body(instruction_cursor);
- body += flow_graph_builder_->CheckStackOverflowInPrologue();
+ body +=
+ flow_graph_builder_->CheckStackOverflowInPrologue(function.token_pos());
// Forwarding the type parameters is complicated by our approach to
// implementing the partial tearoff instantiation.
@@ -4347,7 +4342,7 @@
Compiler::kNoOSRDeoptId);
Fragment body(instruction_cursor);
- body += B->CheckStackOverflowInPrologue();
+ body += B->CheckStackOverflowInPrologue(function.token_pos());
// If we are inside the tearoff wrapper function (implicit closure), we need
// to extract the receiver from the context. We just replace it directly on
@@ -4724,7 +4719,8 @@
}
if (!dart_function.is_native())
- body += flow_graph_builder_->CheckStackOverflowInPrologue();
+ body += flow_graph_builder_->CheckStackOverflowInPrologue(
+ dart_function.token_pos());
intptr_t context_size =
parsed_function()->node_sequence()->scope()->num_context_variables();
if (context_size > 0) {
@@ -5028,17 +5024,19 @@
switch (function.kind()) {
case RawFunction::kRegularFunction:
case RawFunction::kImplicitClosureFunction:
- if (ReadUntilFunctionNode(parsed_function())) {
+ case RawFunction::kGetterFunction:
+ case RawFunction::kSetterFunction: {
+ ReadUntilFunctionNode(parsed_function());
+ if (function.is_no_such_method_forwarder()) {
return BuildGraphOfNoSuchMethodForwarder(
function, function.IsImplicitClosureFunction());
} else if (function.IsImplicitClosureFunction()) {
return BuildGraphOfImplicitClosureFunction(function);
}
+ }
// fallthrough intended
case RawFunction::kClosureFunction:
- case RawFunction::kConvertedClosureFunction:
- case RawFunction::kGetterFunction:
- case RawFunction::kSetterFunction: {
+ case RawFunction::kConvertedClosureFunction: {
ReadUntilFunctionNode(parsed_function()); // read until function node.
return BuildGraphOfFunction(false);
}
@@ -6377,8 +6375,8 @@
return flow_graph_builder_->StoreIndexed(class_id);
}
-Fragment StreamingFlowGraphBuilder::CheckStackOverflow() {
- return flow_graph_builder_->CheckStackOverflow();
+Fragment StreamingFlowGraphBuilder::CheckStackOverflow(TokenPosition position) {
+ return flow_graph_builder_->CheckStackOverflow(position);
}
Fragment StreamingFlowGraphBuilder::CloneContext(
@@ -8628,7 +8626,7 @@
Fragment StreamingFlowGraphBuilder::BuildWhileStatement() {
loop_depth_inc();
- ReadPosition(); // read position.
+ const TokenPosition position = ReadPosition(); // read position.
bool negate;
Fragment condition = TranslateCondition(&negate); // read condition.
@@ -8645,7 +8643,7 @@
body += Goto(join);
Fragment loop(join);
- loop += CheckStackOverflow();
+ loop += CheckStackOverflow(position);
loop += condition;
entry = new (Z) GotoInstr(join, Thread::Current()->GetNextDeoptId());
} else {
@@ -8658,8 +8656,8 @@
Fragment StreamingFlowGraphBuilder::BuildDoStatement() {
loop_depth_inc();
- ReadPosition(); // read position.
- Fragment body = BuildStatement(); // read body.
+ const TokenPosition position = ReadPosition(); // read position.
+ Fragment body = BuildStatement(); // read body.
if (body.is_closed()) {
SkipExpression(); // read condition.
@@ -8670,7 +8668,7 @@
bool negate;
JoinEntryInstr* join = BuildJoinEntry();
Fragment loop(join);
- loop += CheckStackOverflow();
+ loop += CheckStackOverflow(position);
loop += body;
loop += TranslateCondition(&negate); // read condition.
TargetEntryInstr* loop_repeat;
@@ -8688,7 +8686,7 @@
Fragment StreamingFlowGraphBuilder::BuildForStatement() {
intptr_t offset = ReaderOffset() - 1; // Include the tag.
- ReadPosition(); // read position.
+ const TokenPosition position = ReadPosition(); // read position.
Fragment declarations;
@@ -8735,7 +8733,7 @@
body += Goto(join);
Fragment loop(join);
- loop += CheckStackOverflow();
+ loop += CheckStackOverflow(position);
loop += condition;
} else {
declarations += condition;
@@ -8753,7 +8751,7 @@
Fragment StreamingFlowGraphBuilder::BuildForInStatement(bool async) {
intptr_t offset = ReaderOffset() - 1; // Include the tag.
- ReadPosition(); // read position.
+ const TokenPosition position = ReadPosition(); // read position.
TokenPosition body_position = ReadPosition(); // read body position.
intptr_t variable_kernel_position = ReaderOffset() + data_program_offset_;
SkipVariableDeclaration(); // read variable.
@@ -8800,7 +8798,7 @@
body += Goto(join);
Fragment loop(join);
- loop += CheckStackOverflow();
+ loop += CheckStackOverflow(position);
loop += condition;
} else {
instructions += condition;
diff --git a/runtime/vm/compiler/frontend/kernel_binary_flowgraph.h b/runtime/vm/compiler/frontend/kernel_binary_flowgraph.h
index 7db1719..0a16a94 100644
--- a/runtime/vm/compiler/frontend/kernel_binary_flowgraph.h
+++ b/runtime/vm/compiler/frontend/kernel_binary_flowgraph.h
@@ -1050,9 +1050,7 @@
// If a 'ParsedFunction' is provided for 'set_forwarding_stub', this method
// will attach the forwarding stub target reference to the parsed function if
// it crosses a procedure node for a concrete forwarding stub.
- //
- // Returns 'true' if discovered a no-such-method forwarder.
- bool ReadUntilFunctionNode(ParsedFunction* set_forwarding_stub = NULL);
+ void ReadUntilFunctionNode(ParsedFunction* set_forwarding_stub = NULL);
intptr_t ReadListLength();
enum DispatchCategory { Interface, ViaThis, Closure, DynamicDispatch };
@@ -1251,7 +1249,7 @@
Fragment InstantiateType(const AbstractType& type);
Fragment CreateArray();
Fragment StoreIndexed(intptr_t class_id);
- Fragment CheckStackOverflow();
+ Fragment CheckStackOverflow(TokenPosition position);
Fragment CloneContext(intptr_t num_context_variables);
Fragment TranslateFinallyFinalizers(TryFinallyBlock* outer_finally,
intptr_t target_context_depth);
diff --git a/runtime/vm/compiler/frontend/kernel_to_il.cc b/runtime/vm/compiler/frontend/kernel_to_il.cc
index a354661..0372fa1 100644
--- a/runtime/vm/compiler/frontend/kernel_to_il.cc
+++ b/runtime/vm/compiler/frontend/kernel_to_il.cc
@@ -1219,19 +1219,20 @@
return Fragment(body.entry, entry);
}
-Fragment FlowGraphBuilder::CheckStackOverflowInPrologue() {
+Fragment FlowGraphBuilder::CheckStackOverflowInPrologue(
+ TokenPosition position) {
if (IsInlining()) {
// If we are inlining don't actually attach the stack check. We must still
// create the stack check in order to allocate a deopt id.
- CheckStackOverflow();
+ CheckStackOverflow(position);
return Fragment();
}
- return CheckStackOverflow();
+ return CheckStackOverflow(position);
}
-Fragment FlowGraphBuilder::CheckStackOverflow() {
- return Fragment(new (Z) CheckStackOverflowInstr(
- TokenPosition::kNoSource, loop_depth_, GetNextDeoptId()));
+Fragment FlowGraphBuilder::CheckStackOverflow(TokenPosition position) {
+ return Fragment(
+ new (Z) CheckStackOverflowInstr(position, loop_depth_, GetNextDeoptId()));
}
Fragment FlowGraphBuilder::CloneContext(intptr_t num_context_variables) {
@@ -2331,7 +2332,7 @@
graph_entry_ = new (Z)
GraphEntryInstr(*parsed_function_, normal_entry, Compiler::kNoOSRDeoptId);
Fragment body(normal_entry);
- body += CheckStackOverflowInPrologue();
+ body += CheckStackOverflowInPrologue(method.token_pos());
body += BuildImplicitClosureCreation(function);
body += Return(TokenPosition::kNoSource);
@@ -2368,7 +2369,7 @@
parsed_function_->set_default_parameter_values(default_values);
Fragment body(instruction_cursor);
- body += CheckStackOverflowInPrologue();
+ body += CheckStackOverflowInPrologue(function.token_pos());
// The receiver is the first argument to noSuchMethod, and it is the first
// argument passed to the dispatcher function.
@@ -2503,7 +2504,7 @@
GraphEntryInstr(*parsed_function_, normal_entry, Compiler::kNoOSRDeoptId);
Fragment body(instruction_cursor);
- body += CheckStackOverflowInPrologue();
+ body += CheckStackOverflowInPrologue(function.token_pos());
LocalScope* scope = parsed_function_->node_sequence()->scope();
diff --git a/runtime/vm/compiler/frontend/kernel_to_il.h b/runtime/vm/compiler/frontend/kernel_to_il.h
index 50c607c..efb5e13 100644
--- a/runtime/vm/compiler/frontend/kernel_to_il.h
+++ b/runtime/vm/compiler/frontend/kernel_to_il.h
@@ -567,7 +567,7 @@
// for expression stack locations - only real local variables are supported.
// This means that you can't use MakeTemporary in a way that would require
// a Phi in SSA form. For example example below will be miscompiled or
- // will crash debug VM with assertion when building SSA for optimizing
+ // will crash debug VM with assertion when building SSA for optimizing
// compiler:
//
// t = MakeTemporary()
@@ -714,8 +714,8 @@
intptr_t handler_index,
bool needs_stacktrace);
Fragment TryCatch(int try_handler_index);
- Fragment CheckStackOverflowInPrologue();
- Fragment CheckStackOverflow();
+ Fragment CheckStackOverflowInPrologue(TokenPosition position);
+ Fragment CheckStackOverflow(TokenPosition position);
Fragment CloneContext(intptr_t num_context_variables);
Fragment CreateArray();
Fragment InstanceCall(TokenPosition position,
diff --git a/runtime/vm/dart_api_impl_test.cc b/runtime/vm/dart_api_impl_test.cc
index 728a7db..9a55de7 100644
--- a/runtime/vm/dart_api_impl_test.cc
+++ b/runtime/vm/dart_api_impl_test.cc
@@ -247,7 +247,7 @@
Dart_StringToCString(function_name, &cstr);
EXPECT_STREQ(top_frame_func_name, cstr);
Dart_StringToCString(script_url, &cstr);
- EXPECT_STREQ("test-lib", cstr);
+ EXPECT_STREQ(TestCase::url(), cstr);
EXPECT_EQ(expected_line_number, line_number);
EXPECT_EQ(expected_column_number, column_number);
@@ -259,15 +259,19 @@
}
TEST_CASE(DartAPI_StackOverflowStackTraceInfoBraceFunction1) {
+ int line = 2;
+ int col = FLAG_use_dart_frontend ? 10 : 3;
VerifyStackOverflowStackTraceInfo(
"class C {\n"
" static foo(int i) { foo(i); }\n"
"}\n"
"testMain() => C.foo(10);\n",
- "C.foo", "testMain", 2, 21);
+ "C.foo", "testMain", line, col);
}
TEST_CASE(DartAPI_StackOverflowStackTraceInfoBraceFunction2) {
+ int line = 2;
+ int col = FLAG_use_dart_frontend ? 10 : 3;
VerifyStackOverflowStackTraceInfo(
"class C {\n"
" static foo(int i, int j) {\n"
@@ -275,16 +279,18 @@
" }\n"
"}\n"
"testMain() => C.foo(10, 11);\n",
- "C.foo", "testMain", 2, 28);
+ "C.foo", "testMain", line, col);
}
TEST_CASE(DartAPI_StackOverflowStackTraceInfoArrowFunction) {
+ int line = 2;
+ int col = FLAG_use_dart_frontend ? 10 : 3;
VerifyStackOverflowStackTraceInfo(
"class C {\n"
" static foo(int i) => foo(i);\n"
"}\n"
"testMain() => C.foo(10);\n",
- "C.foo", "testMain", 2, 21);
+ "C.foo", "testMain", line, col);
}
TEST_CASE(DartAPI_OutOfMemoryStackTraceInfo) {
@@ -6868,7 +6874,7 @@
"void callPort(SendPort port) {\n"
" var receivePort = new RawReceivePort();\n"
" var replyPort = receivePort.sendPort;\n"
- " port.send([replyPort]);\n"
+ " port.send(<dynamic>[replyPort]);\n"
" receivePort.handler = (message) {\n"
" receivePort.close();\n"
" throw new Exception(message);\n"
@@ -6942,7 +6948,7 @@
"void callPort(SendPort port) {\n"
" var receivePort = new RawReceivePort();\n"
" var replyPort = receivePort.sendPort;\n"
- " port.send([replyPort]);\n"
+ " port.send(<dynamic>[replyPort]);\n"
" receivePort.handler = (message) {\n"
" receivePort.close();\n"
" throw new Exception(message);\n"
@@ -7008,7 +7014,7 @@
" var receivePort = new RawReceivePort();\n"
" var replyPort = receivePort.sendPort;\n"
" port.send(null);\n"
- " port.send([replyPort]);\n"
+ " port.send(<dynamic>[replyPort]);\n"
" receivePort.handler = (message) {\n"
" receivePort.close();\n"
" throw new Exception(message);\n"
@@ -7060,7 +7066,7 @@
" var receivePort = new RawReceivePort();\n"
" var replyPort = receivePort.sendPort;\n"
" port.send(321);\n"
- " port.send([replyPort]);\n"
+ " port.send(<dynamic>[replyPort]);\n"
" receivePort.handler = (message) {\n"
" receivePort.close();\n"
" throw new Exception(message);\n"
diff --git a/runtime/vm/kernel_loader.cc b/runtime/vm/kernel_loader.cc
index 490d3cd..b7fabf3 100644
--- a/runtime/vm/kernel_loader.cc
+++ b/runtime/vm/kernel_loader.cc
@@ -1380,7 +1380,6 @@
const Object& script_class =
ClassForScriptAt(owner, procedure_helper.source_uri_index_);
RawFunction::Kind kind = GetFunctionType(procedure_helper.kind_);
- is_no_such_method_forwarder &= kind == RawFunction::kRegularFunction;
Function& function = Function::ZoneHandle(
Z, Function::New(name, kind,
!is_method, // is_static
@@ -1388,11 +1387,7 @@
is_abstract && !is_no_such_method_forwarder, is_external,
native_name != NULL, // is_native
script_class, procedure_helper.position_));
- if (is_no_such_method_forwarder) {
- // Not inlinable yet because its implementation is generic against the call
- // site in a way that makes assumptions about the stack frame layout.
- function.set_is_inlinable(false);
- }
+ function.set_is_no_such_method_forwarder(is_no_such_method_forwarder);
function.set_end_token_pos(procedure_helper.end_position_);
functions_.Add(&function);
function.set_kernel_offset(procedure_offset);
diff --git a/runtime/vm/object.cc b/runtime/vm/object.cc
index ea5328d..ed5d21c 100644
--- a/runtime/vm/object.cc
+++ b/runtime/vm/object.cc
@@ -6216,26 +6216,33 @@
StoreNonPointer(&raw_ptr()->kind_tag_, static_cast<uint32_t>(value));
}
+void Function::set_packed_fields(uint32_t packed_fields) const {
+ StoreNonPointer(&raw_ptr()->packed_fields_, packed_fields);
+}
+
void Function::set_num_fixed_parameters(intptr_t value) const {
ASSERT(value >= 0);
- ASSERT(Utils::IsInt(16, value));
- StoreNonPointer(&raw_ptr()->num_fixed_parameters_,
- static_cast<int16_t>(value));
+ ASSERT(Utils::IsUint(RawFunction::kMaxFixedParametersBits, value));
+ const uint32_t* original = &raw_ptr()->packed_fields_;
+ StoreNonPointer(original, RawFunction::PackedNumFixedParameters::update(
+ value, *original));
}
-void Function::set_num_optional_parameters(intptr_t value) const {
- // A positive value indicates positional params, a negative one named params.
- ASSERT(Utils::IsInt(16, value));
- StoreNonPointer(&raw_ptr()->num_optional_parameters_,
- static_cast<int16_t>(value));
+void Function::set_is_no_such_method_forwarder(bool value) const {
+ const uint32_t* original = &raw_ptr()->packed_fields_;
+ StoreNonPointer(original, RawFunction::PackedIsNoSuchMethodForwarder::update(
+ value ? 1 : 0, *original));
}
-void Function::SetNumOptionalParameters(intptr_t num_optional_parameters,
+void Function::SetNumOptionalParameters(intptr_t value,
bool are_optional_positional) const {
- ASSERT(num_optional_parameters >= 0);
- set_num_optional_parameters(are_optional_positional
- ? num_optional_parameters
- : -num_optional_parameters);
+ ASSERT(Utils::IsUint(RawFunction::kMaxOptionalParametersBits, value));
+ uint32_t packed_fields = raw_ptr()->packed_fields_;
+ packed_fields = RawFunction::PackedHasNamedOptionalParameters::update(
+ !are_optional_positional, packed_fields);
+ packed_fields =
+ RawFunction::PackedNumOptionalParameters::update(value, packed_fields);
+ set_packed_fields(packed_fields);
}
bool Function::IsOptimizable() const {
@@ -6268,10 +6275,12 @@
bool Function::CanBeInlined() const {
#if defined(PRODUCT)
- return is_inlinable() && !is_external() && !is_generated_body();
+ return is_inlinable() && !is_external() && !is_generated_body() &&
+ !is_no_such_method_forwarder();
#else
Thread* thread = Thread::Current();
return is_inlinable() && !is_external() && !is_generated_body() &&
+ !is_no_such_method_forwarder() &&
!thread->isolate()->debugger()->HasBreakpoint(*this, thread->zone());
#endif
}
@@ -6949,7 +6958,8 @@
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.SetNumOptionalParameters(0, false);
+ result.set_is_no_such_method_forwarder(false);
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));
@@ -7187,13 +7197,13 @@
closure_function.SetParameterNameAt(i, param_name);
}
closure_function.set_kernel_offset(kernel_offset());
+ closure_function.set_is_no_such_method_forwarder(
+ is_no_such_method_forwarder());
// In strong mode, change covariant parameter types to Object in the implicit
// closure of a method compiled by kernel.
// The VM's parser erases covariant types immediately in strong mode.
- do {
- if (is_static() || kernel_offset() == 0) break;
-
+ if (thread->isolate()->strong() && !is_static() && kernel_offset() > 0) {
const Script& function_script = Script::Handle(zone, script());
kernel::TranslationHelper translation_helper(thread);
kernel::StreamingFlowGraphBuilder builder(
@@ -7202,9 +7212,7 @@
translation_helper.InitFromScript(function_script);
builder.SetOffset(kernel_offset());
- closure_function.set_is_inlinable(!builder.ReadUntilFunctionNode(NULL));
-
- if (!thread->isolate()->strong()) break;
+ builder.ReadUntilFunctionNode();
kernel::FunctionNodeHelper fn_helper(&builder);
@@ -7236,7 +7244,7 @@
object_type);
}
}
- } while (false);
+ }
const Type& signature_type =
Type::Handle(zone, closure_function.SignatureType());
if (!signature_type.IsFinalized()) {
diff --git a/runtime/vm/object.h b/runtime/vm/object.h
index 3581349..463013e 100644
--- a/runtime/vm/object.h
+++ b/runtime/vm/object.h
@@ -2419,34 +2419,47 @@
#endif
}
+ bool is_no_such_method_forwarder() const {
+ return RawFunction::PackedIsNoSuchMethodForwarder::decode(
+ raw_ptr()->packed_fields_);
+ }
+
+ void set_is_no_such_method_forwarder(bool value) const;
+
intptr_t num_fixed_parameters() const {
- return raw_ptr()->num_fixed_parameters_;
+ return RawFunction::PackedNumFixedParameters::decode(
+ raw_ptr()->packed_fields_);
}
void set_num_fixed_parameters(intptr_t value) const;
+ uint32_t packed_fields() const { return raw_ptr()->packed_fields_; }
+ void set_packed_fields(uint32_t packed_fields) const;
+
bool HasOptionalParameters() const {
- return raw_ptr()->num_optional_parameters_ != 0;
- }
- bool HasOptionalPositionalParameters() const {
- return raw_ptr()->num_optional_parameters_ > 0;
+ return RawFunction::PackedNumOptionalParameters::decode(
+ raw_ptr()->packed_fields_) > 0;
}
bool HasOptionalNamedParameters() const {
- return raw_ptr()->num_optional_parameters_ < 0;
+ return HasOptionalParameters() &&
+ RawFunction::PackedHasNamedOptionalParameters::decode(
+ raw_ptr()->packed_fields_);
+ }
+ bool HasOptionalPositionalParameters() const {
+ return HasOptionalParameters() && !HasOptionalNamedParameters();
}
intptr_t NumOptionalParameters() const {
- const intptr_t num_opt_params = raw_ptr()->num_optional_parameters_;
- return (num_opt_params >= 0) ? num_opt_params : -num_opt_params;
+ return RawFunction::PackedNumOptionalParameters::decode(
+ raw_ptr()->packed_fields_);
}
void SetNumOptionalParameters(intptr_t num_optional_parameters,
bool are_optional_positional) const;
intptr_t NumOptionalPositionalParameters() const {
- const intptr_t num_opt_params = raw_ptr()->num_optional_parameters_;
- return (num_opt_params > 0) ? num_opt_params : 0;
+ return HasOptionalPositionalParameters() ? NumOptionalParameters() : 0;
}
+
intptr_t NumOptionalNamedParameters() const {
- const intptr_t num_opt_params = raw_ptr()->num_optional_parameters_;
- return (num_opt_params < 0) ? -num_opt_params : 0;
+ return HasOptionalNamedParameters() ? NumOptionalParameters() : 0;
}
intptr_t NumParameters() const;
diff --git a/runtime/vm/parser.cc b/runtime/vm/parser.cc
index 576a194..129152f 100644
--- a/runtime/vm/parser.cc
+++ b/runtime/vm/parser.cc
@@ -168,8 +168,7 @@
}
ParsedFunction::ParsedFunction(Thread* thread, const Function& function)
- : is_no_such_method_forwarder_(false),
- thread_(thread),
+ : thread_(thread),
function_(function),
code_(Code::Handle(zone(), function.unoptimized_code())),
node_sequence_(NULL),
@@ -7789,8 +7788,10 @@
ASSERT((params->num_optional_parameters > 0) ==
(params->has_optional_positional_parameters ||
params->has_optional_named_parameters));
- if (!Utils::IsInt(16, params->num_fixed_parameters) ||
- !Utils::IsInt(16, params->num_optional_parameters)) {
+ if (!Utils::IsUint(RawFunction::kMaxFixedParametersBits,
+ params->num_fixed_parameters) ||
+ !Utils::IsUint(RawFunction::kMaxOptionalParametersBits,
+ params->num_optional_parameters)) {
const Script& script = Script::Handle(Class::Handle(func.Owner()).script());
Report::MessageF(Report::kError, script, func.token_pos(),
Report::AtLocation, "too many formal parameters");
diff --git a/runtime/vm/parser.h b/runtime/vm/parser.h
index 75baa8d..12d0557 100644
--- a/runtime/vm/parser.h
+++ b/runtime/vm/parser.h
@@ -220,17 +220,7 @@
return raw_parameters_[i];
}
- bool is_no_such_method_forwarder() const {
- return is_no_such_method_forwarder_;
- }
-
- void set_is_no_such_method_forwarder(bool value) {
- is_no_such_method_forwarder_ = value;
- }
-
private:
- bool is_no_such_method_forwarder_;
-
Thread* thread_;
const Function& function_;
Code& code_;
diff --git a/runtime/vm/raw_object.h b/runtime/vm/raw_object.h
index da39187..420ed6c 100644
--- a/runtime/vm/raw_object.h
+++ b/runtime/vm/raw_object.h
@@ -881,6 +881,9 @@
kAsyncGen = kAsyncBit | kGeneratorBit,
};
+ static constexpr intptr_t kMaxFixedParametersBits = 15;
+ static constexpr intptr_t kMaxOptionalParametersBits = 15;
+
private:
// So that the SkippedCodeFunctions::DetachCode can null out the code fields.
friend class SkippedCodeFunctions;
@@ -933,8 +936,24 @@
NOT_IN_PRECOMPILED(TokenPosition token_pos_);
NOT_IN_PRECOMPILED(TokenPosition end_token_pos_);
uint32_t kind_tag_; // See Function::KindTagBits.
- int16_t num_fixed_parameters_;
- int16_t num_optional_parameters_; // > 0: positional; < 0: named.
+ uint32_t packed_fields_;
+
+ typedef BitField<uint32_t, bool, 0, 1> PackedIsNoSuchMethodForwarder;
+ typedef BitField<uint32_t, bool, PackedIsNoSuchMethodForwarder::kNextBit, 1>
+ PackedHasNamedOptionalParameters;
+ typedef BitField<uint32_t,
+ uint16_t,
+ PackedHasNamedOptionalParameters::kNextBit,
+ kMaxFixedParametersBits>
+ PackedNumFixedParameters;
+ typedef BitField<uint32_t,
+ uint16_t,
+ PackedNumFixedParameters::kNextBit,
+ kMaxOptionalParametersBits>
+ PackedNumOptionalParameters;
+ static_assert(PackedNumOptionalParameters::kNextBit <=
+ kBitsPerWord * sizeof(decltype(packed_fields_)),
+ "RawFunction::packed_fields_ bitfields don't align.");
#define JIT_FUNCTION_COUNTERS(F) \
F(intptr_t, intptr_t, kernel_offset) \
diff --git a/runtime/vm/raw_object_snapshot.cc b/runtime/vm/raw_object_snapshot.cc
index 3c0f7a5..e738756 100644
--- a/runtime/vm/raw_object_snapshot.cc
+++ b/runtime/vm/raw_object_snapshot.cc
@@ -738,8 +738,7 @@
#if !defined(DART_PRECOMPILED_RUNTIME)
kernel_offset = reader->Read<int32_t>();
#endif
- func.set_num_fixed_parameters(reader->Read<int16_t>());
- func.set_num_optional_parameters(reader->Read<int16_t>());
+ func.set_packed_fields(reader->Read<uint32_t>());
func.set_kind_tag(reader->Read<uint32_t>());
func.set_token_pos(TokenPosition::SnapshotDecode(token_pos));
func.set_end_token_pos(TokenPosition::SnapshotDecode(end_token_pos));
@@ -809,8 +808,7 @@
writer->Write<int32_t>(ptr()->end_token_pos_.SnapshotEncode());
writer->Write<int32_t>(ptr()->kernel_offset_);
#endif
- writer->Write<int16_t>(ptr()->num_fixed_parameters_);
- writer->Write<int16_t>(ptr()->num_optional_parameters_);
+ writer->Write<uint32_t>(ptr()->packed_fields_);
writer->Write<uint32_t>(ptr()->kind_tag_);
#if !defined(DART_PRECOMPILED_RUNTIME)
if (is_optimized) {
diff --git a/sdk/BUILD.gn b/sdk/BUILD.gn
index b3e25e2..c22d567 100644
--- a/sdk/BUILD.gn
+++ b/sdk/BUILD.gn
@@ -922,6 +922,17 @@
]
}
+# This rule copies the dartdoc_options.yaml file.
+copy("copy_dartdoc_options") {
+ visibility = [ ":create_common_sdk" ]
+ sources = [
+ "../dartdoc_options.yaml",
+ ]
+ outputs = [
+ "$root_out_dir/dart-sdk/dartdoc_options.yaml",
+ ]
+}
+
# This rule copies the API readme file to lib/
copy("copy_api_readme") {
visibility = [ ":create_common_sdk" ]
@@ -942,6 +953,7 @@
":copy_api_readme",
":copy_dart",
":copy_dartdoc_files",
+ ":copy_dartdoc_options",
":copy_headers",
":copy_libraries_dart",
":copy_license",
diff --git a/sdk/lib/_internal/js_runtime/lib/convert_patch.dart b/sdk/lib/_internal/js_runtime/lib/convert_patch.dart
index 994604a..771a73a 100644
--- a/sdk/lib/_internal/js_runtime/lib/convert_patch.dart
+++ b/sdk/lib/_internal/js_runtime/lib/convert_patch.dart
@@ -8,7 +8,7 @@
import 'dart:_foreign_helper' show JS;
import 'dart:_interceptors' show JSExtendableArray;
import 'dart:_internal' show MappedIterable, ListIterable;
-import 'dart:collection' show Maps, LinkedHashMap, MapBase;
+import 'dart:collection' show LinkedHashMap, MapBase;
import 'dart:_native_typed_data' show NativeUint8List;
/**
diff --git a/sdk/lib/_internal/js_runtime/lib/js_helper.dart b/sdk/lib/_internal/js_runtime/lib/js_helper.dart
index a947a5f..a57a9d9 100644
--- a/sdk/lib/_internal/js_runtime/lib/js_helper.dart
+++ b/sdk/lib/_internal/js_runtime/lib/js_helper.dart
@@ -96,6 +96,14 @@
'returns:bool;effects:none;depends:none', JsBuiltin.isFunctionType, type);
}
+/// Returns true if the given [type] is a FutureOr type object.
+// TODO(floitsch): move this to foreign_helper.dart or similar.
+@ForceInline()
+bool isDartFutureOrType(Object type) {
+ return JS_BUILTIN(
+ 'returns:bool;effects:none;depends:none', JsBuiltin.isFutureOrType, type);
+}
+
/// Retrieves the class name from type information stored on the constructor of
/// [type].
// TODO(floitsch): move this to foreign_helper.dart or similar.
@@ -3514,6 +3522,12 @@
throw new TypeErrorImplementation.fromMessage(message);
}
+futureOrTest(o, futureOrRti) => checkSubtypeOfRuntimeType(o, futureOrRti);
+
+futureOrCheck(o, futureOrRti) => assertSubtypeOfRuntimeType(o, futureOrRti);
+
+futureOrCast(o, futureOrRti) => subtypeOfRuntimeTypeCast(o, futureOrRti);
+
@NoInline()
void checkDeferredIsLoaded(String loadId, String uri) {
if (!_loadedLibraries.contains(loadId)) {
diff --git a/sdk/lib/_internal/js_runtime/lib/js_rti.dart b/sdk/lib/_internal/js_runtime/lib/js_rti.dart
index 9c20637..b334336 100644
--- a/sdk/lib/_internal/js_runtime/lib/js_rti.dart
+++ b/sdk/lib/_internal/js_runtime/lib/js_rti.dart
@@ -233,11 +233,14 @@
}
return '${genericContext[genericContext.length - index - 1]}';
}
- String functionPropertyName = JS_GET_NAME(JsGetName.FUNCTION_TYPE_TAG);
- if (JS('bool', 'typeof #[#] != "undefined"', rti, functionPropertyName)) {
+ if (isDartFunctionType(rti)) {
// TODO(sra): If there is a typedef tag, use the typedef name.
return _functionRtiToStringV2(rti, genericContext);
}
+ if (isDartFutureOrType(rti)) {
+ var typeArgument = getFutureOrArgument(rti);
+ return 'FutureOr<${runtimeTypeToStringV2(typeArgument, genericContext)}>';
+ }
// We should not get here.
return 'unknown-reified-type';
}
@@ -703,15 +706,53 @@
return invokeOn(signature, context, typeArguments);
}
-/**
- * Returns `true` if the runtime type representation [type] is a supertype of
- * [Null].
- */
+/// Returns `true` if the runtime type representation [type] is a supertype of
+/// [Null].
+@ForceInline()
bool isSupertypeOfNull(var type) {
+ return JS_GET_FLAG('STRONG_MODE')
+ ? isSupertypeOfNullBase(type) || isSupertypeOfNullRecursive(type)
+ : isSupertypeOfNullBase(type);
+}
+
+/// Returns `true` if the runtime type representation [type] is a simple
+/// supertype of [Null].
+///
+/// This method doesn't handle `FutureOr<Null>`. This is handle by
+/// [isSupertypeOfNullRecursive] because it requires a recursive check.
+@ForceInline()
+bool isSupertypeOfNullBase(var type) {
// `null` means `dynamic`.
return type == null || isDartObjectTypeRti(type) || isNullTypeRti(type);
}
+/// Returns `true` if the runtime type representation [type] is a `FutureOr`
+/// type that is a supertype of [Null].
+///
+/// This method is recursive to be able to handle both `FutureOr<Null>` and
+/// `FutureOr<FutureOr<Null>>` etc.
+bool isSupertypeOfNullRecursive(var type) {
+ if (isDartFutureOrType(type)) {
+ var typeArgument = getFutureOrArgument(type);
+ return isSupertypeOfNullBase(type) ||
+ isSupertypeOfNullRecursive(typeArgument);
+ }
+ return false;
+}
+
+/// Returns the type argument of the `FutureOr` runtime type representation
+/// [type].
+///
+/// For instance `num` of `FutureOr<num>`.
+@ForceInline()
+Object getFutureOrArgument(var type) {
+ assert(isDartFutureOrType(type));
+ var typeArgumentTag = JS_GET_NAME(JsGetName.FUTURE_OR_TYPE_ARGUMENT_TAG);
+ return hasField(type, typeArgumentTag)
+ ? getField(type, typeArgumentTag)
+ : null;
+}
+
/**
* Tests whether the Dart object [o] is a subtype of the runtime type
* representation [t].
@@ -850,7 +891,14 @@
// TODO(sra): void is a top type.
// [s] is a top type?
- if (s == null) return false;
+ if (s == null) {
+ if (isDartFutureOrType(t)) {
+ // [t] is FutureOr<T>. Check [s] <: T.
+ var tTypeArgument = getFutureOrArgument(t);
+ return isSubtypeV2(s, sEnv, tTypeArgument, tEnv);
+ }
+ return false;
+ }
// Generic function type parameters must match exactly, which would have
// exited earlier. The de Bruijn indexing ensures the representation as a
@@ -874,8 +922,39 @@
}
// Get the object describing the class and check for the subtyping flag
- // constructed from the type of [t].
+ // constructed from the type of [s].
var typeOfS = isJsArray(s) ? getIndex(s, 0) : s;
+
+ if (isDartFutureOrType(t)) {
+ // [t] is FutureOr<T>
+ var tTypeArgument = getFutureOrArgument(t);
+ if (isDartFutureOrType(s)) {
+ // [S] is FutureOr<S>. Check S <: T
+ var sTypeArgument = getFutureOrArgument(s);
+ return isSubtypeV2(sTypeArgument, sEnv, tTypeArgument, tEnv);
+ } else if (isSubtypeV2(s, sEnv, tTypeArgument, tEnv)) {
+ // `true` because [s] <: T.
+ return true;
+ } else {
+ // Check [s] <: Future<T>.
+ String futureClass = JS_GET_NAME(JsGetName.FUTURE_CLASS_TYPE_NAME);
+ if (!builtinIsSubtype(typeOfS, futureClass)) {
+ // [s] doesn't implement Future.
+ return false;
+ }
+ var typeOfSPrototype = JS('', '#.prototype', typeOfS);
+ var field = '${JS_GET_NAME(JsGetName.OPERATOR_AS_PREFIX)}${futureClass}';
+ var futureSubstitution = getField(typeOfSPrototype, field);
+ var futureArguments = substitute(futureSubstitution, getArguments(s));
+ var futureArgument =
+ isJsArray(futureArguments) ? getIndex(futureArguments, 0) : null;
+ // [s] implements Future<S>. Check S <: T.
+ return isSubtypeV2(futureArgument, sEnv, tTypeArgument, tEnv);
+ }
+ }
+
+ // Get the object describing the class and check for the subtyping flag
+ // constructed from the type of [t].
var typeOfT = isJsArray(t) ? getIndex(t, 0) : t;
// Check for a subtyping flag.
@@ -1128,8 +1207,8 @@
// Check the remaining parameters of [t] with the first optional parameters
// of [s].
for (; tPos < tParametersLen; sPos++, tPos++) {
- if (!isSubtypeV2(getIndex(tOptionalParameterTypes, tPos), tEnv,
- getIndex(sParameterTypes, sPos), sEnv)) {
+ if (!isSubtypeV2(getIndex(tParameterTypes, tPos), tEnv,
+ getIndex(sOptionalParameterTypes, sPos), sEnv)) {
return false;
}
}
diff --git a/sdk/lib/_internal/js_runtime/lib/shared/embedded_names.dart b/sdk/lib/_internal/js_runtime/lib/shared/embedded_names.dart
index 174333c..3e07289 100644
--- a/sdk/lib/_internal/js_runtime/lib/shared/embedded_names.dart
+++ b/sdk/lib/_internal/js_runtime/lib/shared/embedded_names.dart
@@ -363,6 +363,16 @@
/// JavaScript.
FUNCTION_TYPE_NAMED_PARAMETERS_TAG,
+ /// Name used to tag a FutureOr type.
+ FUTURE_OR_TAG,
+
+ /// Name used to tag type arguments types in FutureOr type representations in
+ /// JavaScript.
+ FUTURE_OR_TYPE_ARGUMENT_TAG,
+
+ /// String representation of the type of the Future class.
+ FUTURE_CLASS_TYPE_NAME,
+
/// Field name used for determining if an object or its interceptor has
/// JavaScript indexing behavior.
IS_INDEXABLE_FIELD_NAME,
@@ -403,6 +413,11 @@
/// JS_BUILTIN('bool', JsBuiltin.isFunctionType, o)
isFunctionType,
+ /// Returns true if the given type is a FutureOr type.
+ ///
+ /// JS_BUILTIN('bool', JsBuiltin.isFutureOrType, o)
+ isFutureOrType,
+
/// Returns the JavaScript-constructor name given an rti encoding.
///
/// JS_BUILTIN('String', JsBuiltin.rawRtiToJsConstructorName, rti)
diff --git a/sdk/lib/cli/cli.dart b/sdk/lib/cli/cli.dart
index 1dc4ca7..9c19c3a 100644
--- a/sdk/lib/cli/cli.dart
+++ b/sdk/lib/cli/cli.dart
@@ -2,6 +2,7 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
+/// {@category VM}
library dart.cli;
import 'dart:async';
diff --git a/sdk/lib/collection/hash_map.dart b/sdk/lib/collection/hash_map.dart
index 08289f8..233f644 100644
--- a/sdk/lib/collection/hash_map.dart
+++ b/sdk/lib/collection/hash_map.dart
@@ -133,7 +133,7 @@
factory HashMap.fromIterable(Iterable iterable,
{K key(element), V value(element)}) {
Map<K, V> map = new HashMap<K, V>();
- Maps._fillMapWithMappedIterable(map, iterable, key, value);
+ MapBase._fillMapWithMappedIterable(map, iterable, key, value);
return map;
}
@@ -150,7 +150,7 @@
*/
factory HashMap.fromIterables(Iterable<K> keys, Iterable<V> values) {
Map<K, V> map = new HashMap<K, V>();
- Maps._fillMapWithIterables(map, keys, values);
+ MapBase._fillMapWithIterables(map, keys, values);
return map;
}
}
diff --git a/sdk/lib/collection/linked_hash_map.dart b/sdk/lib/collection/linked_hash_map.dart
index 76029c3..22fe5eb 100644
--- a/sdk/lib/collection/linked_hash_map.dart
+++ b/sdk/lib/collection/linked_hash_map.dart
@@ -121,7 +121,7 @@
factory LinkedHashMap.fromIterable(Iterable iterable,
{K key(element), V value(element)}) {
LinkedHashMap<K, V> map = new LinkedHashMap<K, V>();
- Maps._fillMapWithMappedIterable(map, iterable, key, value);
+ MapBase._fillMapWithMappedIterable(map, iterable, key, value);
return map;
}
@@ -138,7 +138,7 @@
*/
factory LinkedHashMap.fromIterables(Iterable<K> keys, Iterable<V> values) {
LinkedHashMap<K, V> map = new LinkedHashMap<K, V>();
- Maps._fillMapWithIterables(map, keys, values);
+ MapBase._fillMapWithIterables(map, keys, values);
return map;
}
}
diff --git a/sdk/lib/collection/maps.dart b/sdk/lib/collection/maps.dart
index 5967553..bdd775a 100644
--- a/sdk/lib/collection/maps.dart
+++ b/sdk/lib/collection/maps.dart
@@ -49,6 +49,48 @@
return result.toString();
}
+
+ static _id(x) => x;
+
+ /**
+ * Fills a [Map] with key/value pairs computed from [iterable].
+ *
+ * This method is used by [Map] classes in the named constructor
+ * `fromIterable`.
+ */
+ static void _fillMapWithMappedIterable(
+ Map map, Iterable iterable, key(element), value(element)) {
+ key ??= _id;
+ value ??= _id;
+
+ for (var element in iterable) {
+ map[key(element)] = value(element);
+ }
+ }
+
+ /**
+ * Fills a map by associating the [keys] to [values].
+ *
+ * This method is used by [Map] classes in the named constructor
+ * `fromIterables`.
+ */
+ static void _fillMapWithIterables(Map map, Iterable keys, Iterable values) {
+ Iterator keyIterator = keys.iterator;
+ Iterator valueIterator = values.iterator;
+
+ bool hasNextKey = keyIterator.moveNext();
+ bool hasNextValue = valueIterator.moveNext();
+
+ while (hasNextKey && hasNextValue) {
+ map[keyIterator.current] = valueIterator.current;
+ hasNextKey = keyIterator.moveNext();
+ hasNextValue = valueIterator.moveNext();
+ }
+
+ if (hasNextKey || hasNextValue) {
+ throw new ArgumentError("Iterables do not have same length.");
+ }
+ }
}
/**
@@ -347,109 +389,3 @@
Map<RK, RV> retype<RK, RV>() =>
new UnmodifiableMapView<RK, RV>(_map.retype<RK, RV>());
}
-
-/**
- * Helper class which implements complex [Map] operations
- * in term of basic ones ([Map.keys], [Map.[]],
- * [Map.[]=] and [Map.remove].) Not all methods are
- * necessary to implement each particular operation.
- *
- * Deprecated. Will be removed in Dart 2.
- */
-class Maps {
- static bool containsValue(Map map, Object value) {
- for (final v in map.values) {
- if (v == value) {
- return true;
- }
- }
- return false;
- }
-
- static bool containsKey(Map map, Object key) {
- for (final k in map.keys) {
- if (k == key) {
- return true;
- }
- }
- return false;
- }
-
- static putIfAbsent(Map map, key, ifAbsent()) {
- if (map.containsKey(key)) {
- return map[key];
- }
- final v = ifAbsent();
- map[key] = v;
- return v;
- }
-
- static clear(Map map) {
- for (final k in map.keys.toList()) {
- map.remove(k);
- }
- }
-
- static forEach(Map map, void f(key, value)) {
- for (final k in map.keys) {
- f(k, map[k]);
- }
- }
-
- static Iterable getValues(Map map) {
- return map.keys.map((key) => map[key]);
- }
-
- static int length(Map map) => map.keys.length;
-
- static bool isEmpty(Map map) => map.keys.isEmpty;
-
- static bool isNotEmpty(Map map) => map.keys.isNotEmpty;
-
- /**
- * Do not use. This entire class will be removed.
- *
- * Use [MapBase.mapToString] instead.
- */
- static String mapToString(Map m) => MapBase.mapToString(m);
-
- static _id(x) => x;
-
- /**
- * Fills a map with key/value pairs computed from [iterable].
- *
- * This method is used by Map classes in the named constructor fromIterable.
- */
- static void _fillMapWithMappedIterable(
- Map map, Iterable iterable, key(element), value(element)) {
- if (key == null) key = _id;
- if (value == null) value = _id;
-
- for (var element in iterable) {
- map[key(element)] = value(element);
- }
- }
-
- /**
- * Fills a map by associating the [keys] to [values].
- *
- * This method is used by Map classes in the named constructor fromIterables.
- */
- static void _fillMapWithIterables(Map map, Iterable keys, Iterable values) {
- Iterator keyIterator = keys.iterator;
- Iterator valueIterator = values.iterator;
-
- bool hasNextKey = keyIterator.moveNext();
- bool hasNextValue = valueIterator.moveNext();
-
- while (hasNextKey && hasNextValue) {
- map[keyIterator.current] = valueIterator.current;
- hasNextKey = keyIterator.moveNext();
- hasNextValue = valueIterator.moveNext();
- }
-
- if (hasNextKey || hasNextValue) {
- throw new ArgumentError("Iterables do not have same length.");
- }
- }
-}
diff --git a/sdk/lib/collection/splay_tree.dart b/sdk/lib/collection/splay_tree.dart
index 99234f3..b3eb7cb 100644
--- a/sdk/lib/collection/splay_tree.dart
+++ b/sdk/lib/collection/splay_tree.dart
@@ -334,7 +334,7 @@
int compare(K key1, K key2),
bool isValidKey(potentialKey)}) {
SplayTreeMap<K, V> map = new SplayTreeMap<K, V>(compare, isValidKey);
- Maps._fillMapWithMappedIterable(map, iterable, key, value);
+ MapBase._fillMapWithMappedIterable(map, iterable, key, value);
return map;
}
@@ -352,7 +352,7 @@
factory SplayTreeMap.fromIterables(Iterable<K> keys, Iterable<V> values,
[int compare(K key1, K key2), bool isValidKey(potentialKey)]) {
SplayTreeMap<K, V> map = new SplayTreeMap<K, V>(compare, isValidKey);
- Maps._fillMapWithIterables(map, keys, values);
+ MapBase._fillMapWithIterables(map, keys, values);
return map;
}
diff --git a/sdk/lib/dart_server.platform b/sdk/lib/dart_server.platform
index 414a30c..f1f2d3b 100644
--- a/sdk/lib/dart_server.platform
+++ b/sdk/lib/dart_server.platform
@@ -36,9 +36,9 @@
web_gl: unsupported:
web_sql: unsupported:
_chrome: unsupported:
-js: unsupported:
-_js: unsupported:
-js_util: unsupported:
+js: js/dart2js/js_dart2js.dart
+_js: js/_js.dart
+js_util: js_util/dart2js/js_util_dart2js.dart
_mirror_helper: unsupported:
_internal: internal/internal.dart
_js_helper: _internal/js_runtime/lib/js_helper.dart
diff --git a/sdk/lib/html/dart2js/html_dart2js.dart b/sdk/lib/html/dart2js/html_dart2js.dart
index f76fa2e..ceecfac 100644
--- a/sdk/lib/html/dart2js/html_dart2js.dart
+++ b/sdk/lib/html/dart2js/html_dart2js.dart
@@ -21,6 +21,8 @@
* * For even more examples, see
* [Dart HTML5 Samples](https://github.com/dart-lang/dart-html5-samples)
* on Github.
+ *
+ * {@category Web}
*/
library dart.dom.html;
@@ -12375,25 +12377,6 @@
ElementList<T> querySelectorAll<T extends Element>(String selectors) =>
new _FrozenElementList<T>._wrap(_querySelectorAll(selectors));
- /**
- * Alias for [querySelector]. Note this function is deprecated because its
- * semantics will be changing in the future.
- */
- @deprecated
- @Experimental()
- @DomName('Document.querySelector')
- Element query(String relativeSelectors) => querySelector(relativeSelectors);
-
- /**
- * Alias for [querySelectorAll]. Note this function is deprecated because its
- * semantics will be changing in the future.
- */
- @deprecated
- @Experimental()
- @DomName('Document.querySelectorAll')
- ElementList<T> queryAll<T extends Element>(String relativeSelectors) =>
- querySelectorAll(relativeSelectors);
-
/// Checks if [registerElement] is supported on the current platform.
bool get supportsRegisterElement {
return JS('bool', '("registerElement" in #)', this);
@@ -12558,26 +12541,6 @@
validator: validator, treeSanitizer: treeSanitizer));
}
- /**
- * Alias for [querySelector]. Note this function is deprecated because its
- * semantics will be changing in the future.
- */
- @deprecated
- @Experimental()
- @DomName('DocumentFragment.querySelector')
- Element query(String relativeSelectors) {
- return querySelector(relativeSelectors);
- }
-
- /**
- * Alias for [querySelectorAll]. Note this function is deprecated because its
- * semantics will be changing in the future.
- */
- @deprecated
- @Experimental()
- @DomName('DocumentFragment.querySelectorAll')
- ElementList<T> queryAll<T extends Element>(String relativeSelectors) =>
- querySelectorAll(relativeSelectors);
// To suppress missing implicit constructor warnings.
factory DocumentFragment._() {
throw new UnsupportedError("Not supported");
@@ -15706,25 +15669,6 @@
new _FrozenElementList<T>._wrap(_querySelectorAll(selectors));
/**
- * Alias for [querySelector]. Note this function is deprecated because its
- * semantics will be changing in the future.
- */
- @deprecated
- @DomName('Element.querySelector')
- @Experimental()
- Element query(String relativeSelectors) => querySelector(relativeSelectors);
-
- /**
- * Alias for [querySelectorAll]. Note this function is deprecated because its
- * semantics will be changing in the future.
- */
- @deprecated
- @DomName('Element.querySelectorAll')
- @Experimental()
- ElementList<T> queryAll<T extends Element>(String relativeSelectors) =>
- querySelectorAll(relativeSelectors);
-
- /**
* The set of CSS classes applied to this element.
*
* This set makes it easy to add, remove or toggle the classes applied to
@@ -15886,8 +15830,6 @@
@DomName('Element.getClientRects')
@DocsEditable()
- @Returns('DomRectList|Null')
- @Creates('DomRectList')
List<Rectangle> getClientRects() {
var value = _getClientRects();
@@ -15958,31 +15900,6 @@
*/
void attributeChanged(String name, String oldValue, String newValue) {}
- // Hooks to support custom WebComponents.
-
- @Creates('Null') // Set from Dart code; does not instantiate a native type.
- Element _xtag;
-
- /**
- * Experimental support for [web components][wc]. This field stores a
- * reference to the component implementation. It was inspired by Mozilla's
- * [x-tags][] project. Please note: in the future it may be possible to
- * `extend Element` from your class, in which case this field will be
- * deprecated.
- *
- * If xtag has not been set, it will simply return `this` [Element].
- *
- * [wc]: http://dvcs.w3.org/hg/webcomponents/raw-file/tip/explainer/index.html
- * [x-tags]: http://x-tags.org/
- */
- // Note: return type is `dynamic` for convenience to suppress warnings when
- // members of the component are used. The actual type is a subtype of Element.
- get xtag => _xtag != null ? _xtag : this;
-
- set xtag(Element value) {
- _xtag = value;
- }
-
@DomName('Element.localName')
@DocsEditable()
@Returns('String')
@@ -17667,8 +17584,8 @@
*/
@DomName('Element.getClientRects')
@DocsEditable()
- @Returns('DomRectList|Null')
@Creates('DomRectList')
+ @Returns('DomRectList|Null')
List<Rectangle> _getClientRects() native;
/**
@@ -19285,8 +19202,8 @@
@DomName('ExtendableMessageEvent.source')
@DocsEditable()
@Experimental() // untriaged
- @Creates('Client|_ServiceWorker|MessagePort')
- @Returns('Client|_ServiceWorker|MessagePort|Null')
+ @Creates('Client|ServiceWorker|MessagePort')
+ @Returns('Client|ServiceWorker|MessagePort|Null')
final Object source;
}
// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file
@@ -22019,48 +21936,6 @@
return _elementFromPoint(x, y);
}
- /**
- * Checks if the getCssCanvasContext API is supported on the current platform.
- *
- * See also:
- *
- * * [getCssCanvasContext]
- */
- static bool get supportsCssCanvasContext =>
- JS('bool', '!!(document.getCSSCanvasContext)');
-
- /**
- * Gets a CanvasRenderingContext which can be used as the CSS background of an
- * element.
- *
- * CSS:
- *
- * background: -webkit-canvas(backgroundCanvas)
- *
- * Generate the canvas:
- *
- * var context = document.getCssCanvasContext('2d', 'backgroundCanvas',
- * 100, 100);
- * context.fillStyle = 'red';
- * context.fillRect(0, 0, 100, 100);
- *
- * See also:
- *
- * * [supportsCssCanvasContext]
- * * [CanvasElement.getContext]
- */
- @SupportedBrowser(SupportedBrowser.CHROME)
- @SupportedBrowser(SupportedBrowser.SAFARI)
- @Experimental()
- @DomName('Document.getCSSCanvasContext')
- CanvasRenderingContext getCssCanvasContext(
- String contextId, String name, int width, int height) {
- if (HtmlDocument.supportsCssCanvasContext)
- return JS('CanvasRenderingContext', '#.getCSSCanvasContext(#, #, #, #)',
- this, contextId, name, width, height);
- throw new UnsupportedError("Not supported");
- }
-
@DomName('Document.head')
HeadElement get head => _head;
@@ -26919,6 +26794,14 @@
throw new UnsupportedError("Not supported");
}
+ @DomName('MessageChannel.MessageChannel')
+ @DocsEditable()
+ factory MessageChannel() {
+ return MessageChannel._create_1();
+ }
+ static MessageChannel _create_1() =>
+ JS('MessageChannel', 'new MessageChannel()');
+
@DomName('MessageChannel.port1')
@DocsEditable()
final MessagePort port1;
@@ -33672,8 +33555,6 @@
@DomName('Range.getClientRects')
@DocsEditable()
- @Returns('DomRectList|Null')
- @Creates('DomRectList')
List<Rectangle> getClientRects() {
var value = _getClientRects();
@@ -35794,6 +35675,47 @@
// BSD-style license that can be found in the LICENSE file.
@DocsEditable()
+@DomName('ServiceWorker')
+@Experimental() // untriaged
+@Native("ServiceWorker")
+class ServiceWorker extends EventTarget implements AbstractWorker {
+ // To suppress missing implicit constructor warnings.
+ factory ServiceWorker._() {
+ throw new UnsupportedError("Not supported");
+ }
+
+ @DomName('ServiceWorker.errorEvent')
+ @DocsEditable()
+ @Experimental() // untriaged
+ static const EventStreamProvider<Event> errorEvent =
+ const EventStreamProvider<Event>('error');
+
+ @JSName('scriptURL')
+ @DomName('ServiceWorker.scriptURL')
+ @DocsEditable()
+ @Experimental() // untriaged
+ final String scriptUrl;
+
+ @DomName('ServiceWorker.state')
+ @DocsEditable()
+ @Experimental() // untriaged
+ final String state;
+
+ @DomName('ServiceWorker.postMessage')
+ @DocsEditable()
+ @Experimental() // untriaged
+ void postMessage(Object message, [List<Object> transfer]) native;
+
+ @DomName('ServiceWorker.onerror')
+ @DocsEditable()
+ @Experimental() // untriaged
+ Stream<Event> get onError => errorEvent.forTarget(this);
+}
+// Copyright (c) 2012, 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.
+
+@DocsEditable()
@DomName('ServiceWorkerContainer')
@Experimental() // untriaged
@Native("ServiceWorkerContainer")
@@ -35812,7 +35734,7 @@
@DomName('ServiceWorkerContainer.controller')
@DocsEditable()
@Experimental() // untriaged
- final _ServiceWorker controller;
+ final ServiceWorker controller;
@DomName('ServiceWorkerContainer.ready')
@DocsEditable()
@@ -35958,7 +35880,7 @@
@DomName('ServiceWorkerRegistration.active')
@DocsEditable()
@Experimental() // untriaged
- final _ServiceWorker active;
+ final ServiceWorker active;
@DomName('ServiceWorkerRegistration.backgroundFetch')
@DocsEditable()
@@ -35968,7 +35890,7 @@
@DomName('ServiceWorkerRegistration.installing')
@DocsEditable()
@Experimental() // untriaged
- final _ServiceWorker installing;
+ final ServiceWorker installing;
@DomName('ServiceWorkerRegistration.navigationPreload')
@DocsEditable()
@@ -35998,7 +35920,7 @@
@DomName('ServiceWorkerRegistration.waiting')
@DocsEditable()
@Experimental() // untriaged
- final _ServiceWorker waiting;
+ final ServiceWorker waiting;
@DomName('ServiceWorkerRegistration.getNotifications')
@DocsEditable()
@@ -45909,21 +45831,6 @@
// BSD-style license that can be found in the LICENSE file.
@DocsEditable()
-@DomName('ServiceWorker')
-@Experimental() // untriaged
-@Native("ServiceWorker")
-abstract class _ServiceWorker extends EventTarget implements AbstractWorker {
- // To suppress missing implicit constructor warnings.
- factory _ServiceWorker._() {
- throw new UnsupportedError("Not supported");
- }
-}
-
-// Copyright (c) 2012, 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.
-
-@DocsEditable()
@DomName('SpeechRecognitionResultList')
// https://dvcs.w3.org/hg/speech-api/raw-file/tip/speechapi.html#speechrecognitionresultlist
@Experimental()
@@ -51523,22 +51430,6 @@
}
/**
- * Alias for [querySelector]. Note this function is deprecated because its
- * semantics will be changing in the future.
- */
-@deprecated
-@Experimental()
-Element query(String relativeSelectors) => document.query(relativeSelectors);
-/**
- * Alias for [querySelectorAll]. Note this function is deprecated because its
- * semantics will be changing in the future.
- */
-@deprecated
-@Experimental()
-ElementList<Element> queryAll(String relativeSelectors) =>
- document.queryAll(relativeSelectors);
-
-/**
* Finds the first descendant element of this document that matches the
* specified group of selectors.
*
diff --git a/sdk/lib/indexed_db/dart2js/indexed_db_dart2js.dart b/sdk/lib/indexed_db/dart2js/indexed_db_dart2js.dart
index 7edd685..e17e1e2 100644
--- a/sdk/lib/indexed_db/dart2js/indexed_db_dart2js.dart
+++ b/sdk/lib/indexed_db/dart2js/indexed_db_dart2js.dart
@@ -69,6 +69,8 @@
*
* [IndexedDB reference](http://docs.webplatform.org/wiki/apis/indexeddb)
* provides wiki-style docs about indexedDB
+ *
+ * {@category Web}
*/
library dart.dom.indexed_db;
diff --git a/sdk/lib/io/io.dart b/sdk/lib/io/io.dart
index 0feb4ba..bc7e88a 100644
--- a/sdk/lib/io/io.dart
+++ b/sdk/lib/io/io.dart
@@ -185,6 +185,8 @@
* (the program blocks waiting for user to type information):
*
* String inputText = stdin.readLineSync();
+ *
+ * {@category VM}
*/
library dart.io;
diff --git a/sdk/lib/isolate/isolate.dart b/sdk/lib/isolate/isolate.dart
index 5fec1c0..496c820 100644
--- a/sdk/lib/isolate/isolate.dart
+++ b/sdk/lib/isolate/isolate.dart
@@ -11,6 +11,8 @@
* To use this library in your code:
*
* import 'dart:isolate';
+ *
+ * {@category VM}
*/
library dart.isolate;
diff --git a/sdk/lib/js/dart2js/js_dart2js.dart b/sdk/lib/js/dart2js/js_dart2js.dart
index 74c55b8..e0aedb9 100644
--- a/sdk/lib/js/dart2js/js_dart2js.dart
+++ b/sdk/lib/js/dart2js/js_dart2js.dart
@@ -78,6 +78,8 @@
* This expression creates a JavaScript array:
*
* var jsArray = new JsObject.jsify([1, 2, 3]);
+ *
+ * {@category Web}
*/
library dart.js;
diff --git a/sdk/lib/js_util/dart2js/js_util_dart2js.dart b/sdk/lib/js_util/dart2js/js_util_dart2js.dart
index efc4386..ac832ff 100644
--- a/sdk/lib/js_util/dart2js/js_util_dart2js.dart
+++ b/sdk/lib/js_util/dart2js/js_util_dart2js.dart
@@ -7,6 +7,8 @@
/// methods when the same effect cannot be achieved with @JS annotations.
/// These methods would be extension methods on JSObject if Dart supported
/// extension methods.
+///
+/// {@category Web}
library dart.js_util;
import 'dart:_foreign_helper' show JS;
diff --git a/sdk/lib/libraries.json b/sdk/lib/libraries.json
index 633ae36..b1fe827 100644
--- a/sdk/lib/libraries.json
+++ b/sdk/lib/libraries.json
@@ -146,10 +146,6 @@
}
},
"dart2js": {
- "environment_overrides": {
- "mirrors": false,
- "io": false
- },
"libraries": {
"async": {
"patches": "_internal/js_runtime/lib/async_patch.dart",
@@ -160,6 +156,7 @@
},
"mirrors": {
"patches": "_internal/js_runtime/lib/mirrors_patch_cfe.dart",
+ "supported": false,
"uri": "mirrors/mirrors.dart"
},
"_js_embedded_names": {
@@ -167,6 +164,7 @@
},
"io": {
"patches": "_internal/js_runtime/lib/io_patch.dart",
+ "supported": false,
"uri": "io/io.dart"
},
"_internal": {
@@ -229,6 +227,7 @@
},
"isolate": {
"patches": "_internal/js_runtime/lib/isolate_patch.dart",
+ "supported": false,
"uri": "isolate/isolate.dart"
},
"developer": {
@@ -268,10 +267,6 @@
}
},
"dart2js_server": {
- "environment_overrides": {
- "mirrors": false,
- "io": false
- },
"libraries": {
"async": {
"patches": "_internal/js_runtime/lib/async_patch.dart",
@@ -279,6 +274,7 @@
},
"mirrors": {
"patches": "_internal/js_runtime/lib/mirrors_patch_cfe.dart",
+ "supported": false,
"uri": "mirrors/mirrors.dart"
},
"_interceptors": {
@@ -289,6 +285,7 @@
},
"io": {
"patches": "_internal/js_runtime/lib/io_patch.dart",
+ "supported": false,
"uri": "io/io.dart"
},
"_internal": {
@@ -336,6 +333,7 @@
},
"isolate": {
"patches": "_internal/js_runtime/lib/isolate_patch.dart",
+ "supported": false,
"uri": "isolate/isolate.dart"
},
"developer": {
diff --git a/sdk/lib/libraries.yaml b/sdk/lib/libraries.yaml
index 2bb6e8c..eb7ae2e 100644
--- a/sdk/lib/libraries.yaml
+++ b/sdk/lib/libraries.yaml
@@ -184,10 +184,12 @@
io:
uri: "io/io.dart"
patches: "_internal/js_runtime/lib/io_patch.dart"
+ supported: false
isolate:
uri: "isolate/isolate.dart"
patches: "_internal/js_runtime/lib/isolate_patch.dart"
+ supported: false
js:
uri: "js/dart2js/js_dart2js.dart"
@@ -206,6 +208,7 @@
mirrors:
uri: "mirrors/mirrors.dart"
patches: "_internal/js_runtime/lib/mirrors_patch_cfe.dart"
+ supported: false
typed_data:
uri: "typed_data/typed_data.dart"
@@ -260,10 +263,6 @@
_metadata:
uri: "html/html_common/metadata.dart"
- environment_overrides:
- io: false
- mirrors: false
-
dart2js_server:
libraries:
async:
@@ -292,10 +291,12 @@
io:
uri: "io/io.dart"
patches: "_internal/js_runtime/lib/io_patch.dart"
+ supported: false
isolate:
uri: "isolate/isolate.dart"
patches: "_internal/js_runtime/lib/isolate_patch.dart"
+ supported: false
js:
uri: "js/dart2js/js_dart2js.dart"
@@ -314,6 +315,7 @@
mirrors:
uri: "mirrors/mirrors.dart"
patches: "_internal/js_runtime/lib/mirrors_patch_cfe.dart"
+ supported: false
typed_data:
uri: "typed_data/typed_data.dart"
@@ -352,7 +354,3 @@
_async_await_error_codes:
uri: "_internal/js_runtime/lib/shared/async_await_error_codes.dart"
-
- environment_overrides:
- io: false
- mirrors: false
diff --git a/sdk/lib/mirrors/mirrors.dart b/sdk/lib/mirrors/mirrors.dart
index 6b455c6..0811fdb 100644
--- a/sdk/lib/mirrors/mirrors.dart
+++ b/sdk/lib/mirrors/mirrors.dart
@@ -52,6 +52,8 @@
* result of user feedback. This library is platform dependent and therefore it
* has implementations for both dart2js and the Dart VM. Both are under
* development and may not support all operations yet.
+ *
+ * {@category VM}
*/
library dart.mirrors;
diff --git a/sdk/lib/svg/dart2js/svg_dart2js.dart b/sdk/lib/svg/dart2js/svg_dart2js.dart
index fb3da8b..16ba803 100644
--- a/sdk/lib/svg/dart2js/svg_dart2js.dart
+++ b/sdk/lib/svg/dart2js/svg_dart2js.dart
@@ -5,6 +5,8 @@
* For details about the features and syntax of SVG, a W3C standard,
* refer to the
* [Scalable Vector Graphics Specification](http://www.w3.org/TR/SVG/).
+ *
+ * {@category Web}
*/
library dart.dom.svg;
diff --git a/sdk/lib/web_audio/dart2js/web_audio_dart2js.dart b/sdk/lib/web_audio/dart2js/web_audio_dart2js.dart
index 707b1e7..c927559 100644
--- a/sdk/lib/web_audio/dart2js/web_audio_dart2js.dart
+++ b/sdk/lib/web_audio/dart2js/web_audio_dart2js.dart
@@ -1,5 +1,7 @@
/**
* High-fidelity audio programming in the browser.
+ *
+ * {@category Web}
*/
library dart.dom.web_audio;
diff --git a/sdk/lib/web_gl/dart2js/web_gl_dart2js.dart b/sdk/lib/web_gl/dart2js/web_gl_dart2js.dart
index d441cf1..657d0a8 100644
--- a/sdk/lib/web_gl/dart2js/web_gl_dart2js.dart
+++ b/sdk/lib/web_gl/dart2js/web_gl_dart2js.dart
@@ -1,5 +1,7 @@
/**
* 3D programming in the browser.
+ *
+ * {@category Web}
*/
library dart.dom.web_gl;
diff --git a/sdk/lib/web_sql/dart2js/web_sql_dart2js.dart b/sdk/lib/web_sql/dart2js/web_sql_dart2js.dart
index 9a84406..633ebe5 100644
--- a/sdk/lib/web_sql/dart2js/web_sql_dart2js.dart
+++ b/sdk/lib/web_sql/dart2js/web_sql_dart2js.dart
@@ -7,6 +7,8 @@
* for more information.
*
* The [dart:indexed_db] APIs is a recommended alternatives.
+ *
+ * {@category Web}
*/
library dart.dom.web_sql;
diff --git a/tests/co19/co19-dart2js.status b/tests/co19/co19-dart2js.status
index c05773a..9025f36 100644
--- a/tests/co19/co19-dart2js.status
+++ b/tests/co19/co19-dart2js.status
@@ -69,19 +69,40 @@
Language/Types/Interface_Types/subtype_t27: Skip # Times out or crashes. Issue 21174
Language/Types/Interface_Types/subtype_t28: Pass, Fail, Crash # Stack overflow. Issue 25282
Language/Types/Interface_Types/subtype_t30: Fail # Issue 14654
-Language/Types/Type_Void/syntax_t05: MissingCompileTimeError, Crash
Language/Types/Type_Void/syntax_t08: MissingCompileTimeError
+LayoutTests/fast/borders/border-color-visited_t01: RuntimeError # See issue 143
+LayoutTests/fast/canvas/fillText-shadow_t01: RuntimeError # See issue 143
LayoutTests/fast/css/content/content-quotes-01_t01: Pass, RuntimeError
LayoutTests/fast/css/font-face-cache-bug_t01: Pass, RuntimeError
LayoutTests/fast/css/fontfaceset-loadingdone_t01: Pass, RuntimeError
+LayoutTests/fast/css/misplaced-charset_t01: RuntimeError # See issue 143
+LayoutTests/fast/css/pseudo-empty-dynamic-empty_t01: RuntimeError # See issue 143
+LayoutTests/fast/css/remove-class-name_t01: RuntimeError # See issue 143
LayoutTests/fast/dom/HTMLLinkElement/link-onload-stylesheet-with-import_t01: Skip # https://github.com/dart-lang/sdk/issues/28873
+LayoutTests/fast/dom/HTMLTableElement/createCaption_t01: RuntimeError # See issue 143
+LayoutTests/fast/dom/HTMLTableElement/early-acid3-66-excerpt_t01: RuntimeError # See issue 143
+LayoutTests/fast/dom/HTMLTableRowElement/insertCell_t01: RuntimeError # See issue 143
+LayoutTests/fast/dom/Range/create-contextual-fragment-script-unmark-already-started_t01: RuntimeError # See issue 143
+LayoutTests/fast/dom/clone-node-style_t01: RuntimeError # See issue 143
LayoutTests/fast/dom/css-innerHTML_t01: SkipByDesign # Test is incorrect.
+LayoutTests/fast/dom/icon-url-change_t01: RuntimeError # See issue 143
+LayoutTests/fast/dom/icon-url-list_t01: RuntimeError # See issue 143
LayoutTests/fast/dom/mutation-event-remove-inserted-node_t01: Skip # https://github.com/dart-lang/sdk/issues/28873
LayoutTests/fast/dom/shadow/event-path-not-in-document_t01: Skip # https://github.com/dart-lang/sdk/issues/28873
+LayoutTests/fast/dom/shared-inline-style-after-node-removal_t01: RuntimeError # See issue 143
LayoutTests/fast/dom/subtree-modified-attributes_t01: Skip # https://github.com/dart-lang/sdk/issues/28873
+LayoutTests/fast/events/form-onchange_t01: RuntimeError # See issue 143
+LayoutTests/fast/events/onerror-bubbling_t01: RuntimeError # See issue 143
LayoutTests/fast/files/file-reader-done-reading-abort_t01: Skip # https://github.com/dart-lang/sdk/issues/28873
+LayoutTests/fast/forms/autofocus-attribute_t01: RuntimeError # See issue 143
+LayoutTests/fast/forms/autofocus-opera-004_t01: RuntimeError # See issue 143
+LayoutTests/fast/forms/autofocus-opera-005_t01: RuntimeError # See issue 143
+LayoutTests/fast/forms/autofocus-opera-008_t01: RuntimeError # See issue 143
LayoutTests/fast/forms/input-implicit-length-limit_t01: SkipByDesign # Test is not about Dart, but about a DOM-only webkit bug that has been fixed.
+LayoutTests/fast/forms/interactive-validation-attach-assertion_t01: RuntimeError # See issue 143
LayoutTests/fast/forms/search-popup-crasher_t01: Skip # https://github.com/dart-lang/sdk/issues/28873
+LayoutTests/fast/forms/select-namedItem_t01: RuntimeError # See issue 143
+LayoutTests/fast/forms/select-reset-multiple-selections-4-single-selection_t01: RuntimeError # See issue 143
LayoutTests/fast/loader/loadInProgress_t01: Skip # Issue 23466
LayoutTests/fast/loader/stateobjects/replacestate-in-onunload_t01: Skip # https://github.com/dart-lang/sdk/issues/28873
LayoutTests/fast/media/mq-parsing_t01: Skip # https://github.com/dart-lang/sdk/issues/28873
@@ -111,12 +132,15 @@
LayoutTests/fast/writing-mode/percentage-margins-absolute_t01: Skip # https://github.com/dart-lang/sdk/issues/28873
LayoutTests/fast/xmlhttprequest/xmlhttprequest-responsetype-abort_t01: Skip # https://github.com/dart-lang/sdk/issues/28873
LayoutTests/fast/xpath/4XPath/Core/test_core_functions_t02: Skip # https://github.com/dart-lang/sdk/issues/28873
+LayoutTests/fast/xpath/4XPath/Core/test_location_path_t01: RuntimeError # See issue 143
+LayoutTests/fast/xpath/4XPath/Core/test_step_t01: RuntimeError # See issue 143
LayoutTests/fast/xpath/ambiguous-operators_t01: Skip # https://github.com/dart-lang/sdk/issues/28873
LibTest/async/Future/Future.delayed_A01_t02: Pass, Fail # Issue 15524
LibTest/collection/LinkedHashSet/LinkedHashSet.from_A03_t01: RuntimeError # Please triage this failure.
LibTest/collection/LinkedList/add_A01_t01: Pass, Slow # Slow tests that needs extra time to finish.
LibTest/collection/ListBase/ListBase_class_A01_t01: RuntimeError # Please triage this failure
LibTest/collection/ListMixin/ListMixin_class_A01_t01: RuntimeError # Please triage this failure
+LibTest/collection/Maps/*: Skip # Maps class no longer exists
LibTest/convert/JsonCodec/encode_A01_t01: RuntimeError # code.google.com/p/co19/issues/detail?id=735
LibTest/convert/JsonCodec/encode_A01_t02: RuntimeError # code.google.com/p/co19/issues/detail?id=735
LibTest/convert/JsonDecoder/fuse_A01_t01: RuntimeError # co19-roll r667: Please triage this failure
@@ -148,6 +172,8 @@
LibTest/core/int/operator_right_shift_A01_t01: RuntimeError, OK # Expects negative result from bit-operation.
LibTest/core/int/toDouble_A01_t01: RuntimeError, OK # co19 issue 200
LibTest/html/Element/addEventListener_A01_t04: Skip # https://github.com/dart-lang/sdk/issues/28873
+LibTest/html/Element/queryAll_A01_t01: RuntimeError # See issue 143
+LibTest/html/Element/query_A01_t01: RuntimeError # See issue 143
LibTest/html/HttpRequest/responseType_A01_t03: CompileTimeError # co19-roll r706: Please triage this failure
LibTest/html/IFrameElement/addEventListener_A01_t04: Skip # https://github.com/dart-lang/sdk/issues/28873
LibTest/html/IFrameElement/enteredView_A01_t01: CompileTimeError # co19-roll r706: Please triage this failure
@@ -276,10 +302,22 @@
Utils/tests/Expect/identical_A01_t01: Fail # co19-roll r546: Please triage this failure
WebPlatformTest/Utils/test/asyncTestFail_t02: Skip # https://github.com/dart-lang/sdk/issues/28873
WebPlatformTest/Utils/test/testFail_t01: RuntimeError # co19-roll r722: Please triage this failure.
+WebPlatformTest/custom-elements/instantiating/isAttribute_A01_t01: RuntimeError # See issue 143
+WebPlatformTest/custom-elements/instantiating/isAttribute_A01_t02: RuntimeError # See issue 143
+WebPlatformTest/custom-elements/instantiating/isAttribute_A02_t01: RuntimeError # See issue 143
+WebPlatformTest/custom-elements/instantiating/isAttribute_A03_t01: RuntimeError # See issue 143
+WebPlatformTest/custom-elements/instantiating/localName_A01_t01: RuntimeError # See issue 143
WebPlatformTest/dom/EventTarget/dispatchEvent_A02_t01: Skip # https://github.com/dart-lang/sdk/issues/28873
WebPlatformTest/dom/nodes/DOMImplementation-createHTMLDocument_t01: CompileTimeError # co19-roll r722: Please triage this failure.
WebPlatformTest/dom/nodes/Document-createElement_t01: CompileTimeError # co19-roll r722: Please triage this failure.
WebPlatformTest/dom/nodes/Element-childElementCount-nochild_t01: CompileTimeError # co19-roll r722: Please triage this failure.
+WebPlatformTest/html/dom/elements/global-attributes/classlist-nonstring_t01: RuntimeError # See issue 143
+WebPlatformTest/html/semantics/forms/the-textarea-element/textarea-type_t01: RuntimeError # See issue 143
+WebPlatformTest/html/semantics/tabular-data/the-table-element/insertRow-method_t01: RuntimeError # See issue 143
+WebPlatformTest/html/semantics/tabular-data/the-table-element/insertRow-method_t02: RuntimeError # See issue 143
+WebPlatformTest/html/semantics/tabular-data/the-table-element/tBodies_t01: RuntimeError # See issue 143
+WebPlatformTest/html/semantics/text-level-semantics/the-a-element/a.text-getter_t01: RuntimeError # See issue 143
+WebPlatformTest/html/semantics/text-level-semantics/the-a-element/a.text-setter_t01: RuntimeError # See issue 143
WebPlatformTest/webstorage/event_local_storageeventinit_t01: Skip # https://github.com/dart-lang/sdk/issues/28873
WebPlatformTest/webstorage/storage_local_setitem_quotaexceedederr_t01: Skip # Times out. Please triage this failure.
WebPlatformTest/webstorage/storage_session_setitem_quotaexceedederr_t01: Skip # Times out. Please triage this failure
diff --git a/tests/co19/co19-kernel.status b/tests/co19/co19-kernel.status
index 8e7ae4b..8347cd1 100644
--- a/tests/co19/co19-kernel.status
+++ b/tests/co19/co19-kernel.status
@@ -4,10 +4,10 @@
[ $compiler == fasta ]
Language/Classes/definition_t24: MissingCompileTimeError
-Language/Types/Type_Void/syntax_t05: MissingCompileTimeError
Language/Types/Type_Void/syntax_t08: MissingCompileTimeError
Language/Types/Type_Void/syntax_t09: MissingCompileTimeError
LayoutTests/*: Skip # TODO(ahe): Make dart:html available.
+LibTest/collection/Maps/*: Skip # Maps class no longer exists.
LibTest/html/*: Skip # TODO(ahe): Make dart:html available.
WebPlatformTest/*: Skip # TODO(ahe): Make dart:html available.
@@ -1079,7 +1079,6 @@
Language/Types/Type_Declarations/Typedef/self_reference_t08: Crash
Language/Types/Type_Declarations/Typedef/self_reference_t09: Crash
Language/Types/Type_Declarations/Typedef/syntax_t01: CompileTimeError
-Language/Types/Type_Void/syntax_t05: MissingCompileTimeError
Language/Types/Type_Void/syntax_t08: MissingCompileTimeError
Language/Types/Type_Void/syntax_t09: MissingCompileTimeError
Language/Variables/constant_variable_t01: CompileTimeError
diff --git a/tests/co19/co19-runtime.status b/tests/co19/co19-runtime.status
index 5b01ef4..8a3884a 100644
--- a/tests/co19/co19-runtime.status
+++ b/tests/co19/co19-runtime.status
@@ -303,6 +303,7 @@
LayoutTests/fast/*: SkipByDesign # DOM not supported on VM.
LibTest/collection/ListBase/ListBase_class_A01_t01: RuntimeError # Large integers
LibTest/collection/ListMixin/ListMixin_class_A01_t01: RuntimeError # Large integers
+LibTest/collection/Maps/*: Skip # Maps class no longer exists
LibTest/core/Duration/inDays_A01_t01: RuntimeError # Large integers
LibTest/core/Duration/inHours_A01_t01: RuntimeError # Large integers
LibTest/core/Duration/inMilliseconds_A01_t01: RuntimeError # Large integers
diff --git a/tests/compiler/dart2js/dart2js.status b/tests/compiler/dart2js/dart2js.status
index f4b558f..7a97fd3 100644
--- a/tests/compiler/dart2js/dart2js.status
+++ b/tests/compiler/dart2js/dart2js.status
@@ -67,7 +67,6 @@
sourcemaps/source_mapping_operators_test: Pass, Slow
sourcemaps/source_mapping_test: Pass, Slow
subtype_test: Slow, Pass
-uri_retention_test: Fail # Issue 26504
[ $mode == debug ]
deferred/load_graph_segmentation_test: Pass, Slow
diff --git a/tests/compiler/dart2js/end_to_end/command_line_test.dart b/tests/compiler/dart2js/end_to_end/command_line_test.dart
index 88a7650..75db352 100644
--- a/tests/compiler/dart2js/end_to_end/command_line_test.dart
+++ b/tests/compiler/dart2js/end_to_end/command_line_test.dart
@@ -21,35 +21,10 @@
await test(['foo.dart']);
await test([Flags.useOldFrontend], exitCode: 1);
await test([Flags.useOldFrontend, 'foo.dart']);
- await test([Flags.useOldFrontend, Flags.resolveOnly, 'foo.dart'],
- resolveOnly: true, resolutionOutput: Uri.base.resolve('out.data'));
- await test(
- [Flags.useOldFrontend, '--resolution-input=bar.dart', 'foo.dart'],
- resolutionInputs: [Uri.base.resolve('bar.dart')]);
- await test(
- [
- Flags.useOldFrontend,
- Flags.resolveOnly,
- '--resolution-input=bar.dart',
- 'foo.dart'
- ],
- resolveOnly: true,
- resolutionOutput: Uri.base.resolve('out.data'),
- resolutionInputs: [Uri.base.resolve('bar.dart')]);
- await test([
- Flags.useOldFrontend,
- Flags.resolveOnly,
- '--resolution-input=out.data',
- 'foo.dart'
- ], exitCode: 1);
});
}
-Future test(List<String> arguments,
- {int exitCode,
- bool resolveOnly: false,
- Uri resolutionOutput,
- List<Uri> resolutionInputs}) async {
+Future test(List<String> arguments, {int exitCode}) async {
print('--------------------------------------------------------------------');
print('dart2js ${arguments.join(' ')}');
print('--------------------------------------------------------------------');
@@ -75,17 +50,6 @@
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(resolutionOutput, options.resolutionOutput,
- "Unexpected resolutionOutput value");
- if (resolutionInputs == null) {
- Expect.isNull(
- options.resolutionInputs, "Unexpected resolutionInputs value");
- } else {
- Expect.listEquals(resolutionInputs, options.resolutionInputs,
- "Unexpected resolutionInputs value");
- }
}
entry.compileFunc = oldCompileFunc;
diff --git a/tests/compiler/dart2js/end_to_end/library_env_test.dart b/tests/compiler/dart2js/end_to_end/library_env_test.dart
index 1fcdb15..8c3ae8b 100644
--- a/tests/compiler/dart2js/end_to_end/library_env_test.dart
+++ b/tests/compiler/dart2js/end_to_end/library_env_test.dart
@@ -84,10 +84,10 @@
const DummyCompilerInput(),
const NullCompilerOutput(),
const DummyCompilerDiagnostics(),
- new CompilerOptions.parse(
- libraryRoot: Uri.base.resolve("sdk/"),
- options: ['--platform-binaries=$platformDir']..addAll(options),
- environment: environment));
+ CompilerOptions.parse(
+ ['--platform-binaries=$platformDir']..addAll(options),
+ libraryRoot: Uri.base.resolve("sdk/"))
+ ..environment = environment);
}
runTest() async {
diff --git a/tests/compiler/dart2js/equivalence/id_equivalence_helper.dart b/tests/compiler/dart2js/equivalence/id_equivalence_helper.dart
index 80ec57a..4c006b6 100644
--- a/tests/compiler/dart2js/equivalence/id_equivalence_helper.dart
+++ b/tests/compiler/dart2js/equivalence/id_equivalence_helper.dart
@@ -201,6 +201,7 @@
elementEnvironment.lookupLibrary(Uri.parse('dart:collection')),
commonElements.interceptorsLibrary,
commonElements.jsHelperLibrary,
+ commonElements.asyncLibrary,
];
ClassEntity getGlobalClass(String className) {
diff --git a/tests/compiler/dart2js/memory_compiler.dart b/tests/compiler/dart2js/memory_compiler.dart
index 70b26c0..a5f6d2e 100644
--- a/tests/compiler/dart2js/memory_compiler.dart
+++ b/tests/compiler/dart2js/memory_compiler.dart
@@ -182,16 +182,14 @@
outputProvider = const NullCompilerOutput();
}
- CompilerOptions compilerOptions = new CompilerOptions.parse(
- entryPoint: entryPoint,
- resolutionInputs: resolutionInputs,
- libraryRoot: libraryRoot,
- packageRoot: packageRoot,
- options: options,
- environment: {},
- platformBinaries: platformBinaries,
- packageConfig: packageConfig,
- packagesDiscoveryProvider: packagesDiscoveryProvider);
+ CompilerOptions compilerOptions = CompilerOptions.parse(options,
+ libraryRoot: libraryRoot, platformBinaries: platformBinaries)
+ ..entryPoint = entryPoint
+ ..resolutionInputs = resolutionInputs
+ ..packageRoot = packageRoot
+ ..environment = {}
+ ..packageConfig = packageConfig
+ ..packagesDiscoveryProvider = packagesDiscoveryProvider;
if (compilerOptions.strongMode) {
compilerOptions.kernelInitializedCompilerState =
strongKernelInitializedCompilerState;
diff --git a/tests/compiler/dart2js/mirrors/preserve_uris_test.dart b/tests/compiler/dart2js/mirrors/preserve_uris_test.dart
deleted file mode 100644
index 6ecc464..0000000
--- a/tests/compiler/dart2js/mirrors/preserve_uris_test.dart
+++ /dev/null
@@ -1,60 +0,0 @@
-// 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.
-
-import 'package:expect/expect.dart';
-import 'package:async_helper/async_helper.dart';
-import 'package:compiler/compiler_new.dart';
-import 'package:compiler/src/commandline_options.dart';
-import '../memory_compiler.dart' show runCompiler, OutputCollector;
-
-const MEMORY_SOURCE_FILES = const <String, String>{
- 'main.dart': """
-library main;
-
-@MirrorsUsed(targets: const ['main', 'lib'])
-import 'dart:mirrors';
-import 'lib.dart';
-
-
-class Subclass extends Super {
- int _private;
-
- int magic() => _private++;
-}
-
-main() {
- var objects = [new Super(), new Subclass()];
- print(currentMirrorSystem().findLibrary(#main).uri);
-}
-""",
- 'lib.dart': """
-library lib;
-
-class Super {
- int _private;
-
- int magic() => _private++;
-}
-"""
-};
-
-runTest(bool preserveUris) async {
- OutputCollector collector = new OutputCollector();
- var options = ["--minify", Flags.useOldFrontend];
- if (preserveUris) options.add("--preserve-uris");
- await runCompiler(
- memorySourceFiles: MEMORY_SOURCE_FILES,
- outputProvider: collector,
- options: options);
- String jsOutput = collector.getOutput('', OutputType.js);
- Expect.equals(preserveUris, jsOutput.contains("main.dart"));
- Expect.equals(preserveUris, jsOutput.contains("lib.dart"));
-}
-
-void main() {
- asyncTest(() async {
- await runTest(true);
- await runTest(false);
- });
-}
diff --git a/tests/compiler/dart2js/model/future_or_test.dart b/tests/compiler/dart2js/model/future_or_test.dart
index a183c3a..e1598ee 100644
--- a/tests/compiler/dart2js/model/future_or_test.dart
+++ b/tests/compiler/dart2js/model/future_or_test.dart
@@ -4,6 +4,7 @@
import 'package:async_helper/async_helper.dart';
import 'package:compiler/src/commandline_options.dart';
+import 'package:compiler/src/elements/entities.dart';
import 'package:compiler/src/elements/types.dart';
import 'package:expect/expect.dart';
import '../type_test_helper.dart';
@@ -26,13 +27,40 @@
Future<Null> futureNull() async => null;
FutureOr<Null> futureOrNull() async => null;
+
+void returnVoid() {}
+
+class C<T> {
+ Future<T> futureT() async => null;
+ FutureOr<T> futureOrT() async => null;
+}
''',
compileMode: CompileMode.kernel,
options: [Flags.strongMode]);
- DartType getReturnType(String name, String expectedType) {
- FunctionType type = env.getMemberType(name);
+ FunctionType getFunctionType(String name, String expectedType,
+ [ClassEntity cls]) {
+ FunctionType type = env.getMemberType(name, cls);
+ Expect.isNotNull(type,
+ "Member $name not found${cls != null ? ' in class $cls' : ''}.");
+ Expect.equals(
+ expectedType,
+ '${type}',
+ "Unexpected type for $name"
+ "${cls != null ? ' in class $cls' : ''}.");
+ return type;
+ }
+
+ DartType getReturnType(String name, String expectedType,
+ [ClassEntity cls]) {
+ FunctionType type = env.getMemberType(name, cls);
+ Expect.isNotNull(type,
+ "Member $name not found${cls != null ? ' in class $cls' : ''}.");
DartType returnType = type.returnType;
- Expect.equals(expectedType, '${returnType}');
+ Expect.equals(
+ expectedType,
+ '${returnType}',
+ "Unexpected return type for $name"
+ "${cls != null ? ' in class $cls' : ''}.");
return returnType;
}
@@ -61,28 +89,45 @@
FutureOrType futureOrNull = getReturnType('futureOrNull', 'FutureOr<Null>');
DartType Null_ = futureOrNull.typeArgument;
+ ClassEntity C = env.getClass('C');
+ DartType futureT = getReturnType('futureT', 'Future<C.T>', C);
+ FutureOrType futureOrT = getReturnType('futureOrT', 'FutureOr<C.T>', C);
+ DartType T = futureOrT.typeArgument;
+ Expect.isTrue(futureOrT.containsTypeVariables);
+ futureOrT.forEachTypeVariable((t) => Expect.equals(T, t));
+
+ DartType returnVoid = getFunctionType('returnVoid', 'void Function()');
+ DartType returnFutureNull =
+ getFunctionType('futureOrNull', 'FutureOr<Null> Function()');
+
List<DartType> all = [
Object_,
num_,
int_,
Null_,
ListNum,
+ T,
futureNum,
futureOrNum,
futureInt,
futureNull,
futureListNum,
+ futureT,
futureOrInt,
futureOrNull,
futureOrListNum,
futureFutureNum,
futureOrFutureOrNum,
+ futureOrT,
+ returnVoid,
+ returnFutureNull,
];
Map<DartType, List<DartType>> expectedSubtypesMap = {
num_: [futureOrNum, futureOrFutureOrNum],
int_: [num_, futureOrInt, futureOrNum, futureOrFutureOrNum],
ListNum: [futureOrListNum],
+ T: [futureOrT],
futureNum: [futureOrNum, futureOrFutureOrNum],
futureInt: [futureNum, futureOrNum, futureOrInt, futureOrFutureOrNum],
futureNull: [
@@ -95,18 +140,21 @@
futureOrListNum,
futureFutureNum,
futureOrFutureOrNum,
- futureOrNull,
+ futureT,
+ futureOrT,
],
futureListNum: [futureOrListNum],
futureFutureNum: [futureOrFutureOrNum],
futureOrNum: [futureOrFutureOrNum],
futureOrInt: [futureOrNum, futureOrFutureOrNum],
futureOrNull: [
+ futureOrT,
futureOrNum,
futureOrInt,
futureOrListNum,
- futureOrFutureOrNum
+ futureOrFutureOrNum,
],
+ returnFutureNull: [returnVoid],
};
for (DartType t in all) {
diff --git a/tests/compiler/dart2js/model/strong_mode_impact_test.dart b/tests/compiler/dart2js/model/strong_mode_impact_test.dart
new file mode 100644
index 0000000..188bd2e
--- /dev/null
+++ b/tests/compiler/dart2js/model/strong_mode_impact_test.dart
@@ -0,0 +1,195 @@
+// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+import 'package:expect/expect.dart';
+import 'package:async_helper/async_helper.dart';
+import 'package:compiler/src/commandline_options.dart';
+import 'package:compiler/src/compiler.dart';
+import 'package:compiler/src/common_elements.dart';
+import 'package:compiler/src/elements/entities.dart';
+import 'package:compiler/src/world.dart';
+import 'package:compiler/src/universe/use.dart';
+import 'package:compiler/src/universe/world_impact.dart';
+import '../memory_compiler.dart';
+
+main() {
+ asyncTest(() async {
+ print('--test from non-strong mode---------------------------------------');
+ await runTest(strongMode: false);
+ print('--test from strong mode-------------------------------------------');
+ await runTest(strongMode: true);
+ });
+}
+
+runTest({bool strongMode}) async {
+ String source = '''
+class A {}
+class B {}
+
+int method1() => 0;
+int method2(dynamic o) => o;
+method3(int i) {}
+int method4(dynamic o) => o as int;
+void method5() {}
+method6() => [];
+method7() => [0];
+method8() => <int>[0];
+method9(dynamic o) => <int>[o];
+method10() => {};
+method11() => {0: ''};
+method12() => <int, String>{0: ''};
+method13(dynamic k, String v) => <int, String>{k: v};
+
+main() {
+ method1();
+ method2(null);
+ method3(0);
+ method4(0);
+ method5();
+ method6();
+ method7();
+ method8();
+ method9(0);
+ method10();
+ method11();
+ method12();
+ method13(0, '');
+}
+''';
+
+ Map<String, Impact> expectedImpactMap = <String, Impact>{
+ 'method1':
+ strongMode ? const Impact() : new Impact(checkedModeChecks: ['int']),
+ 'method2': strongMode
+ ? new Impact(implicitCasts: ['int'])
+ : new Impact(checkedModeChecks: ['int']),
+ 'method3': strongMode
+ ? new Impact(parameterChecks: ['int'])
+ : new Impact(checkedModeChecks: ['int']),
+ 'method4': strongMode
+ ? new Impact(asCasts: ['int'])
+ : new Impact(checkedModeChecks: ['int'], asCasts: ['int']),
+ 'method5':
+ strongMode ? const Impact() : new Impact(checkedModeChecks: ['void']),
+ 'method6': const Impact(),
+ 'method7': const Impact(),
+ 'method8':
+ strongMode ? const Impact() : new Impact(checkedModeChecks: ['int']),
+ 'method9': strongMode
+ ? new Impact(implicitCasts: ['int'])
+ : new Impact(checkedModeChecks: ['int']),
+ 'method10': const Impact(),
+ 'method11': const Impact(),
+ 'method12': strongMode
+ ? const Impact()
+ : new Impact(checkedModeChecks: ['int', 'String']),
+ 'method13': strongMode
+ ? new Impact(implicitCasts: ['int'], parameterChecks: ['String'])
+ : new Impact(checkedModeChecks: ['int', 'String']),
+ };
+
+ CompilationResult result = await runCompiler(
+ memorySourceFiles: {'main.dart': source},
+ options: strongMode ? [Flags.strongMode] : [],
+ beforeRun: (compiler) {
+ compiler.impactCacheDeleter.retainCachesForTesting = true;
+ });
+ Expect.isTrue(result.isSuccess);
+ Compiler compiler = result.compiler;
+
+ ClosedWorld closedWorld =
+ compiler.resolutionWorldBuilder.closedWorldForTesting;
+ ElementEnvironment elementEnvironment = closedWorld.elementEnvironment;
+
+ elementEnvironment.forEachLibraryMember(elementEnvironment.mainLibrary,
+ (MemberEntity member) {
+ if (member == elementEnvironment.mainFunction) return;
+
+ Impact expectedImpact = expectedImpactMap[member.name];
+ Expect.isNotNull(expectedImpact, "Not expected impact for $member");
+ WorldImpact actualImpact = compiler.impactCache[member];
+
+ Set<TypeUse> typeUses = actualImpact.typeUses.toSet();
+
+ Set<String> asCasts = expectedImpact.asCasts.toSet();
+ Set<String> checkedModeChecks = expectedImpact.checkedModeChecks.toSet();
+ Set<String> implicitCasts = expectedImpact.implicitCasts.toSet();
+ Set<String> parameterChecks = expectedImpact.parameterChecks.toSet();
+
+ String context = 'in $member for Dart ${strongMode ? '2' : '1'}:\n'
+ 'Expected: $expectedImpact\nActual: $typeUses';
+ for (TypeUse typeUse in typeUses) {
+ String type = '${typeUse.type}';
+ switch (typeUse.kind) {
+ case TypeUseKind.AS_CAST:
+ Expect.isTrue(asCasts.contains(type), "Extra $typeUse $context");
+ asCasts.remove(type);
+ break;
+ case TypeUseKind.CHECKED_MODE_CHECK:
+ Expect.isTrue(
+ checkedModeChecks.contains(type), "Extra $typeUse $context");
+ checkedModeChecks.remove(type);
+ break;
+ case TypeUseKind.IMPLICIT_CAST:
+ Expect.isTrue(
+ implicitCasts.contains(type), "Extra $typeUse $context");
+ implicitCasts.remove(type);
+ break;
+ case TypeUseKind.PARAMETER_CHECK:
+ Expect.isTrue(
+ parameterChecks.contains(type), "Extra $typeUse $context");
+ parameterChecks.remove(type);
+ break;
+ default:
+ }
+ }
+ Expect.isTrue(asCasts.isEmpty, "Missing as casts $asCasts $context");
+ Expect.isTrue(checkedModeChecks.isEmpty,
+ "Missing checked mode checks $checkedModeChecks $context");
+ });
+}
+
+class Impact {
+ final List<String> checkedModeChecks;
+ final List<String> asCasts;
+ final List<String> implicitCasts;
+ final List<String> parameterChecks;
+
+ const Impact(
+ {this.checkedModeChecks: const <String>[],
+ this.asCasts: const <String>[],
+ this.implicitCasts: const <String>[],
+ this.parameterChecks: const <String>[]});
+
+ String toString() {
+ StringBuffer sb = new StringBuffer();
+ sb.write('Impact(');
+ String comma = '';
+ if (checkedModeChecks.isNotEmpty) {
+ sb.write('checkedModeChecks=');
+ sb.write(checkedModeChecks.join(','));
+ comma = ',';
+ }
+ if (asCasts.isNotEmpty) {
+ sb.write(comma);
+ sb.write('asCasts=');
+ sb.write(asCasts.join(','));
+ comma = ',';
+ }
+ if (implicitCasts.isNotEmpty) {
+ sb.write(comma);
+ sb.write('syntheticCasts=');
+ sb.write(implicitCasts.join(','));
+ comma = ',';
+ }
+ if (parameterChecks.isNotEmpty) {
+ sb.write(comma);
+ sb.write('parameterChecks=');
+ sb.write(parameterChecks.join(','));
+ comma = ',';
+ }
+ sb.write(')');
+ return sb.toString();
+ }
+}
diff --git a/tests/compiler/dart2js/old_frontend/analyze_helper.dart b/tests/compiler/dart2js/old_frontend/analyze_helper.dart
index 851e1e3..84dc1c1 100644
--- a/tests/compiler/dart2js/old_frontend/analyze_helper.dart
+++ b/tests/compiler/dart2js/old_frontend/analyze_helper.dart
@@ -258,11 +258,9 @@
provider,
null,
handler,
- new CompilerOptions.parse(
- libraryRoot: libraryRoot,
- packageConfig: packageConfig,
- options: options,
- environment: {}));
+ CompilerOptions.parse(options, libraryRoot: libraryRoot)
+ ..packageConfig = packageConfig
+ ..environment = {});
String MESSAGE = """
diff --git a/tests/compiler/dart2js/old_frontend/analyze_only_test.dart b/tests/compiler/dart2js/old_frontend/analyze_only_test.dart
index efe3c52..e2e1f3b 100644
--- a/tests/compiler/dart2js/old_frontend/analyze_only_test.dart
+++ b/tests/compiler/dart2js/old_frontend/analyze_only_test.dart
@@ -47,11 +47,10 @@
asyncStart();
OutputCollector outputCollector = new OutputCollector();
Future<CompilationResult> result = compile(
- new CompilerOptions.parse(
- entryPoint: new Uri(scheme: 'main'),
- libraryRoot: new Uri(scheme: 'lib', path: '/'),
- packageRoot: new Uri(scheme: 'package', path: '/'),
- options: options),
+ CompilerOptions.parse(options,
+ libraryRoot: new Uri(scheme: 'lib', path: '/'))
+ ..entryPoint = new Uri(scheme: 'main')
+ ..packageRoot = new Uri(scheme: 'package', path: '/'),
new LegacyCompilerInput(localProvider),
new LegacyCompilerDiagnostics(localHandler),
outputCollector);
@@ -165,14 +164,6 @@
Expect.isTrue(warnings.isEmpty);
});
- // Test that --allow-native-extensions works.
- runCompiler("""main() {}
- foo() native 'foo';""", [Flags.analyzeOnly, Flags.allowNativeExtensions],
- (String code, List errors, List warnings) {
- Expect.isNull(code);
- Expect.isTrue(errors.isEmpty);
- Expect.isTrue(warnings.isEmpty);
- });
runCompiler("""main() {}
foo() native 'foo';""", [Flags.analyzeOnly],
(String code, List errors, List warnings) {
diff --git a/tests/compiler/dart2js/old_frontend/bad_loop_test.dart b/tests/compiler/dart2js/old_frontend/bad_loop_test.dart
index 8148664..69d2490 100644
--- a/tests/compiler/dart2js/old_frontend/bad_loop_test.dart
+++ b/tests/compiler/dart2js/old_frontend/bad_loop_test.dart
@@ -35,10 +35,10 @@
provider,
new LegacyCompilerOutput(),
new LegacyCompilerDiagnostics(diagnosticHandler),
- new CompilerOptions(
- libraryRoot: libraryRoot,
- useKernel: false,
- packageRoot: packageRoot));
+ new CompilerOptions()
+ ..libraryRoot = libraryRoot
+ ..useKernel = false
+ ..packageRoot = packageRoot);
asyncTest(() => compiler.run(Uri.parse('memory:main.dart')).then((_) {
Expect.isTrue(compiler.compilationFailed);
Expect.equals(5, errorCount);
diff --git a/tests/compiler/dart2js/old_frontend/library_resolution_test.dart b/tests/compiler/dart2js/old_frontend/library_resolution_test.dart
index a698aba..190bea2 100644
--- a/tests/compiler/dart2js/old_frontend/library_resolution_test.dart
+++ b/tests/compiler/dart2js/old_frontend/library_resolution_test.dart
@@ -37,10 +37,10 @@
provider,
const NullCompilerOutput(),
handler,
- new CompilerOptions(
- libraryRoot: libraryRoot,
- useKernel: false,
- packageConfig: packageConfig));
+ new CompilerOptions()
+ ..libraryRoot = libraryRoot
+ ..useKernel = false
+ ..packageConfig = packageConfig);
}
main() async {
diff --git a/tests/compiler/dart2js/old_frontend/mock_compiler.dart b/tests/compiler/dart2js/old_frontend/mock_compiler.dart
index 1ecfdfe..2bb5bee 100644
--- a/tests/compiler/dart2js/old_frontend/mock_compiler.dart
+++ b/tests/compiler/dart2js/old_frontend/mock_compiler.dart
@@ -77,7 +77,6 @@
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,
@@ -90,22 +89,21 @@
LibrarySourceProvider this.librariesOverride})
: sourceFiles = new Map<String, SourceFile>(),
super(
- options: new CompilerOptions(
- entryPoint: new Uri(scheme: 'mock'),
- libraryRoot: Uri.parse('placeholder_library_root_for_mock/'),
- useKernel: false,
- enableTypeAssertions: enableTypeAssertions,
- enableUserAssertions: enableUserAssertions,
- disableInlining: disableInlining,
- enableAssertMessage: true,
- enableMinification: enableMinification,
- disableTypeInference: disableTypeInference,
- analyzeAll: analyzeAll,
- analyzeOnly: analyzeOnly,
- preserveComments: preserveComments,
- trustTypeAnnotations: trustTypeAnnotations,
- trustJSInteropTypeAnnotations: trustJSInteropTypeAnnotations,
- shownPackageWarnings: const []),
+ options: new CompilerOptions()
+ ..entryPoint = new Uri(scheme: 'mock')
+ ..libraryRoot = Uri.parse('placeholder_library_root_for_mock/')
+ ..useKernel = false
+ ..enableTypeAssertions = enableTypeAssertions
+ ..enableUserAssertions = enableUserAssertions
+ ..disableInlining = disableInlining
+ ..enableAssertMessage = true
+ ..enableMinification = enableMinification
+ ..disableTypeInference = disableTypeInference
+ ..analyzeAll = analyzeAll
+ ..analyzeOnly = analyzeOnly
+ ..trustTypeAnnotations = trustTypeAnnotations
+ ..trustJSInteropTypeAnnotations = trustJSInteropTypeAnnotations
+ ..shownPackageWarnings = const [],
outputProvider: outputProvider) {
deferredLoadTask = new MockDeferredLoadTask(this);
diff --git a/tests/compiler/dart2js/old_frontend/mock_libraries.dart b/tests/compiler/dart2js/old_frontend/mock_libraries.dart
index 3544485..6e8a3ee 100644
--- a/tests/compiler/dart2js/old_frontend/mock_libraries.dart
+++ b/tests/compiler/dart2js/old_frontend/mock_libraries.dart
@@ -207,6 +207,9 @@
'functionTypeTest': r'functionTypeTest(f, t) {}',
'functionTypeCast': r'functionTypeCast(f, t) { return f; }',
'functionTypeCheck': r'functionTypeCheck(f, t) { return f; }',
+ 'futureOrTest': r'futureOrTest(f, t) {}',
+ 'futureOrCast': r'futureOrCast(f, t) { return f; }',
+ 'futureOrCheck': r'futureOrCheck(f, t) { return f; }',
'getFallThroughError': 'getFallThroughError() {}',
'getIsolateAffinityTag': 'getIsolateAffinityTag(_) {}',
'getRuntimeTypeArgument':
@@ -473,6 +476,5 @@
const String DEFAULT_JS_MIRRORS_SOURCE = r'''
disableTreeShaking(){}
preserveMetadata(){}
-preserveUris(){}
preserveLibraryNames(){}
''';
diff --git a/tests/compiler/dart2js/output_type_test.dart b/tests/compiler/dart2js/output_type_test.dart
index 34c18a1..ae79f4e 100644
--- a/tests/compiler/dart2js/output_type_test.dart
+++ b/tests/compiler/dart2js/output_type_test.dart
@@ -116,17 +116,6 @@
]..addAll(additionOptionals),
expectedOutput,
useKernel: useKernel);
-
- if (!useKernel) {
- // Option --resolve-only is only supported for the old frontend.
- await test([
- 'tests/compiler/dart2js/deferred/data/deferred_helper.dart',
- '--out=custom.data',
- '--resolve-only',
- ], [
- 'custom.data',
- ], useKernel: useKernel);
- }
}
asyncTest(() async {
diff --git a/tests/compiler/dart2js/rti/data/future_or_future_or_generic_strong.dart b/tests/compiler/dart2js/rti/data/future_or_future_or_generic_strong.dart
new file mode 100644
index 0000000..32b28d9
--- /dev/null
+++ b/tests/compiler/dart2js/rti/data/future_or_future_or_generic_strong.dart
@@ -0,0 +1,22 @@
+// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+import 'dart:async';
+
+/*class: global#Future:deps=[A],implicit=[Future<B<A.T>>,Future<C>],indirect,needsArgs*/
+
+/*class: A:explicit=[FutureOr<B<A.T>>],implicit=[B<A.T>,Future<B<A.T>>],indirect,needsArgs*/
+class A<T> {
+ m(o) => o is FutureOr<B<T>>;
+}
+
+/*class: B:deps=[A],explicit=[FutureOr<B<A.T>>],implicit=[B<A.T>,Future<B<A.T>>],needsArgs*/
+class B<T> {}
+
+/*class: C:implicit=[C,Future<C>,FutureOr<C>]*/
+class C {}
+
+main() {
+ new A<FutureOr<C>>().m(new B<C>());
+}
diff --git a/tests/compiler/dart2js/rti/data/future_or_future_or_strong.dart b/tests/compiler/dart2js/rti/data/future_or_future_or_strong.dart
new file mode 100644
index 0000000..4f825b0
--- /dev/null
+++ b/tests/compiler/dart2js/rti/data/future_or_future_or_strong.dart
@@ -0,0 +1,14 @@
+// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+import 'dart:async';
+
+/*class: global#Future:implicit=[Future<A>,Future<FutureOr<A>>],indirect,needsArgs*/
+
+/*class: A:explicit=[FutureOr<FutureOr<A>>],implicit=[A,Future<A>,Future<FutureOr<A>>,FutureOr<A>]*/
+class A {}
+
+main() {
+ new A() is FutureOr<FutureOr<A>>;
+}
diff --git a/tests/compiler/dart2js/rti/data/future_or_generic2_strong.dart b/tests/compiler/dart2js/rti/data/future_or_generic2_strong.dart
new file mode 100644
index 0000000..8e588cf
--- /dev/null
+++ b/tests/compiler/dart2js/rti/data/future_or_generic2_strong.dart
@@ -0,0 +1,22 @@
+// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+import 'dart:async';
+
+/*class: global#Future:deps=[A],implicit=[Future<B<A.T>>],indirect,needsArgs*/
+
+/*class: A:explicit=[FutureOr<B<A.T>>],implicit=[B<A.T>,Future<B<A.T>>],indirect,needsArgs*/
+class A<T> {
+ m(o) => o is FutureOr<B<T>>;
+}
+
+/*class: B:deps=[A],explicit=[FutureOr<B<A.T>>],implicit=[B<A.T>,Future<B<A.T>>],needsArgs*/
+class B<T> {}
+
+/*class: C:implicit=[C]*/
+class C {}
+
+main() {
+ new A<C>().m(new B<C>());
+}
diff --git a/tests/compiler/dart2js/rti/data/future_or_generic_strong.dart b/tests/compiler/dart2js/rti/data/future_or_generic_strong.dart
new file mode 100644
index 0000000..84291b90
--- /dev/null
+++ b/tests/compiler/dart2js/rti/data/future_or_generic_strong.dart
@@ -0,0 +1,20 @@
+// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+import 'dart:async';
+
+/*class: global#Future:deps=[A],implicit=[Future<A.T>],indirect,needsArgs*/
+
+/*class: A:explicit=[FutureOr<A.T>],implicit=[A.T,Future<A.T>],indirect,needsArgs*/
+class A<T> {
+ m(o) => o is FutureOr<T>;
+}
+
+// TODO(johnniwinther): Do we need the implied `Future<B>` test in `A.m`?
+/*class: B:implicit=[B]*/
+class B {}
+
+main() {
+ new A<B>().m(new B());
+}
diff --git a/tests/compiler/dart2js/rti/data/future_or_strong.dart b/tests/compiler/dart2js/rti/data/future_or_strong.dart
new file mode 100644
index 0000000..f39c148
--- /dev/null
+++ b/tests/compiler/dart2js/rti/data/future_or_strong.dart
@@ -0,0 +1,14 @@
+// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+import 'dart:async';
+
+/*class: global#Future:implicit=[Future<A>],indirect,needsArgs*/
+
+/*class: A:explicit=[FutureOr<A>],implicit=[A,Future<A>]*/
+class A {}
+
+main() {
+ new A() is FutureOr<A>;
+}
diff --git a/tests/compiler/dart2js/rti/emission/future_or_as_type_argument_strong.dart b/tests/compiler/dart2js/rti/emission/future_or_as_type_argument_strong.dart
new file mode 100644
index 0000000..c1ca45b
--- /dev/null
+++ b/tests/compiler/dart2js/rti/emission/future_or_as_type_argument_strong.dart
@@ -0,0 +1,27 @@
+// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+import 'dart:async';
+import 'package:expect/expect.dart';
+
+/*class: global#Future:checks=[],typeArgument*/
+
+/*class: A:checkedInstance,checks=[],instance*/
+class A<T> {}
+
+/*class: B:checks=[],typeArgument*/
+class B {}
+
+/*class: C:checks=[],typeArgument*/
+class C {}
+
+@NoInline()
+test(o) => o as A<FutureOr<B>>;
+
+main() {
+ test(new A<B>());
+ test(new A<Future<B>>());
+ test(new A<C>());
+ test(new A<Future<C>>());
+}
diff --git a/tests/compiler/dart2js/rti/emission/future_or_future_or_generic_strong.dart b/tests/compiler/dart2js/rti/emission/future_or_future_or_generic_strong.dart
new file mode 100644
index 0000000..41a9baf
--- /dev/null
+++ b/tests/compiler/dart2js/rti/emission/future_or_future_or_generic_strong.dart
@@ -0,0 +1,28 @@
+// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+import 'dart:async';
+import 'package:expect/expect.dart';
+
+/*class: global#Future:checkedInstance*/
+
+/*class: A:checks=[],instance*/
+class A<T> {
+ @NoInline()
+ m(o) => o is FutureOr<B<T>>;
+}
+
+/*class: B:checkedInstance,checkedTypeArgument,checks=[],instance,typeArgument*/
+class B<T> {}
+
+/*class: C:checkedInstance,checkedTypeArgument,checks=[],typeArgument*/
+class C {}
+
+/*class: D:checkedInstance,checkedTypeArgument,checks=[],typeArgument*/
+class D {}
+
+main() {
+ Expect.isTrue(new A<FutureOr<C>>().m(new B<C>()));
+ Expect.isFalse(new A<FutureOr<D>>().m(new B<C>()));
+}
diff --git a/tests/compiler/dart2js/rti/emission/future_or_future_or_strong.dart b/tests/compiler/dart2js/rti/emission/future_or_future_or_strong.dart
new file mode 100644
index 0000000..c667d0d
--- /dev/null
+++ b/tests/compiler/dart2js/rti/emission/future_or_future_or_strong.dart
@@ -0,0 +1,22 @@
+// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+import 'dart:async';
+import 'package:expect/expect.dart';
+
+/*class: global#Future:checkedInstance*/
+
+/*class: A:checkedInstance,checkedTypeArgument,checks=[],instance,typeArgument*/
+class A {}
+
+/*class: B:checks=[],instance*/
+class B {}
+
+@NoInline()
+test(o) => o is FutureOr<FutureOr<A>>;
+
+main() {
+ Expect.isTrue(test(new A()));
+ Expect.isFalse(test(new B()));
+}
diff --git a/tests/compiler/dart2js/rti/emission/future_or_generic2_strong.dart b/tests/compiler/dart2js/rti/emission/future_or_generic2_strong.dart
new file mode 100644
index 0000000..efbac15
--- /dev/null
+++ b/tests/compiler/dart2js/rti/emission/future_or_generic2_strong.dart
@@ -0,0 +1,28 @@
+// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+import 'dart:async';
+import 'package:expect/expect.dart';
+
+/*class: global#Future:checkedInstance*/
+
+/*class: A:checks=[],instance*/
+class A<T> {
+ @NoInline()
+ m(o) => o is FutureOr<B<T>>;
+}
+
+/*class: B:checkedInstance,checkedTypeArgument,checks=[],instance,typeArgument*/
+class B<T> {}
+
+/*class: C:checkedInstance,checks=[],typeArgument*/
+class C {}
+
+/*class: D:checkedInstance,checks=[],typeArgument*/
+class D {}
+
+main() {
+ Expect.isTrue(new A<C>().m(new B<C>()));
+ Expect.isFalse(new A<D>().m(new B<C>()));
+}
diff --git a/tests/compiler/dart2js/rti/emission/future_or_generic_strong.dart b/tests/compiler/dart2js/rti/emission/future_or_generic_strong.dart
new file mode 100644
index 0000000..114f59e
--- /dev/null
+++ b/tests/compiler/dart2js/rti/emission/future_or_generic_strong.dart
@@ -0,0 +1,53 @@
+// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+import 'dart:async';
+import 'package:expect/expect.dart';
+
+/*class: global#Future:checkedInstance*/
+
+/*class: A:checks=[],instance*/
+class A<T> {
+ @NoInline()
+ m(o) => o is FutureOr<T>;
+}
+
+/*class: B:checkedInstance,checks=[],instance,typeArgument*/
+class B {}
+
+// TODO(johnniwinther): Do we need the implied `checkedTypeArgument` from
+// the `Future<C>` test in `A.m`?
+/*class: C:checkedInstance,checks=[],typeArgument*/
+class C {}
+
+/*class: FutureMock:checks=[$isFuture],instance*/
+class FutureMock<T> implements Future<T> {
+ final T value;
+
+ FutureMock(this.value);
+
+ @override
+ Future<T> timeout(Duration timeLimit, {FutureOr<T> onTimeout()}) => null;
+
+ @override
+ Stream<T> asStream() => null;
+
+ @override
+ Future<T> whenComplete(FutureOr action()) => null;
+
+ @override
+ Future<T> catchError(Function onError, {bool test(bool test(Object error))}) {
+ return null;
+ }
+
+ @override
+ Future<S> then<S>(FutureOr<S> onValue(T value), {Function onError}) => null;
+}
+
+main() {
+ Expect.isTrue(new A<B>().m(new B()));
+ Expect.isTrue(new A<B>().m(new FutureMock<B>(new B())));
+ Expect.isFalse(new A<C>().m(new B()));
+ Expect.isFalse(new A<C>().m(new FutureMock<B>(new B())));
+}
diff --git a/tests/compiler/dart2js/rti/emission/future_or_strong.dart b/tests/compiler/dart2js/rti/emission/future_or_strong.dart
new file mode 100644
index 0000000..e7a0cf8
--- /dev/null
+++ b/tests/compiler/dart2js/rti/emission/future_or_strong.dart
@@ -0,0 +1,48 @@
+// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+import 'dart:async';
+import 'package:expect/expect.dart';
+
+/*class: global#Future:checkedInstance*/
+
+/*class: A:checkedInstance,checkedTypeArgument,checks=[],instance,typeArgument*/
+class A {}
+
+/*class: B:checkedInstance,checks=[],instance,typeArgument*/
+class B {}
+
+/*class: FutureMock:checks=[$isFuture],instance*/
+class FutureMock<T> implements Future<T> {
+ final T value;
+
+ FutureMock(this.value);
+
+ @override
+ Future<T> timeout(Duration timeLimit, {FutureOr<T> onTimeout()}) => null;
+
+ @override
+ Stream<T> asStream() => null;
+
+ @override
+ Future<T> whenComplete(FutureOr action()) => null;
+
+ @override
+ Future<T> catchError(Function onError, {bool test(bool test(Object error))}) {
+ return null;
+ }
+
+ @override
+ Future<S> then<S>(FutureOr<S> onValue(T value), {Function onError}) => null;
+}
+
+@NoInline()
+test(o) => o is FutureOr<A>;
+
+main() {
+ Expect.isTrue(test(new A()));
+ Expect.isTrue(test(new FutureMock<A>(new A())));
+ Expect.isFalse(test(new B()));
+ Expect.isFalse(test(new FutureMock<B>(new B())));
+}
diff --git a/tests/compiler/dart2js/rti/emission/future_or_type_argument_strong.dart b/tests/compiler/dart2js/rti/emission/future_or_type_argument_strong.dart
new file mode 100644
index 0000000..ac9a440
--- /dev/null
+++ b/tests/compiler/dart2js/rti/emission/future_or_type_argument_strong.dart
@@ -0,0 +1,27 @@
+// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+import 'dart:async';
+import 'package:expect/expect.dart';
+
+/*class: global#Future:checks=[],typeArgument*/
+
+/*class: A:checkedInstance,checks=[],instance*/
+class A<T> {}
+
+/*class: B:checks=[],typeArgument*/
+class B {}
+
+/*class: C:checks=[],typeArgument*/
+class C {}
+
+@NoInline()
+test(o) => o is A<FutureOr<B>>;
+
+main() {
+ Expect.isTrue(test(new A<B>()));
+ Expect.isTrue(test(new A<Future<B>>()));
+ Expect.isFalse(test(new A<C>()));
+ Expect.isFalse(test(new A<Future<C>>()));
+}
diff --git a/tests/compiler/dart2js/rti/rti_need_test.dart b/tests/compiler/dart2js/rti/rti_need_test.dart
index 5f30dc5..053b43b 100644
--- a/tests/compiler/dart2js/rti/rti_need_test.dart
+++ b/tests/compiler/dart2js/rti/rti_need_test.dart
@@ -238,6 +238,11 @@
bool visitTypeVariableType(TypeVariableType type, _) {
return type.element.typeDeclaration == entity;
}
+
+ @override
+ bool visitFutureOrType(FutureOrType type, _) {
+ return type.typeArgument.accept(this, null);
+ }
}
abstract class AstMixin implements ComputeValueMixin<ast.Node> {
diff --git a/tests/compiler/dart2js/type_test_helper.dart b/tests/compiler/dart2js/type_test_helper.dart
index f515c66..6a03262 100644
--- a/tests/compiler/dart2js/type_test_helper.dart
+++ b/tests/compiler/dart2js/type_test_helper.dart
@@ -232,7 +232,7 @@
} else if (member is FunctionEntity) {
return elementEnvironment.getFunctionType(member);
}
- throw 'Unexpected member: $member';
+ throw 'Unexpected member: $member for ${name}, cls=$cls';
}
DartType getClosureType(String name, [ClassEntity cls]) {
diff --git a/tests/compiler/dart2js/uri_retention_test.dart b/tests/compiler/dart2js/uri_retention_test.dart
index 43bd12b..782e0f7 100644
--- a/tests/compiler/dart2js/uri_retention_test.dart
+++ b/tests/compiler/dart2js/uri_retention_test.dart
@@ -12,11 +12,9 @@
import 'package:expect/expect.dart';
import 'memory_compiler.dart' show runCompiler, OutputCollector;
-Future<String> compileSources(sources,
- {bool minify, bool preserveUri, bool useKernel}) async {
+Future<String> compileSources(sources, {bool minify, bool useKernel}) async {
var options = [];
if (minify) options.add(Flags.minify);
- if (preserveUri) options.add(Flags.preserveUris);
if (!useKernel) options.add(Flags.useOldFrontend);
OutputCollector outputCollector = new OutputCollector();
await runCompiler(
@@ -27,22 +25,17 @@
}
Future test(sources, {bool libName, bool fileName, bool useKernel}) {
- return compileSources(sources,
- minify: false, preserveUri: false, useKernel: useKernel).then((output) {
+ return compileSources(sources, minify: false, useKernel: useKernel)
+ .then((output) {
// Unminified the sources should always contain the library name and the
// file name.
Expect.isTrue(output.contains("main_lib"));
Expect.isTrue(output.contains("main.dart"));
}).then((_) {
- compileSources(sources, minify: true, preserveUri: false).then((output) {
+ compileSources(sources, minify: true, useKernel: useKernel).then((output) {
Expect.equals(libName, output.contains("main_lib"));
Expect.isFalse(output.contains("main.dart"));
});
- }).then((_) {
- compileSources(sources, minify: true, preserveUri: true).then((output) {
- Expect.equals(libName, output.contains("main_lib"));
- Expect.equals(fileName, output.contains("main.dart"));
- });
});
}
diff --git a/tests/corelib/corelib.status b/tests/corelib/corelib.status
index bf64735..858757d 100644
--- a/tests/corelib/corelib.status
+++ b/tests/corelib/corelib.status
@@ -2,6 +2,8 @@
# 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.
+maps_test: Skip # Maps class no longer exists
+
[ $compiler == dart2analyzer ]
*: Skip
diff --git a/tests/corelib_2/apply_generic_function_test.dart b/tests/corelib_2/apply_generic_function_test.dart
new file mode 100644
index 0000000..47349fd
--- /dev/null
+++ b/tests/corelib_2/apply_generic_function_test.dart
@@ -0,0 +1,21 @@
+// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
+// for details. All rights reserved. Use of this source code is governed by a
+// BSD-style license that can be found in the LICENSE file.
+
+import "package:expect/expect.dart";
+import "symbol_map_helper.dart";
+
+// Testing Function.apply calls correctly with generic type arguments.
+// This test is not testing error handling, only that correct parameters
+// cause a correct call.
+
+test0<T extends num>(T i, T j, {T a}) => i + j + a;
+
+main() {
+ test(res, func, list, map) {
+ map = symbolMapToStringMap(map);
+ Expect.equals(res, Function.apply(func, list, map));
+ }
+
+ test(42, test0, [10, 15], {"a": 17});
+}
diff --git a/tests/corelib_2/corelib_2.status b/tests/corelib_2/corelib_2.status
index 2890a4f..b88cc46 100644
--- a/tests/corelib_2/corelib_2.status
+++ b/tests/corelib_2/corelib_2.status
@@ -3,6 +3,8 @@
# BSD-style license that can be found in the LICENSE file.
iterable_where_type_test: RuntimeError # Disabled. Issue 32463
+maps_test: Skip # Maps class no longer exists
+
[ $compiler == dart2analyzer ]
bigint_from_test: CompileTimeError # Issue 32585
compare_to2_test: CompileTimeError # invalid test
@@ -13,7 +15,6 @@
[ $compiler == dart2js ]
bigint_from_test: RuntimeError # Issue 32589
date_time11_test: RuntimeError, Pass # Fails when US is on winter time, issue 31285.
-int_parse_radix_test/badTypes: RuntimeError # wrong exception returned
iterable_where_type_test: RuntimeError # issue 31718
list_unmodifiable_test: Pass, RuntimeError # Issue 28712
@@ -87,9 +88,6 @@
[ !$strong ]
cast_test: SkipByDesign # Uses generic method parameters.
-[ $arch == ia32 && $builder_tag == optimization_counter_threshold ]
-bigint_from_test: RuntimeError # Issue 32619
-
[ $arch == simarmv5te && ($runtime == dart_precompiled || $runtime == vm) ]
int_parse_radix_test/*: Pass, Slow
integer_parsed_mul_div_vm_test: Pass, Slow
@@ -227,9 +225,7 @@
integer_to_radix_string_test/02: RuntimeError
integer_to_radix_string_test/none: RuntimeError
integer_to_string_test/01: RuntimeError
-iterable_fold_test: Crash # NoSuchMethodError: The getter 'isDynamic' was called on null.
iterable_followed_by_test: RuntimeError
-iterable_reduce_test: Crash # NoSuchMethodError: The getter 'isDynamic' was called on null.
iterable_return_type_test/01: RuntimeError # Issue 20085
iterable_return_type_test/02: RuntimeError # Dart2js does not support Uint64*.
iterable_to_list_test/01: RuntimeError # Issue 26501
@@ -278,9 +274,7 @@
integer_to_radix_string_test/02: RuntimeError
integer_to_radix_string_test/none: RuntimeError
integer_to_string_test/01: RuntimeError
-iterable_fold_test: Crash # NoSuchMethodError: The getter 'isDynamic' was called on null.
iterable_followed_by_test: RuntimeError
-iterable_reduce_test: Crash # NoSuchMethodError: The getter 'isDynamic' was called on null.
iterable_return_type_test/01: RuntimeError # Issue 20085
iterable_return_type_test/02: RuntimeError # Dart2js does not support Uint64*.
iterable_to_list_test/01: RuntimeError # Issue 26501
@@ -307,10 +301,10 @@
splay_tree_from_iterable_test: RuntimeError
string_from_list_test: RuntimeError
string_fromcharcodes_test: RuntimeError
-string_replace_test: Crash # NoSuchMethodError: The getter 'isDynamic' was called on null.
string_split_test/checkedstore: RuntimeError # Issue 30548: does not check stores into List<String>
string_split_test/none: RuntimeError
string_test: RuntimeError
+string_replace_test: RuntimeError
symbol_operator_test/03: RuntimeError
symbol_operator_test/none: RuntimeError
symbol_reserved_word_test/03: RuntimeError # Issue 19972, new Symbol('void') should be allowed.
@@ -319,7 +313,6 @@
uri_test: RuntimeError
[ $compiler == dart2js && $fasta && $strong ]
-map_update_test: Crash # Issue 32453
null_nosuchmethod_test: RuntimeError # Fails if type checks are skipped.
shuffle_test: RuntimeError
@@ -369,6 +362,7 @@
# ===== dartk + vm status lines =====
[ $compiler == dartk && $runtime == vm && $strong ]
apply3_test: RuntimeError
+apply_generic_function_test: RuntimeError
iterable_fold_test/02: RuntimeError
iterable_reduce_test/01: CompileTimeError # Issue 31533
iterable_reduce_test/none: RuntimeError
@@ -383,6 +377,7 @@
apply_test/01: RuntimeError
[ $compiler == dartkp && $runtime == dart_precompiled && $strong ]
+apply_generic_function_test: RuntimeError
iterable_fold_test/02: RuntimeError
iterable_reduce_test/01: CompileTimeError # Issue 31533
iterable_reduce_test/none: RuntimeError
diff --git a/tests/html/cssstyledeclaration_test.dart b/tests/html/cssstyledeclaration_test.dart
index 85257e0..9f69daf 100644
--- a/tests/html/cssstyledeclaration_test.dart
+++ b/tests/html/cssstyledeclaration_test.dart
@@ -115,13 +115,13 @@
treeSanitizer: new NullTreeSanitizer());
document.documentElement.children.add(listElement);
- var elements = document.queryAll('li');
+ var elements = document.querySelectorAll('li');
expect(elements.style.backgroundColor, equals('red'));
expect(elements.style.borderLeftWidth, equals('10px'));
- elements = document.queryAll('.baz');
+ elements = document.querySelectorAll('.baz');
expect(elements.style.backgroundColor, equals('black'));
expect(elements.style.borderLeftWidth, equals(''));
- elements = document.queryAll('.bar');
+ elements = document.querySelectorAll('.bar');
expect(elements.style.backgroundColor, equals('red'));
});
@@ -135,25 +135,25 @@
treeSanitizer: new NullTreeSanitizer());
document.documentElement.children.add(listElement);
- var elements = document.queryAll('li');
+ var elements = document.querySelectorAll('li');
elements.style.backgroundColor = 'green';
expect(elements.style.backgroundColor, equals('green'));
expect(elements.style.borderLeftWidth, equals('10px'));
- elements = document.queryAll('.baz');
+ elements = document.querySelectorAll('.baz');
expect(elements.style.backgroundColor, equals('green'));
elements.style.backgroundColor = 'yellow';
expect(elements.style.backgroundColor, equals('yellow'));
expect(elements.style.borderLeftWidth, equals(''));
- elements = document.queryAll('.bar');
+ elements = document.querySelectorAll('.bar');
expect(elements.style.backgroundColor, equals('green'));
- elements = document.queryAll('#wat');
+ elements = document.querySelectorAll('#wat');
expect(elements.style.backgroundColor, equals('yellow'));
elements.style.borderLeftWidth = '18px';
expect(elements.style.borderLeftWidth, equals('18px'));
- elements = document.queryAll('li');
+ elements = document.querySelectorAll('li');
expect(elements.style.borderLeftWidth, equals('10px'));
});
diff --git a/tests/html/custom/created_callback_test.dart b/tests/html/custom/created_callback_test.dart
index 48d2ff1..30602c9 100644
--- a/tests/html/custom/created_callback_test.dart
+++ b/tests/html/custom/created_callback_test.dart
@@ -36,12 +36,12 @@
return;
}
- var t = div.query('#t');
- var v = div.query('#v');
- var w = div.query('#w');
+ var t = div.querySelector('#t');
+ var v = div.querySelector('#v');
+ var w = div.querySelector('#w');
- expect(query('x-b:not(:unresolved)'), this);
- expect(queryAll(':unresolved'), [v, w]);
+ expect(querySelector('x-b:not(:unresolved)'), this);
+ expect(querySelectorAll(':unresolved'), [v, w]);
// As per:
// http://www.w3.org/TR/2013/WD-custom-elements-20130514/#serializing-and-parsing
@@ -94,7 +94,7 @@
upgradeCustomElements(div);
expect(C.createdInvocations, 2);
- expect(div.query('#w') is B, isTrue);
+ expect(div.querySelector('#w') is B, isTrue);
});
test('nesting of constructors', NestedElement.test);
diff --git a/tests/html/custom_elements_test.dart b/tests/html/custom_elements_test.dart
index 9f7b210..3b19e1b 100644
--- a/tests/html/custom_elements_test.dart
+++ b/tests/html/custom_elements_test.dart
@@ -139,7 +139,7 @@
treeSanitizer: new NullTreeSanitizer());
upgradeCustomElements(element);
document.body.nodes.add(element);
- var queried = query(tag);
+ var queried = querySelector(tag);
expect(queried, isNotNull);
expect(queried is CustomType, isTrue);
@@ -154,7 +154,7 @@
treeSanitizer: new NullTreeSanitizer());
upgradeCustomElements(element);
document.body.nodes.add(element);
- var queried = query('#someid');
+ var queried = querySelector('#someid');
expect(queried, isNotNull);
expect(queried is CustomType, isTrue);
diff --git a/tests/html/custom_tags_test.dart b/tests/html/custom_tags_test.dart
index 78e61ca..1010d76 100644
--- a/tests/html/custom_tags_test.dart
+++ b/tests/html/custom_tags_test.dart
@@ -16,10 +16,10 @@
var element = new Element.tag('x-basic1')..id = 'basic1';
document.body.nodes.add(element);
- var queryById = query('#basic1');
+ var queryById = querySelector('#basic1');
expect(queryById, equals(element));
- var queryByTag = queryAll('x-basic1');
+ var queryByTag = querySelectorAll('x-basic1');
expect(queryByTag.length, equals(1));
expect(queryByTag[0], equals(element));
});
@@ -30,10 +30,10 @@
treeSanitizer: new NullTreeSanitizer());
document.body.nodes.add(element);
- var queryById = query('#basic2');
+ var queryById = querySelector('#basic2');
expect(queryById is Element, isTrue);
- var queryByTag = queryAll('x-basic2');
+ var queryByTag = querySelectorAll('x-basic2');
expect(queryByTag.length, equals(1));
expect(queryByTag[0], equals(queryById));
});
@@ -44,7 +44,7 @@
treeSanitizer: new NullTreeSanitizer());
document.body.nodes.add(element);
- var queryById = query('#basic3');
+ var queryById = querySelector('#basic3');
expect(queryById is DivElement, isTrue);
});
}
diff --git a/tests/html/dart_object_local_storage_test.dart b/tests/html/dart_object_local_storage_test.dart
index 2d75be4..2213ab7 100644
--- a/tests/html/dart_object_local_storage_test.dart
+++ b/tests/html/dart_object_local_storage_test.dart
@@ -29,7 +29,7 @@
expect(sessionStorage, equals(window.sessionStorage));
});
test('unknown', () {
- var test = document.query('#test');
+ var test = document.querySelector('#test');
expect(element, equals(test));
});
}
diff --git a/tests/html/datalistelement_test.dart b/tests/html/datalistelement_test.dart
index 346eb5e..131ceb1 100644
--- a/tests/html/datalistelement_test.dart
+++ b/tests/html/datalistelement_test.dart
@@ -40,22 +40,22 @@
test('is', () {
expect(() {
- var list = document.query('#browsers');
+ var list = document.querySelector('#browsers');
expect(list, isDataListElement);
}, expectation);
});
test('list', () {
expect(() {
- var list = document.query('#browsers');
- var input = document.query('#input');
+ var list = document.querySelector('#browsers');
+ var input = document.querySelector('#input');
expect(input.list, list);
}, expectation);
});
test('options', () {
expect(() {
- var options = document.query('#browsers').options;
+ var options = document.querySelector('#browsers').options;
expect(options.length, 5);
}, expectation);
});
diff --git a/tests/html/document_test.dart b/tests/html/document_test.dart
index ab3ff79..a315263 100644
--- a/tests/html/document_test.dart
+++ b/tests/html/document_test.dart
@@ -36,7 +36,7 @@
</ResultSet>''',
'text/xml');
- var rs = doc.query('ResultSet');
+ var rs = doc.querySelector('ResultSet');
expect(rs, isNotNull);
});
@@ -54,7 +54,7 @@
expect(doc.adoptNode(div), div);
expect(div.ownerDocument, doc);
doc.body.nodes.add(div);
- expect(doc.query('#foo').text, 'bar');
+ expect(doc.querySelector('#foo').text, 'bar');
});
test('importNode', () {
@@ -64,7 +64,7 @@
expect(div2, isNot(equals(div)));
expect(div2.ownerDocument, doc);
doc.body.nodes.add(div2);
- expect(doc.query('#foo').text, 'bar');
+ expect(doc.querySelector('#foo').text, 'bar');
});
test('typeTest1', () {
diff --git a/tests/html/documentfragment_test.dart b/tests/html/documentfragment_test.dart
index f2c42a6..70a4a3f 100644
--- a/tests/html/documentfragment_test.dart
+++ b/tests/html/documentfragment_test.dart
@@ -181,7 +181,8 @@
test('query searches the fragment', () {
var fragment = new DocumentFragment.html(
"<div class='foo'><a>foo</a><b>bar</b></div>");
- expect(fragment.query(".foo a").tagName, "A");
- expect(_nodeStrings(fragment.queryAll(".foo *")), equals(["A", "B"]));
+ expect(fragment.querySelector(".foo a").tagName, "A");
+ expect(
+ _nodeStrings(fragment.querySelectorAll(".foo *")), equals(["A", "B"]));
});
}
diff --git a/tests/html/element_classes_test.dart b/tests/html/element_classes_test.dart
index 85a5f41d..d9341b9 100644
--- a/tests/html/element_classes_test.dart
+++ b/tests/html/element_classes_test.dart
@@ -283,7 +283,7 @@
test('listClasses=', () {
var elements = listElementSetup();
elements.classes = ['foo', 'qux'];
- elements = document.queryAll('li');
+ elements = document.querySelectorAll('li');
for (Element e in elements) {
expect(e.classes, orderedEquals(['foo', 'qux']));
expect(extractClasses(e), orderedEquals(['foo', 'qux']));
diff --git a/tests/html/element_dimensions_test.dart b/tests/html/element_dimensions_test.dart
index d68af21..32df16b 100644
--- a/tests/html/element_dimensions_test.dart
+++ b/tests/html/element_dimensions_test.dart
@@ -46,7 +46,7 @@
setUp(initDiv);
test('contentEdge.height', () {
- var all1 = queryAll('#test');
+ var all1 = querySelectorAll('#test');
expect(all1.contentEdge.height, 10);
expect(all1[0].getComputedStyle().getPropertyValue('height'), '10px');
@@ -72,7 +72,7 @@
});
test('contentEdge.height with border-box', () {
- var all1 = queryAll('#test');
+ var all1 = querySelectorAll('#test');
div.style.boxSizing = 'border-box';
expect(all1.contentEdge.height, 2);
div.style.padding = '20pc';
@@ -82,7 +82,7 @@
});
test('contentEdge.width', () {
- var all1 = queryAll('#test');
+ var all1 = querySelectorAll('#test');
expect(all1.contentEdge.width, 11);
expect(all1[0].getComputedStyle().getPropertyValue('width'), '11px');
@@ -105,7 +105,7 @@
});
test('contentEdge.width with border-box', () {
- var all1 = queryAll('#test');
+ var all1 = querySelectorAll('#test');
div.style.boxSizing = 'border-box';
expect(all1.contentEdge.width, 3);
div.style.padding = '20pc';
@@ -115,7 +115,7 @@
});
test('paddingEdge.height', () {
- var all1 = queryAll('#test');
+ var all1 = querySelectorAll('#test');
expect(all1.paddingEdge.height, 18);
all1[0].style.visibility = 'hidden';
expect(all1.paddingEdge.height, 18);
@@ -130,7 +130,7 @@
});
test('paddingEdge.height with border-box', () {
- var all1 = queryAll('#test');
+ var all1 = querySelectorAll('#test');
div.style.boxSizing = 'border-box';
expect(all1.paddingEdge.height, 10);
div.style.padding = '20pc';
@@ -140,7 +140,7 @@
});
test('paddingEdge.width', () {
- var all1 = queryAll('#test');
+ var all1 = querySelectorAll('#test');
expect(all1.paddingEdge.width, 19);
all1[0].style.visibility = 'hidden';
expect(all1.paddingEdge.width, 19);
@@ -156,7 +156,7 @@
});
test('paddingEdge.width with border-box', () {
- var all1 = queryAll('#test');
+ var all1 = querySelectorAll('#test');
div.style.boxSizing = 'border-box';
expect(all1.paddingEdge.width, 11);
div.style.padding = '20pc';
@@ -166,7 +166,7 @@
});
test('borderEdge.height and marginEdge.height', () {
- var all1 = queryAll('#test');
+ var all1 = querySelectorAll('#test');
expect(div.borderEdge.height, 18);
expect(div.marginEdge.height, 30);
expect(all1.borderEdge.height, 18);
@@ -185,7 +185,7 @@
});
test('borderEdge.height and marginEdge.height with border-box', () {
- var all1 = queryAll('#test');
+ var all1 = querySelectorAll('#test');
div.style.boxSizing = 'border-box';
expect(all1.borderEdge.height, 10);
expect(all1.marginEdge.height, 22);
@@ -198,7 +198,7 @@
});
test('borderEdge.width and marginEdge.width', () {
- var all1 = queryAll('#test');
+ var all1 = querySelectorAll('#test');
expect(all1.borderEdge.width, 19);
expect(all1.marginEdge.width, 31);
@@ -213,7 +213,7 @@
});
test('borderEdge.width and marginEdge.width with border-box', () {
- var all1 = queryAll('#test');
+ var all1 = querySelectorAll('#test');
div.style.boxSizing = 'border-box';
expect(all1.borderEdge.width, 11);
expect(all1.marginEdge.width, 23);
@@ -229,7 +229,7 @@
div.style.border = '1px solid #fff';
div.style.margin = '6px 7px';
div.style.padding = '4px 5px';
- var all1 = queryAll('#test');
+ var all1 = querySelectorAll('#test');
expect(all1.borderEdge.left, all1[0].getBoundingClientRect().left);
expect(all1.borderEdge.top, all1[0].getBoundingClientRect().top);
@@ -249,7 +249,7 @@
div.style.border = '1px solid #fff';
div.style.margin = '6px 7px';
div.style.padding = '4px 5px';
- var all1 = queryAll('div');
+ var all1 = querySelectorAll('div');
all1.contentEdge.height = new Dimension.px(200);
all1.contentEdge.height = 200;
for (Element elem in all1) {
diff --git a/tests/html/element_offset_test.dart b/tests/html/element_offset_test.dart
index ad0a124..567e464 100644
--- a/tests/html/element_offset_test.dart
+++ b/tests/html/element_offset_test.dart
@@ -69,15 +69,15 @@
setUp(initPage);
test('offsetTo', () {
- var itema = query('.item-a');
- var itemb = query('.item-b');
- var item1 = query('.item-1');
- var itemii = query('.item-ii');
- var level1 = query('.level-1');
- var baz = query('.baz');
- var bar = query('.bar');
- var qux = query('.qux');
- var quux = query('.quux');
+ var itema = querySelector('.item-a');
+ var itemb = querySelector('.item-b');
+ var item1 = querySelector('.item-1');
+ var itemii = querySelector('.item-ii');
+ var level1 = querySelector('.level-1');
+ var baz = querySelector('.baz');
+ var bar = querySelector('.bar');
+ var qux = querySelector('.qux');
+ var quux = querySelector('.quux');
var point = itema.offsetTo(itemii);
expect(point.x, 40);
@@ -102,14 +102,14 @@
});
test('documentOffset', () {
- var bar = query('.bar');
- var baz = query('.baz');
- var qux = query('.qux');
- var quux = query('.quux');
- var itema = query('.item-a');
- var itemb = query('.item-b');
- var item1 = query('.item-1');
- var itemii = query('.item-ii');
+ var bar = querySelector('.bar');
+ var baz = querySelector('.baz');
+ var qux = querySelector('.qux');
+ var quux = querySelector('.quux');
+ var itema = querySelector('.item-a');
+ var itemb = querySelector('.item-b');
+ var item1 = querySelector('.item-1');
+ var itemii = querySelector('.item-ii');
expect(itema.documentOffset.x, 88);
expect(itema.documentOffset.y, inInclusiveRange(111, 160));
diff --git a/tests/html/element_test.dart b/tests/html/element_test.dart
index 2fdd9ec..af0ec74 100644
--- a/tests/html/element_test.dart
+++ b/tests/html/element_test.dart
@@ -641,7 +641,7 @@
});
group('queryAll', () {
- List<Element> getQueryAll() {
+ List<Element> getquerySelectorAll() {
return new Element.html("""
<div>
<hr/>
@@ -652,59 +652,61 @@
</p>
<hr class='q'/>
</div>
-""").queryAll('.q');
+""").querySelectorAll('.q');
}
- List<Element> getEmptyQueryAll() => new Element.tag('div').queryAll('img');
+ List<Element> getEmptyquerySelectorAll() =>
+ new Element.tag('div').querySelectorAll('img');
test('last', () {
- expect(getQueryAll().last, isHRElement);
+ expect(getquerySelectorAll().last, isHRElement);
});
test('forEach', () {
var els = [];
- getQueryAll().forEach((el) => els.add(el));
+ getquerySelectorAll().forEach((el) => els.add(el));
expect(els[0], isAnchorElement);
expect(els[1], isSpanElement);
expect(els[2], isHRElement);
});
test('map', () {
- var texts = getQueryAll().map((el) => el.text).toList();
+ var texts = getquerySelectorAll().map((el) => el.text).toList();
expect(texts, equals(['Dart!', 'Hello', '']));
});
test('where', () {
- var filtered = getQueryAll().where((n) => n is SpanElement).toList();
+ var filtered =
+ getquerySelectorAll().where((n) => n is SpanElement).toList();
expect(filtered.length, 1);
expect(filtered[0], isSpanElement);
expect(filtered, isElementList);
});
test('every', () {
- var el = getQueryAll();
+ var el = getquerySelectorAll();
expect(el.every((n) => n is Element), isTrue);
expect(el.every((n) => n is SpanElement), isFalse);
});
test('any', () {
- var el = getQueryAll();
+ var el = getquerySelectorAll();
expect(el.any((n) => n is SpanElement), isTrue);
expect(el.any((n) => n is svg.SvgElement), isFalse);
});
test('isEmpty', () {
- expect(getEmptyQueryAll().isEmpty, isTrue);
- expect(getQueryAll().isEmpty, isFalse);
+ expect(getEmptyquerySelectorAll().isEmpty, isTrue);
+ expect(getquerySelectorAll().isEmpty, isFalse);
});
test('length', () {
- expect(getEmptyQueryAll().length, 0);
- expect(getQueryAll().length, 3);
+ expect(getEmptyquerySelectorAll().length, 0);
+ expect(getquerySelectorAll().length, 3);
});
test('[]', () {
- var els = getQueryAll();
+ var els = getquerySelectorAll();
expect(els[0], isAnchorElement);
expect(els[1], isSpanElement);
expect(els[2], isHRElement);
@@ -712,7 +714,7 @@
test('iterator', () {
var els = [];
- for (var subel in getQueryAll()) {
+ for (var subel in getquerySelectorAll()) {
els.add(subel);
}
expect(els[0], isAnchorElement);
@@ -721,31 +723,34 @@
});
test('sublist', () {
- expect(getQueryAll().sublist(1, 2) is List<Element>, isTrue);
+ expect(getquerySelectorAll().sublist(1, 2) is List<Element>, isTrue);
});
- testUnsupported('[]=', () => getQueryAll()[1] = new Element.tag('br'));
- testUnsupported('add', () => getQueryAll().add(new Element.tag('br')));
+ testUnsupported(
+ '[]=', () => getquerySelectorAll()[1] = new Element.tag('br'));
+ testUnsupported(
+ 'add', () => getquerySelectorAll().add(new Element.tag('br')));
testUnsupported('addAll', () {
- getQueryAll().addAll([
+ getquerySelectorAll().addAll([
new Element.tag('span'),
new Element.tag('a'),
new Element.tag('h1')
]);
});
- testUnsupported('sort', () => getQueryAll().sort((a1, a2) => true));
+ testUnsupported('sort', () => getquerySelectorAll().sort((a1, a2) => true));
testUnsupported('setRange', () {
- getQueryAll().setRange(0, 1, [new BRElement()]);
+ getquerySelectorAll().setRange(0, 1, [new BRElement()]);
});
- testUnsupported('removeRange', () => getQueryAll().removeRange(0, 1));
+ testUnsupported(
+ 'removeRange', () => getquerySelectorAll().removeRange(0, 1));
- testUnsupported('clear', () => getQueryAll().clear());
+ testUnsupported('clear', () => getquerySelectorAll().clear());
- testUnsupported('removeLast', () => getQueryAll().removeLast());
+ testUnsupported('removeLast', () => getquerySelectorAll().removeLast());
});
group('functional', () {
@@ -839,30 +844,30 @@
document.body.append(elem6);
var firedEvent = false;
- var elems = queryAll('.a');
- queryAll('.a').onClick.listen((event) {
+ var elems = querySelectorAll('.a');
+ querySelectorAll('.a').onClick.listen((event) {
firedEvent = true;
});
expect(firedEvent, false);
- query('.c').click();
+ querySelector('.c').click();
expect(firedEvent, false);
- query('#wat').click();
+ querySelector('#wat').click();
expect(firedEvent, true);
var firedEvent4 = false;
- queryAll('.a').onClick.matches('.d').listen((event) {
+ querySelectorAll('.a').onClick.matches('.d').listen((event) {
firedEvent4 = true;
});
expect(firedEvent4, false);
- query('.c').click();
+ querySelector('.c').click();
expect(firedEvent4, false);
- query('#wat').click();
+ querySelector('#wat').click();
expect(firedEvent4, false);
- query('#cookie').click();
+ querySelector('#cookie').click();
expect(firedEvent4, true);
var firedEvent2 = false;
- queryAll('.a').onClick.listen((event) {
+ querySelectorAll('.a').onClick.listen((event) {
firedEvent2 = true;
});
Element elem2 = new Element.html('<div class="a"><br/>');
@@ -874,7 +879,7 @@
expect(firedEvent2, false);
var firedEvent3 = false;
- queryAll(':root').onClick.matches('.a').listen((event) {
+ querySelectorAll(':root').onClick.matches('.a').listen((event) {
firedEvent3 = true;
});
Element elem3 = new Element.html('<div class="d"><br/>');
@@ -886,11 +891,11 @@
expect(firedEvent3, true);
var firedEvent5 = false;
- queryAll(':root').onClick.matches('.e').listen((event) {
+ querySelectorAll(':root').onClick.matches('.e').listen((event) {
firedEvent5 = true;
});
expect(firedEvent5, false);
- query('.i').click();
+ querySelector('.i').click();
expect(firedEvent5, true);
});
@@ -940,7 +945,7 @@
ElementList<Element> makeElementList() =>
(new Element.html("<div>Foo<br/><!--baz--><br/><br/></div>"))
- .queryAll('br');
+ .querySelectorAll('br');
test('hashCode', () {
var nodes = makeElementList();
diff --git a/tests/html/hidden_dom_1_test.dart b/tests/html/hidden_dom_1_test.dart
index 7b7f3dc..e511440 100644
--- a/tests/html/hidden_dom_1_test.dart
+++ b/tests/html/hidden_dom_1_test.dart
@@ -15,7 +15,7 @@
<div id='div1'>
Hello World!
</div>'''));
- Element e = document.query('#div1');
+ Element e = document.querySelector('#div1');
expect(e, isNotNull);
checkNoSuchMethod(() {
diff --git a/tests/html/hidden_dom_2_test.dart b/tests/html/hidden_dom_2_test.dart
index 4257a9a..10bb07c 100644
--- a/tests/html/hidden_dom_2_test.dart
+++ b/tests/html/hidden_dom_2_test.dart
@@ -15,7 +15,7 @@
<div id='div1'>
Hello World!
</div>'''));
- Element e = document.query('#div1');
+ Element e = document.querySelector('#div1');
Element e2 = new Element.html(r"<div id='xx'>XX</div>");
expect(e, isNotNull);
diff --git a/tests/html/htmlcollection_test.dart b/tests/html/htmlcollection_test.dart
index 949d60a..53da995 100644
--- a/tests/html/htmlcollection_test.dart
+++ b/tests/html/htmlcollection_test.dart
@@ -38,7 +38,7 @@
test('IsList', () {
Element root = insertTestDiv();
- List<Element> eachChecked = document.query('#allChecked').children;
+ List<Element> eachChecked = document.querySelector('#allChecked').children;
expect(eachChecked, isList);
@@ -47,11 +47,11 @@
test('Every', () {
Element root = insertTestDiv();
- List<Element> eachChecked = document.query('#allChecked').children;
+ List<Element> eachChecked = document.querySelector('#allChecked').children;
- List<Element> someChecked = document.query('#someChecked').children;
+ List<Element> someChecked = document.querySelector('#someChecked').children;
- List<Element> noneChecked = document.query('#noneChecked').children;
+ List<Element> noneChecked = document.querySelector('#noneChecked').children;
expect(eachChecked.length, 4);
expect(someChecked.length, 4);
@@ -69,11 +69,11 @@
test('Some', () {
Element root = insertTestDiv();
- List<Element> eachChecked = document.query('#allChecked').children;
+ List<Element> eachChecked = document.querySelector('#allChecked').children;
- List<Element> someChecked = document.query('#someChecked').children;
+ List<Element> someChecked = document.querySelector('#someChecked').children;
- List<Element> noneChecked = document.query('#noneChecked').children;
+ List<Element> noneChecked = document.querySelector('#noneChecked').children;
expect(eachChecked.length, 4);
expect(someChecked.length, 4);
@@ -91,11 +91,11 @@
test('Filter', () {
Element root = insertTestDiv();
- List<Element> eachChecked = document.query('#allChecked').children;
+ List<Element> eachChecked = document.querySelector('#allChecked').children;
- List<Element> someChecked = document.query('#someChecked').children;
+ List<Element> someChecked = document.querySelector('#someChecked').children;
- List<Element> noneChecked = document.query('#noneChecked').children;
+ List<Element> noneChecked = document.querySelector('#noneChecked').children;
expect(eachChecked.length, 4);
expect(someChecked.length, 4);
@@ -113,9 +113,9 @@
test('IsEmpty', () {
Element root = insertTestDiv();
- List<Element> someChecked = document.query('#someChecked').children;
+ List<Element> someChecked = document.querySelector('#someChecked').children;
- List<Element> emptyDiv = document.query('#emptyDiv').children;
+ List<Element> emptyDiv = document.querySelector('#emptyDiv').children;
expect(someChecked.length, 4);
expect(emptyDiv.length, 0);
@@ -137,11 +137,11 @@
test('ForEach', () {
Element root = insertTestDiv();
- List<Element> eachChecked = document.query('#allChecked').children;
+ List<Element> eachChecked = document.querySelector('#allChecked').children;
- List<Element> someChecked = document.query('#someChecked').children;
+ List<Element> someChecked = document.querySelector('#someChecked').children;
- List<Element> noneChecked = document.query('#noneChecked').children;
+ List<Element> noneChecked = document.querySelector('#noneChecked').children;
expect(eachChecked.length, 4);
expect(someChecked.length, 4);
@@ -169,11 +169,11 @@
// Uses iterator.
Element root = insertTestDiv();
- List<Element> eachChecked = document.query('#allChecked').children;
+ List<Element> eachChecked = document.querySelector('#allChecked').children;
- List<Element> someChecked = document.query('#someChecked').children;
+ List<Element> someChecked = document.querySelector('#someChecked').children;
- List<Element> noneChecked = document.query('#noneChecked').children;
+ List<Element> noneChecked = document.querySelector('#noneChecked').children;
expect(eachChecked.length, 4);
expect(someChecked.length, 4);
@@ -191,7 +191,7 @@
test('Last', () {
Element root = insertTestDiv();
- List<Element> someChecked = document.query('#someChecked').children;
+ List<Element> someChecked = document.querySelector('#someChecked').children;
expect(someChecked.length, 4);
@@ -202,9 +202,9 @@
test('IndexOf', () {
Element root = insertTestDiv();
- List<Element> someChecked = document.query('#someChecked').children;
+ List<Element> someChecked = document.querySelector('#someChecked').children;
- List<Element> noneChecked = document.query('#noneChecked').children;
+ List<Element> noneChecked = document.querySelector('#noneChecked').children;
expect(someChecked.length, 4);
expect(noneChecked.length, 4);
@@ -229,9 +229,9 @@
test('LastIndexOf', () {
Element root = insertTestDiv();
- List<Element> someChecked = document.query('#someChecked').children;
+ List<Element> someChecked = document.querySelector('#someChecked').children;
- List<Element> noneChecked = document.query('#noneChecked').children;
+ List<Element> noneChecked = document.querySelector('#noneChecked').children;
expect(someChecked.length, 4);
expect(noneChecked.length, 4);
diff --git a/tests/html/htmlelement_test.dart b/tests/html/htmlelement_test.dart
index 7335857..4942482 100644
--- a/tests/html/htmlelement_test.dart
+++ b/tests/html/htmlelement_test.dart
@@ -13,7 +13,7 @@
element.innerHtml = 'Hello World';
document.body.append(element);
- element = document.query('#test');
+ element = document.querySelector('#test');
expect(element.innerHtml, 'Hello World');
element.remove();
});
diff --git a/tests/html/query_test.dart b/tests/html/query_test.dart
index 85a4262..26bacbe 100644
--- a/tests/html/query_test.dart
+++ b/tests/html/query_test.dart
@@ -23,7 +23,7 @@
predicate((x) => x is ImageElement, 'is an ImageElement');
test('query', () {
- Element e = query('#testcanvas');
+ Element e = querySelector('#testcanvas');
expect(e, isNotNull);
expect(e.id, 'testcanvas');
expect(e, isCanvasElement);
@@ -31,18 +31,18 @@
});
test('query (None)', () {
- Element e = query('#nothere');
+ Element e = querySelector('#nothere');
expect(e, isNull);
});
test('queryAll (One)', () {
- List l = queryAll('canvas');
+ List l = querySelectorAll('canvas');
expect(l.length, 1);
expect(l[0], canvas);
});
test('queryAll (Multiple)', () {
- List l = queryAll('img');
+ List l = querySelectorAll('img');
expect(l.length, 2);
expect(l[0], isImageElement);
expect(l[1], isImageElement);
@@ -50,7 +50,7 @@
});
test('queryAll (None)', () {
- List l = queryAll('video');
+ List l = querySelectorAll('video');
expect(l.isEmpty, isTrue);
});
}
diff --git a/tests/html/queryall_test.dart b/tests/html/queryall_test.dart
index cf87873..5749a04 100644
--- a/tests/html/queryall_test.dart
+++ b/tests/html/queryall_test.dart
@@ -31,15 +31,15 @@
]);
test('queryAll', () {
- List<Node> all = queryAll('*');
+ List<Node> all = querySelectorAll('*');
for (var e in all) {
expect(e, isElement);
}
});
test('document.queryAll', () {
- List<Element> all1 = queryAll('*');
- List<Element> all2 = document.queryAll('*');
+ List<Element> all1 = querySelectorAll('*');
+ List<Element> all2 = document.querySelectorAll('*');
expect(all1.length, equals(all2.length));
for (var i = 0; i < all1.length; ++i) {
expect(all1[i], equals(all2[i]));
@@ -47,7 +47,7 @@
});
test('queryAll-canvas', () {
- List<CanvasElement> all = queryAll('canvas');
+ List<CanvasElement> all = querySelectorAll('canvas');
for (var e in all) {
expect(e, isCanvasElement);
}
@@ -55,14 +55,14 @@
});
test('queryAll-contains', () {
- List<Element> all = queryAll('*');
+ List<Element> all = querySelectorAll('*');
for (var e in all) {
expect(all.contains(e), isTrue);
}
});
test('queryAll-where', () {
- List<Element> all = queryAll('*');
+ List<Element> all = querySelectorAll('*');
Iterable<CanvasElement> canvases = all.where((e) => e is CanvasElement);
for (var e in canvases) {
expect(e is CanvasElement, isTrue);
@@ -71,7 +71,7 @@
});
test('node.queryAll', () {
- List<Element> list = div.queryAll('*');
+ List<Element> list = div.querySelectorAll('*');
expect(list.length, equals(5));
expect(list[0], isDivElement);
expect(list[1], isCanvasElement);
@@ -81,7 +81,7 @@
});
test('immutable', () {
- List<Element> list = div.queryAll('*');
+ List<Element> list = div.querySelectorAll('*');
int len = list.length;
expect(() {
list.add(new DivElement());
diff --git a/tests/html/shadow_dom_test.dart b/tests/html/shadow_dom_test.dart
index c3baee5..9efa5c6 100644
--- a/tests/html/shadow_dom_test.dart
+++ b/tests/html/shadow_dom_test.dart
@@ -43,7 +43,7 @@
expect(() {
init();
- expect(queryAll('.foo'), equals([div1, paragraph2]));
+ expect(querySelectorAll('.foo'), equals([div1, paragraph2]));
}, expectation);
});
@@ -64,7 +64,7 @@
expect(() {
init();
- expect(shadowRoot.queryAll('.foo'), equals([paragraph1]));
+ expect(shadowRoot.querySelectorAll('.foo'), equals([paragraph1]));
}, expectation);
});
diff --git a/tests/html/svg_test.dart b/tests/html/svg_test.dart
index 67b0e20..a837e39 100644
--- a/tests/html/svg_test.dart
+++ b/tests/html/svg_test.dart
@@ -26,10 +26,10 @@
''',
validator: new NodeValidatorBuilder()..allowSvg());
- var e = document.query('#svg1');
+ var e = document.querySelector('#svg1');
expect(e, isNotNull);
- svg.RectElement r = document.query('#rect1');
+ svg.RectElement r = document.querySelector('#rect1');
expect(r.x.baseVal.value, 10);
expect(r.y.baseVal.value, 20);
expect(r.height.baseVal.value, 40);
@@ -75,7 +75,7 @@
test('rect_isChecks', () {
var div = insertTestDiv();
- var r = document.query('#rect1');
+ var r = document.querySelector('#rect1');
// Direct inheritance chain
expect(r, isSvgElement);
@@ -124,7 +124,7 @@
testRect(name, checker) {
test(name, () {
var div = insertTestDiv();
- var r = document.query('#rect1');
+ var r = document.querySelector('#rect1');
checker(r);
div.remove();
});
diff --git a/tests/html/track_element_constructor_test.dart b/tests/html/track_element_constructor_test.dart
index 883dabd..088eb27 100644
--- a/tests/html/track_element_constructor_test.dart
+++ b/tests/html/track_element_constructor_test.dart
@@ -19,11 +19,11 @@
test('', () {
if (!TrackElement.supported) return;
document.body.append(new TrackElement()..defaultValue = true);
- if (!document.query('track').defaultValue) {
+ if (!document.querySelector('track').defaultValue) {
throw 'Expected default value to be true';
}
- document.query('track').defaultValue = false;
- if (document.query('track').defaultValue) {
+ document.querySelector('track').defaultValue = false;
+ if (document.querySelector('track').defaultValue) {
throw 'Expected default value to be false';
}
});
diff --git a/tests/html/typing_test.dart b/tests/html/typing_test.dart
index 570723e..084de8c 100644
--- a/tests/html/typing_test.dart
+++ b/tests/html/typing_test.dart
@@ -11,15 +11,15 @@
predicate((x) => x is List<StyleSheet>, 'is a List<StyleSheet>');
test('NodeList', () {
- List<Node> asList = window.document.queryAll('body');
+ List<Node> asList = window.document.querySelectorAll('body');
// Check it's Iterable
int counter = 0;
- for (Node node in window.document.queryAll('body')) {
+ for (Node node in window.document.querySelectorAll('body')) {
counter++;
}
expect(counter, 1);
counter = 0;
- window.document.queryAll('body').forEach((e) {
+ window.document.querySelectorAll('body').forEach((e) {
counter++;
});
expect(counter, 1);
diff --git a/tests/html/unknownelement_test.dart b/tests/html/unknownelement_test.dart
index 0957766..0c97858 100644
--- a/tests/html/unknownelement_test.dart
+++ b/tests/html/unknownelement_test.dart
@@ -23,8 +23,8 @@
test('type-check', () {
expect(foo, isUnknownElement);
expect(bar, isUnknownElement);
- expect(query('#foo'), equals(foo));
- expect(query('#bar'), equals(bar));
+ expect(querySelector('#foo'), equals(foo));
+ expect(querySelector('#bar'), equals(bar));
});
test('dispatch-fail', () {
diff --git a/tests/language/language_dart2js.status b/tests/language/language_dart2js.status
index 9cc7e0e..e848251 100644
--- a/tests/language/language_dart2js.status
+++ b/tests/language/language_dart2js.status
@@ -70,10 +70,6 @@
config_import_test: RuntimeError # Test flag is not passed to the compiler.
library_env_test/has_io_support: RuntimeError, OK # dart2js doesn't support io when using '--categories=Client'.
-[ $compiler == dart2js && $browser && $csp && !$fast_startup ]
-conditional_import_string_test: Fail # Issue 30615
-conditional_import_test: Fail # Issue 30615
-
[ $compiler == dart2js && !$browser ]
library_env_test/has_no_io_support: RuntimeError, OK # dart2js supports io when using '--categories=all'.
diff --git a/tests/language_2/language_2_dart2js.status b/tests/language_2/language_2_dart2js.status
index acf2b12..a8eb7cf 100644
--- a/tests/language_2/language_2_dart2js.status
+++ b/tests/language_2/language_2_dart2js.status
@@ -68,35 +68,12 @@
[ $compiler == dart2js && $runtime != none && $checked ]
assert_with_message_test: RuntimeError
-function_subtype_bound_closure1_test: RuntimeError
-function_subtype_bound_closure2_test: RuntimeError
function_subtype_bound_closure3_test: RuntimeError
function_subtype_bound_closure4_test: RuntimeError
-function_subtype_bound_closure5_test: RuntimeError
-function_subtype_bound_closure5a_test: RuntimeError
-function_subtype_bound_closure6_test: RuntimeError
-function_subtype_bound_closure7_test: RuntimeError
function_subtype_call1_test: RuntimeError
function_subtype_call2_test: RuntimeError
-function_subtype_cast0_test: RuntimeError
function_subtype_cast1_test: RuntimeError
-function_subtype_cast2_test: RuntimeError
-function_subtype_cast3_test: RuntimeError
-function_subtype_checked0_test: RuntimeError
-function_subtype_local1_test: RuntimeError
-function_subtype_local2_test: RuntimeError
-function_subtype_local5_test: RuntimeError
-function_subtype_named1_test: RuntimeError
-function_subtype_named2_test: RuntimeError
-function_subtype_not0_test: RuntimeError
function_subtype_not1_test: RuntimeError
-function_subtype_not2_test: RuntimeError
-function_subtype_not3_test: RuntimeError
-function_subtype_optional1_test: RuntimeError
-function_subtype_optional2_test: RuntimeError
-function_subtype_top_level1_test: RuntimeError
-function_subtype_typearg2_test: RuntimeError
-function_subtype_typearg3_test: RuntimeError
function_subtype_typearg5_test: RuntimeError
function_type/function_type0_test: RuntimeError # Issue 30476
function_type/function_type10_test: RuntimeError # Issue 30476
@@ -125,7 +102,10 @@
function_type/function_type33_test: RuntimeError # Issue 30476
function_type/function_type34_test: RuntimeError # Issue 30476
function_type/function_type36_test: RuntimeError # Issue 30476
+function_type/function_type38_test: RuntimeError # Issue 30476
function_type/function_type3_test: RuntimeError # Issue 30476
+function_type/function_type40_test: RuntimeError # Issue 30476
+function_type/function_type42_test: RuntimeError # Issue 30476
function_type/function_type44_test: RuntimeError # Issue 30476
function_type/function_type45_test: RuntimeError # Issue 30476
function_type/function_type46_test: RuntimeError # Issue 30476
@@ -167,7 +147,6 @@
function_type/function_type96_test: RuntimeError # Issue 30476
function_type/function_type9_test: RuntimeError # Issue 30476
function_type_alias2_test: RuntimeError
-function_type_alias3_test: RuntimeError
function_type_alias4_test: RuntimeError
[ $compiler == dart2js && $runtime == safari ]
@@ -196,10 +175,13 @@
typedef_is_test: Crash
[ $compiler == dart2js && $checked && $fasta && $strong ]
-assertion_initializer_const_function_test/01: MissingCompileTimeError
-assertion_test: RuntimeError
+assign_instance_method_test: RuntimeError
+async_await_foreign_test: RuntimeError
async_star_cancel_while_paused_test: RuntimeError
+async_star_pause_test: RuntimeError
+async_star_regression_23116_test: RuntimeError
async_star_test/02: RuntimeError
+await_test: RuntimeError
bad_override_test/03: MissingCompileTimeError
bad_override_test/04: MissingCompileTimeError
bad_override_test/05: MissingCompileTimeError
@@ -207,8 +189,6 @@
bit_operations_test/04: RuntimeError
bit_operations_test/none: RuntimeError
branch_canonicalization_test: RuntimeError
-built_in_identifier_test: RuntimeError # Issue 28815
-call_function_apply_test: RuntimeError # Issue 23873
canonical_const2_test: RuntimeError, OK # non JS number semantics
check_member_static_test/02: MissingCompileTimeError
checked_method_error_order_test: RuntimeError
@@ -358,7 +338,6 @@
full_stacktrace1_test: RuntimeError # Issue 12698
full_stacktrace2_test: RuntimeError # Issue 12698
full_stacktrace3_test: RuntimeError # Issue 12698
-function_type_alias_test: RuntimeError
generalized_void_syntax_test: CompileTimeError # Issue #30176.
generic_closure_test/01: RuntimeError
generic_closure_test/none: RuntimeError
@@ -583,15 +562,16 @@
covariance_setter_test/05: RuntimeError
covariance_setter_test/06: RuntimeError
recursive_mixin_test: RuntimeError # no check without --checked
-type_argument_in_super_type_test: RuntimeError
[ $compiler == dart2js && !$checked && !$enable_asserts ]
assertion_test: RuntimeError, OK
[ $compiler == dart2js && !$checked && $fasta ]
+bool_check_test: RuntimeError
+bool_condition_check_test: RuntimeError
+bug31436_test: RuntimeError
cascaded_forwarding_stubs_generic_test: RuntimeError
cascaded_forwarding_stubs_test: RuntimeError
-checked_setter3_test: RuntimeError # Issue 31128
constructor_call_as_function_test: CompileTimeError # Issue 32517
forwarding_semi_stub_test: RuntimeError
forwarding_stub_tearoff_generic_test: RuntimeError
@@ -606,33 +586,6 @@
implicit_creation/implicit_new_or_const_composite_test: CompileTimeError # Issue 32517
implicit_creation/implicit_new_or_const_test: CompileTimeError # Issue 32517
implicit_creation/implicit_new_prefix_constructor_named_test: CompileTimeError # Issue 32517
-implicit_downcast_during_assignment_test: RuntimeError
-implicit_downcast_during_combiner_test: RuntimeError
-implicit_downcast_during_compound_assignment_test: RuntimeError
-implicit_downcast_during_conditional_expression_test: RuntimeError
-implicit_downcast_during_constructor_initializer_test: RuntimeError
-implicit_downcast_during_do_test: RuntimeError
-implicit_downcast_during_factory_constructor_invocation_test: RuntimeError
-implicit_downcast_during_field_declaration_test: RuntimeError
-implicit_downcast_during_for_condition_test: RuntimeError
-implicit_downcast_during_for_initializer_expression_test: RuntimeError
-implicit_downcast_during_for_initializer_var_test: RuntimeError
-implicit_downcast_during_if_null_assignment_test: RuntimeError
-implicit_downcast_during_if_statement_test: RuntimeError
-implicit_downcast_during_indexed_assignment_test: RuntimeError
-implicit_downcast_during_indexed_compound_assignment_test: RuntimeError
-implicit_downcast_during_indexed_get_test: RuntimeError
-implicit_downcast_during_indexed_if_null_assignment_test: RuntimeError
-implicit_downcast_during_logical_expression_test: RuntimeError
-implicit_downcast_during_map_literal_test: RuntimeError
-implicit_downcast_during_method_invocation_test: RuntimeError
-implicit_downcast_during_not_test: RuntimeError
-implicit_downcast_during_null_aware_method_invocation_test: RuntimeError
-implicit_downcast_during_return_test: RuntimeError
-implicit_downcast_during_static_method_invocation_test: RuntimeError
-implicit_downcast_during_super_method_invocation_test: RuntimeError
-implicit_downcast_during_variable_declaration_test: RuntimeError
-implicit_downcast_during_while_statement_test: RuntimeError
issue31596_implement_covariant_test: RuntimeError
issue31596_super_test/02: MissingCompileTimeError
issue31596_super_test/04: MissingCompileTimeError
@@ -680,8 +633,6 @@
bad_override_test/04: MissingCompileTimeError
bad_override_test/05: MissingCompileTimeError
bit_operations_test: RuntimeError
-bool_check_test: RuntimeError
-bool_condition_check_test: RuntimeError
branch_canonicalization_test: RuntimeError
call_function_apply_test: RuntimeError # Issue 23873
canonical_const2_test: RuntimeError, OK # non JS number semantics
@@ -862,8 +813,6 @@
function_type2_test: RuntimeError
function_type_alias2_test: RuntimeError
function_type_alias_test: RuntimeError
-function_type_call_getter2_test/none: RuntimeError
-function_type_test: RuntimeError
generalized_void_syntax_test: CompileTimeError # Issue #30176.
generic_closure_test/01: RuntimeError
generic_closure_test/none: RuntimeError
@@ -1079,8 +1028,6 @@
typevariable_substitution2_test/02: RuntimeError
[ $compiler == dart2js && $fasta ]
-async_error_timing_test: Crash
-bug31436_test: RuntimeError
call_method_function_typed_value_test/02: RuntimeError
call_method_function_typed_value_test/04: RuntimeError
call_method_function_typed_value_test/06: RuntimeError
@@ -1088,27 +1035,13 @@
call_method_must_not_be_field_test/03: RuntimeError # Issue 32155
call_method_must_not_be_getter_test/03: RuntimeError # Issue 32155
call_with_no_such_method_test: RuntimeError
-callable_test/none: RuntimeError
checked_setter2_test: RuntimeError # Issue 31128
checked_setter_test: RuntimeError # Issue 31128
const_dynamic_type_literal_test/03: Pass # but it shouldn't until we fix issue 17207
extract_type_arguments_test: Crash # Issue 31371
function_propagation_test: RuntimeError
-function_type_call_getter2_test/none: RuntimeError
generic_test/01: MissingCompileTimeError # front end does not validate `extends`
-implicit_downcast_during_constructor_invocation_test: RuntimeError
-implicit_downcast_during_for_in_element_test: RuntimeError
-implicit_downcast_during_for_in_iterable_test: RuntimeError
-implicit_downcast_during_function_literal_arrow_test: RuntimeError
-implicit_downcast_during_function_literal_return_test: RuntimeError
-implicit_downcast_during_invocation_test: RuntimeError
-implicit_downcast_during_list_literal_test: RuntimeError
-implicit_downcast_during_redirecting_initializer_test: RuntimeError
-implicit_downcast_during_return_async_test: RuntimeError
-implicit_downcast_during_super_initializer_test: RuntimeError
implicit_downcast_during_yield_star_test: RuntimeError
-implicit_downcast_during_yield_test: RuntimeError
-instantiate_tearoff_after_contravariance_check_test: RuntimeError
instantiate_tearoff_of_call_test: RuntimeError
instantiate_tearoff_test: RuntimeError
mixin_type_parameter_inference_error_test/none: CompileTimeError
@@ -1133,7 +1066,6 @@
partial_tearoff_instantiation_test/07: Pass # for the wrong reason.
partial_tearoff_instantiation_test/08: Pass # for the wrong reason.
partial_tearoff_instantiation_test/none: CompileTimeError
-syntax_test/62: Crash
[ $compiler == dart2js && $fasta && $host_checked && $strong ]
abstract_factory_constructor_test/00: MissingCompileTimeError
@@ -1143,16 +1075,9 @@
abstract_syntax_test/00: MissingCompileTimeError
additional_interface_adds_optional_args_concrete_subclass_test: MissingCompileTimeError
additional_interface_adds_optional_args_concrete_test: MissingCompileTimeError
-argument_assignability_function_typed_test/03: RuntimeError
-argument_assignability_function_typed_test/04: RuntimeError
-argument_assignability_function_typed_test/05: RuntimeError
assertion_initializer_const_error2_test/none: CompileTimeError
assertion_initializer_test: CompileTimeError
assertion_test: RuntimeError
-async_await_syntax_test/a06a: RuntimeError
-async_await_syntax_test/b06a: RuntimeError
-async_await_syntax_test/c06a: RuntimeError
-async_await_syntax_test/d06a: RuntimeError
async_await_test/02: RuntimeError
async_await_test/03: RuntimeError
async_await_test/none: RuntimeError
@@ -1160,25 +1085,16 @@
async_congruence_method_test/none: RuntimeError
async_congruence_top_level_test: RuntimeError
async_congruence_unnamed_test/none: RuntimeError
-async_error_timing_test: RuntimeError
async_or_generator_return_type_stacktrace_test/01: MissingCompileTimeError
async_or_generator_return_type_stacktrace_test/02: MissingCompileTimeError
async_or_generator_return_type_stacktrace_test/03: MissingCompileTimeError
async_return_types_test/nestedFuture: Crash # 'file:*/pkg/compiler/lib/src/js_emitter/runtime_type_generator.dart': Failed assertion: line 208 pos 18: '!(_useKernel && _strongMode && !_disableRtiOptimization) ||
-async_return_types_test/none: RuntimeError
async_return_types_test/tooManyTypeParameters: Crash # 'file:*/pkg/compiler/lib/src/js_emitter/runtime_type_generator.dart': Failed assertion: line 208 pos 18: '!(_useKernel && _strongMode && !_disableRtiOptimization) ||
async_return_types_test/wrongReturnType: Crash # 'file:*/pkg/compiler/lib/src/js_emitter/runtime_type_generator.dart': Failed assertion: line 208 pos 18: '!(_useKernel && _strongMode && !_disableRtiOptimization) ||
async_star_await_pauses_test: RuntimeError
-async_star_cancel_and_throw_in_finally_test: RuntimeError
async_star_cancel_while_paused_test: Crash # 'file:*/pkg/compiler/lib/src/js_emitter/runtime_type_generator.dart': Failed assertion: line 208 pos 18: '!(_useKernel && _strongMode && !_disableRtiOptimization) ||
-async_star_no_cancel2_test: RuntimeError
-async_star_no_cancel_test: RuntimeError
-async_star_pause_test: RuntimeError
async_star_regression_2238_test: RuntimeError
-async_star_regression_23116_test: RuntimeError
-async_star_regression_fisk_test: RuntimeError
async_star_stream_take_test: RuntimeError
-async_star_take_reyield_test: RuntimeError
async_star_test/01: RuntimeError
async_star_test/02: RuntimeError
async_star_test/03: RuntimeError
@@ -1186,23 +1102,13 @@
async_star_test/05: RuntimeError
async_star_test/none: RuntimeError
async_test: RuntimeError
-asyncstar_concat_test: RuntimeError
-asyncstar_yield_test: RuntimeError
-asyncstar_yieldstar_test: RuntimeError
-await_for_cancel_test: RuntimeError
-await_for_test: RuntimeError
-await_for_use_local_test: RuntimeError
await_not_started_immediately_test: Crash # Assertion failure: Runtime type information not available for type_variable_local(bindCallback.R) in (local(_RootZone.bindCallback#)) for j:closure_call(_RootZone_bindCallback_closure.call).
-await_test: RuntimeError
bad_override_test/01: MissingCompileTimeError
bad_override_test/02: MissingCompileTimeError
bad_override_test/03: MissingCompileTimeError
bad_override_test/04: MissingCompileTimeError
bad_override_test/05: MissingCompileTimeError
bit_operations_test: RuntimeError
-bool_check_test: RuntimeError
-bool_condition_check_test: RuntimeError
-bool_test: RuntimeError
branch_canonicalization_test: RuntimeError
branches_test: Crash # 'package:front_end/src/fasta/kernel/kernel_shadow_ast.dart': Failed assertion: line 441 pos 16: 'identical(combiner.arguments.positional[0], rhs)': is not true.
call_non_method_field_test/01: MissingCompileTimeError
@@ -1221,7 +1127,6 @@
closure_invoked_through_interface_target_field_test: MissingCompileTimeError
closure_invoked_through_interface_target_getter_test: MissingCompileTimeError
closure_self_reference_test: Crash # 'file:*/pkg/compiler/lib/src/ssa/nodes.dart': Failed assertion: line 641 pos 12: 'isClosed()': is not true.
-closure_type_test: RuntimeError
compile_time_constant_d_test: CompileTimeError
compile_time_constant_e_test: CompileTimeError
compile_time_constant_k_test/01: MissingCompileTimeError
@@ -1357,44 +1262,23 @@
full_stacktrace1_test: RuntimeError # Issue 12698
full_stacktrace2_test: RuntimeError # Issue 12698
full_stacktrace3_test: RuntimeError # Issue 12698
-function_subtype2_test: RuntimeError
function_subtype3_test: RuntimeError
-function_subtype_bound_closure2_test: RuntimeError
function_subtype_bound_closure3_test: RuntimeError
function_subtype_bound_closure4_test: RuntimeError
-function_subtype_bound_closure5_test: RuntimeError
-function_subtype_bound_closure5a_test: RuntimeError
-function_subtype_bound_closure6_test: RuntimeError
function_subtype_bound_closure7_test: RuntimeError
function_subtype_call0_test: RuntimeError
function_subtype_call1_test: RuntimeError
function_subtype_call2_test: RuntimeError
function_subtype_cast1_test: RuntimeError
-function_subtype_checked0_test: RuntimeError
-function_subtype_closure0_test: RuntimeError
-function_subtype_closure1_test: RuntimeError
-function_subtype_factory1_test: RuntimeError
-function_subtype_inline1_test: RuntimeError
function_subtype_inline2_test: RuntimeError
-function_subtype_local2_test: RuntimeError
-function_subtype_local5_test: RuntimeError
function_subtype_not1_test: RuntimeError
-function_subtype_optional1_test: RuntimeError
-function_subtype_optional2_test: RuntimeError
-function_subtype_regression_ddc_588_test: RuntimeError
function_subtype_setter0_test: RuntimeError
-function_subtype_simple2_test: RuntimeError
function_subtype_typearg5_test: RuntimeError
function_type2_test: RuntimeError
function_type_alias2_test: RuntimeError
function_type_alias4_test: RuntimeError
-function_type_alias_test: RuntimeError
-function_type_call_getter2_test/none: RuntimeError
-function_type_test: RuntimeError
-generic_async_star_test: RuntimeError
generic_closure_test/01: RuntimeError
generic_closure_test/none: RuntimeError
-generic_field_mixin6_test/none: RuntimeError
generic_function_bounds_test: RuntimeError
generic_function_dcall_test: RuntimeError
generic_function_type_as_type_argument_test/01: MissingCompileTimeError
@@ -1425,8 +1309,6 @@
getter_override_test/01: MissingCompileTimeError
getter_override_test/02: MissingCompileTimeError
getter_override_test/03: MissingCompileTimeError
-getters_setters2_test/01: RuntimeError
-getters_setters2_test/none: RuntimeError
identical_closure2_test: RuntimeError # non JS number semantics
identical_const_test/01: MissingCompileTimeError
identical_const_test/02: MissingCompileTimeError
@@ -1435,7 +1317,6 @@
if_null_precedence_test/none: RuntimeError
implicit_creation/implicit_new_or_const_composite_test: RuntimeError
implicit_creation/implicit_new_or_const_test: RuntimeError
-implicit_downcast_during_return_async_test: Crash # Assertion failure: Runtime type information not available for type_variable_local(bindCallback.R) in (local(_RootZone.bindCallback#)) for j:closure_call(_RootZone_bindCallback_closure.call).
implicit_this_test/01: MissingCompileTimeError
implicit_this_test/04: MissingCompileTimeError
inferrer_synthesized_constructor_test: RuntimeError
@@ -1443,7 +1324,6 @@
initializing_formal_type_annotation_test/01: MissingCompileTimeError
initializing_formal_type_annotation_test/02: MissingCompileTimeError
instance_creation_in_function_annotation_test: RuntimeError
-instantiate_tearoff_after_contravariance_check_test: Crash # Assertion failure: kind=special,memberName=instantiate,callStructure:CallStructure(arity=0, types=1)
instantiate_tearoff_of_call_test: CompileTimeError
instantiate_tearoff_test: Crash # Assertion failure: kind=special,memberName=instantiate,callStructure:CallStructure(arity=0, types=1)
int64_literal_test/01: RuntimeError
@@ -1468,7 +1348,6 @@
issue31596_override_test/08: MissingCompileTimeError
issue31596_super_test/01: CompileTimeError
issue31596_super_test/03: CompileTimeError
-known_identifier_usage_error_test/none: RuntimeError
left_shift_test: RuntimeError # non JS number semantics
library_env_test/has_mirror_support: RuntimeError
library_env_test/has_no_html_support: RuntimeError
@@ -1478,9 +1357,6 @@
local_function3_test/none: RuntimeError
local_function_test/none: RuntimeError
main_test/03: RuntimeError
-main_test/20: RuntimeError
-main_test/22: RuntimeError
-main_test/44: RuntimeError
malbounded_instantiation_test/01: MissingCompileTimeError
malbounded_instantiation_test/02: MissingCompileTimeError
malbounded_instantiation_test/03: MissingCompileTimeError
@@ -1634,7 +1510,6 @@
number_identity2_test: RuntimeError
numbers_test: RuntimeError, OK # non JS number semantics
operator2_negative_test: Crash # 'file:*/pkg/compiler/lib/src/kernel/env.dart': Failed assertion: line 322 pos 16: '!name.contains('#')': is not true.
-operator4_test: RuntimeError
operator_test: Crash # 'package:front_end/src/fasta/kernel/kernel_shadow_ast.dart': Failed assertion: line 441 pos 16: 'identical(combiner.arguments.positional[0], rhs)': is not true.
overridden_no_such_method_test: RuntimeError
override_field_method1_negative_test: Fail
@@ -1712,9 +1587,7 @@
regress_22443_test: RuntimeError
regress_23089_test: Crash # Stack Overflow
regress_23408_test: CompileTimeError
-regress_23996_test: RuntimeError
regress_24283_test: RuntimeError # non JS number semantics
-regress_24935_test/none: RuntimeError
regress_27617_test/1: Crash # Assertion failure: Unexpected constructor j:constructor(Foo._) in ConstructorDataImpl._getConstructorConstant
regress_28255_test: RuntimeError
regress_28278_test: RuntimeError
@@ -1723,7 +1596,6 @@
regress_29784_test/01: Crash # Assertion failure: Cannot find value Instance of 'ThisLocal' in () for j:constructor(A.ok).
regress_29784_test/02: MissingCompileTimeError # Issue 29784
regress_30339_test: CompileTimeError
-regress_31591_test: RuntimeError
runtime_type_function_test: RuntimeError
setter4_test: MissingCompileTimeError
setter_no_getter_test/01: CompileTimeError
@@ -1731,7 +1603,6 @@
setter_override_test/01: MissingCompileTimeError
setter_override_test/02: MissingCompileTimeError
setter_override_test/03: MissingCompileTimeError
-shadow_parameter_and_local_test: RuntimeError
stacktrace_demangle_ctors_test: RuntimeError # Issue 12698
stacktrace_rethrow_error_test/none: RuntimeError # Issue 12698
stacktrace_rethrow_error_test/withtraceparameter: RuntimeError # Issue 12698
@@ -1818,8 +1689,6 @@
type_variable_bounds_test/08: MissingCompileTimeError
type_variable_bounds_test/11: MissingCompileTimeError
type_variable_promotion_test: RuntimeError
-typedef_is_test: RuntimeError
-typevariable_substitution2_test/02: RuntimeError
vm/async_await_catch_stacktrace_test: Crash # Assertion failure: Runtime type information not available for type_variable_local(bindCallback.R) in (local(_RootZone.bindCallback#)) for j:closure_call(_RootZone_bindCallback_closure.call).
vm/await_synchronous_future_test: Crash # Interpolated value #1 is not an Expression or List of Expressions: [VariableUse(f), Instance of 'LiteralNull', null]
vm/causal_async_exception_stack2_test: Crash # Assertion failure: Unexpected arguments. Expected 1 argument, actual: [invoke dynamic method: selector=Selector(operator, *, arity=1), mask=[subclass=JSUInt32], HTypeInfoReadVariable(ListQueue.E)].
@@ -1892,7 +1761,6 @@
void_type_usage_test/paren_null_equals2: Crash # 'package:front_end/src/fasta/type_inference/type_schema_environment.dart': Failed assertion: line 214 pos 12: 'false': is not true.
wrong_number_type_arguments_test/01: MissingCompileTimeError
wrong_number_type_arguments_test/none: Pass
-yieldstar_pause_test: RuntimeError
[ $compiler == dart2js && $fasta && $minified && $strong ]
abstract_factory_constructor_test/00: MissingCompileTimeError
@@ -1902,16 +1770,9 @@
abstract_syntax_test/00: MissingCompileTimeError
additional_interface_adds_optional_args_concrete_subclass_test: MissingCompileTimeError
additional_interface_adds_optional_args_concrete_test: MissingCompileTimeError
-argument_assignability_function_typed_test/03: RuntimeError
-argument_assignability_function_typed_test/04: RuntimeError
-argument_assignability_function_typed_test/05: RuntimeError
assertion_initializer_const_error2_test/none: CompileTimeError
assertion_initializer_test: CompileTimeError
assertion_test: RuntimeError
-async_await_syntax_test/a06a: RuntimeError
-async_await_syntax_test/b06a: RuntimeError
-async_await_syntax_test/c06a: RuntimeError
-async_await_syntax_test/d06a: RuntimeError
async_await_test/02: RuntimeError
async_await_test/03: RuntimeError
async_await_test/none: RuntimeError
@@ -1919,25 +1780,16 @@
async_congruence_method_test/none: RuntimeError
async_congruence_top_level_test: RuntimeError
async_congruence_unnamed_test/none: RuntimeError
-async_error_timing_test: RuntimeError
async_or_generator_return_type_stacktrace_test/01: MissingCompileTimeError
async_or_generator_return_type_stacktrace_test/02: MissingCompileTimeError
async_or_generator_return_type_stacktrace_test/03: MissingCompileTimeError
async_return_types_test/nestedFuture: Crash # Interpolated value #1 is not an Expression or List of Expressions: [VariableUse(f), Instance of 'LiteralNull', null]
-async_return_types_test/none: RuntimeError
async_return_types_test/tooManyTypeParameters: Crash # Interpolated value #1 is not an Expression or List of Expressions: [VariableUse(f), Instance of 'LiteralNull', null]
async_return_types_test/wrongReturnType: Crash # Interpolated value #1 is not an Expression or List of Expressions: [VariableUse(f), Instance of 'LiteralNull', null]
async_star_await_pauses_test: RuntimeError
-async_star_cancel_and_throw_in_finally_test: RuntimeError
async_star_cancel_while_paused_test: Crash # Interpolated value #1 is not an Expression or List of Expressions: [VariableUse(f), Instance of 'LiteralNull', null]
-async_star_no_cancel2_test: RuntimeError
-async_star_no_cancel_test: RuntimeError
-async_star_pause_test: RuntimeError
async_star_regression_2238_test: RuntimeError
-async_star_regression_23116_test: RuntimeError
-async_star_regression_fisk_test: RuntimeError
async_star_stream_take_test: RuntimeError
-async_star_take_reyield_test: RuntimeError
async_star_test/01: RuntimeError
async_star_test/02: RuntimeError
async_star_test/03: RuntimeError
@@ -1945,23 +1797,13 @@
async_star_test/05: RuntimeError
async_star_test/none: RuntimeError
async_test: RuntimeError
-asyncstar_concat_test: RuntimeError
-asyncstar_yield_test: RuntimeError
-asyncstar_yieldstar_test: RuntimeError
-await_for_cancel_test: RuntimeError
-await_for_test: RuntimeError
-await_for_use_local_test: RuntimeError
await_not_started_immediately_test: Crash # Assertion failure: Runtime type information not available for type_variable_local(bindCallback.R) in (local(_RootZone.bindCallback#)) for j:closure_call(_RootZone_bindCallback_closure.call).
-await_test: RuntimeError
bad_override_test/01: MissingCompileTimeError
bad_override_test/02: MissingCompileTimeError
bad_override_test/03: MissingCompileTimeError
bad_override_test/04: MissingCompileTimeError
bad_override_test/05: MissingCompileTimeError
bit_operations_test: RuntimeError
-bool_check_test: RuntimeError
-bool_condition_check_test: RuntimeError
-bool_test: RuntimeError
branch_canonicalization_test: RuntimeError
call_non_method_field_test/01: MissingCompileTimeError
call_non_method_field_test/02: MissingCompileTimeError
@@ -1978,7 +1820,6 @@
class_literal_static_test/07: MissingCompileTimeError
closure_invoked_through_interface_target_field_test: MissingCompileTimeError
closure_invoked_through_interface_target_getter_test: MissingCompileTimeError
-closure_type_test: RuntimeError
compile_time_constant_d_test: CompileTimeError
compile_time_constant_e_test: CompileTimeError
compile_time_constant_k_test/01: MissingCompileTimeError
@@ -2115,42 +1956,21 @@
full_stacktrace1_test: RuntimeError # Issue 12698
full_stacktrace2_test: RuntimeError # Issue 12698
full_stacktrace3_test: RuntimeError # Issue 12698
-function_subtype2_test: RuntimeError
function_subtype3_test: RuntimeError
-function_subtype_bound_closure2_test: RuntimeError
function_subtype_bound_closure3_test: RuntimeError
function_subtype_bound_closure4_test: RuntimeError
-function_subtype_bound_closure5_test: RuntimeError
-function_subtype_bound_closure5a_test: RuntimeError
-function_subtype_bound_closure6_test: RuntimeError
function_subtype_bound_closure7_test: RuntimeError
function_subtype_call0_test: RuntimeError
function_subtype_call1_test: RuntimeError
function_subtype_call2_test: RuntimeError
function_subtype_cast1_test: RuntimeError
-function_subtype_checked0_test: RuntimeError
-function_subtype_closure0_test: RuntimeError
-function_subtype_closure1_test: RuntimeError
-function_subtype_factory1_test: RuntimeError
-function_subtype_inline1_test: RuntimeError
function_subtype_inline2_test: RuntimeError
-function_subtype_local2_test: RuntimeError
-function_subtype_local5_test: RuntimeError
function_subtype_not1_test: RuntimeError
-function_subtype_optional1_test: RuntimeError
-function_subtype_optional2_test: RuntimeError
-function_subtype_regression_ddc_588_test: RuntimeError
function_subtype_setter0_test: RuntimeError
-function_subtype_simple2_test: RuntimeError
function_subtype_typearg5_test: RuntimeError
function_type2_test: RuntimeError
function_type_alias2_test: RuntimeError
function_type_alias4_test: RuntimeError
-function_type_alias_test: RuntimeError
-function_type_call_getter2_test/none: RuntimeError
-function_type_test: RuntimeError
-generic_async_star_test: RuntimeError
-generic_field_mixin6_test/none: RuntimeError
generic_function_bounds_test: RuntimeError
generic_function_dcall_test: RuntimeError
generic_function_type_as_type_argument_test/01: MissingCompileTimeError
@@ -2181,8 +2001,6 @@
getter_override_test/01: MissingCompileTimeError
getter_override_test/02: MissingCompileTimeError
getter_override_test/03: MissingCompileTimeError
-getters_setters2_test/01: RuntimeError
-getters_setters2_test/none: RuntimeError
identical_closure2_test: RuntimeError # non JS number semantics
identical_const_test/01: MissingCompileTimeError
identical_const_test/02: MissingCompileTimeError
@@ -2191,7 +2009,6 @@
if_null_precedence_test/none: RuntimeError
implicit_creation/implicit_new_or_const_composite_test: RuntimeError
implicit_creation/implicit_new_or_const_test: RuntimeError
-implicit_downcast_during_return_async_test: Crash # Assertion failure: Runtime type information not available for type_variable_local(bindCallback.R) in (local(_RootZone.bindCallback#)) for j:closure_call(_RootZone_bindCallback_closure.call).
implicit_this_test/01: MissingCompileTimeError
implicit_this_test/04: MissingCompileTimeError
inferrer_synthesized_constructor_test: RuntimeError
@@ -2223,7 +2040,6 @@
issue31596_override_test/08: MissingCompileTimeError
issue31596_super_test/01: CompileTimeError
issue31596_super_test/03: CompileTimeError
-known_identifier_usage_error_test/none: RuntimeError
left_shift_test: RuntimeError # non JS number semantics
library_env_test/has_mirror_support: RuntimeError
library_env_test/has_no_html_support: RuntimeError
@@ -2233,9 +2049,6 @@
local_function3_test/none: RuntimeError
local_function_test/none: RuntimeError
main_test/03: RuntimeError
-main_test/20: RuntimeError
-main_test/22: RuntimeError
-main_test/44: RuntimeError
malbounded_instantiation_test/01: MissingCompileTimeError
malbounded_instantiation_test/02: MissingCompileTimeError
malbounded_instantiation_test/03: MissingCompileTimeError
@@ -2393,7 +2206,6 @@
null_test/none: RuntimeError
number_identity2_test: RuntimeError
numbers_test: RuntimeError, OK # non JS number semantics
-operator4_test: RuntimeError
overridden_no_such_method_test: RuntimeError
override_field_method1_negative_test: Fail
override_field_method2_negative_test: Fail
@@ -2464,9 +2276,7 @@
regress_22443_test: RuntimeError
regress_23089_test: Crash # Stack Overflow
regress_23408_test: CompileTimeError
-regress_23996_test: RuntimeError
regress_24283_test: RuntimeError, OK # Requires 64 bit numbers.
-regress_24935_test/none: RuntimeError
regress_27617_test/1: Crash # Assertion failure: Unexpected constructor j:constructor(Foo._) in ConstructorDataImpl._getConstructorConstant
regress_28255_test: RuntimeError
regress_28278_test: RuntimeError
@@ -2475,7 +2285,6 @@
regress_29784_test/01: Crash # Issue 29784
regress_29784_test/02: MissingCompileTimeError # Issue 29784
regress_30339_test: CompileTimeError
-regress_31591_test: RuntimeError
runtime_type_function_test: RuntimeError
setter4_test: MissingCompileTimeError
setter_no_getter_test/01: CompileTimeError
@@ -2483,7 +2292,6 @@
setter_override_test/01: MissingCompileTimeError
setter_override_test/02: MissingCompileTimeError
setter_override_test/03: MissingCompileTimeError
-shadow_parameter_and_local_test: RuntimeError
stack_trace_test: RuntimeError, OK # Stack trace not preserved in minified code.
stacktrace_demangle_ctors_test: RuntimeError # Issue 12698
stacktrace_rethrow_error_test/none: RuntimeError # Issue 12698
@@ -2548,8 +2356,6 @@
type_variable_bounds_test/08: MissingCompileTimeError
type_variable_bounds_test/11: MissingCompileTimeError
type_variable_promotion_test: RuntimeError
-typedef_is_test: RuntimeError
-typevariable_substitution2_test/02: RuntimeError
vm/async_await_catch_stacktrace_test: Crash # Assertion failure: Runtime type information not available for type_variable_local(bindCallback.R) in (local(_RootZone.bindCallback#)) for j:closure_call(_RootZone_bindCallback_closure.call).
vm/await_synchronous_future_test: Crash # Interpolated value #1 is not an Expression or List of Expressions: [VariableUse(f), Instance of 'LiteralNull', null]
vm/causal_async_exception_stack2_test: Crash # Wrong number of template arguments, given 2, expected 1
@@ -2586,7 +2392,6 @@
void_type_usage_test/conditional_return_to_void: MissingCompileTimeError
wrong_number_type_arguments_test/01: MissingCompileTimeError
wrong_number_type_arguments_test/none: Pass
-yieldstar_pause_test: RuntimeError
[ $compiler == dart2js && $fasta && $strong ]
mixin_type_parameter5_test: RuntimeError
diff --git a/tests/language_2/language_2_dartdevc.status b/tests/language_2/language_2_dartdevc.status
index 2dfeef7..ebb3c4d 100644
--- a/tests/language_2/language_2_dartdevc.status
+++ b/tests/language_2/language_2_dartdevc.status
@@ -611,8 +611,6 @@
multiline_newline_test/06r: MissingCompileTimeError
named_constructor_test/01: MissingCompileTimeError
named_parameters_default_eq_test/02: MissingCompileTimeError
-no_such_method_mock_test: RuntimeError # Issue 31425
-nosuchmethod_forwarding/nosuchmethod_forwarding_test/06: RuntimeError # Issue 31425
nosuchmethod_forwarding/nosuchmethod_forwarding_arguments_test: RuntimeError # Issue 31425
nsm5_test: MissingCompileTimeError
null2_test: RuntimeError # Issue 32194
diff --git a/tests/language_2/language_2_kernel.status b/tests/language_2/language_2_kernel.status
index 776be24..7fff2fc 100644
--- a/tests/language_2/language_2_kernel.status
+++ b/tests/language_2/language_2_kernel.status
@@ -243,7 +243,6 @@
syntax_test/33: MissingCompileTimeError
syntax_test/60: MissingCompileTimeError
syntax_test/61: MissingCompileTimeError
-syntax_test/62: MissingCompileTimeError
type_variable_bounds2_test: MissingCompileTimeError
type_variable_bounds3_test/00: MissingCompileTimeError
type_variable_bounds4_test/01: MissingCompileTimeError
@@ -792,6 +791,7 @@
assertion_initializer_const_error2_test/cc11: MissingCompileTimeError # Not reporting failed assert() at compile time.
redirecting_factory_reflection_test: RuntimeError
+
# Enabling of dartk for sim{arm,arm64,dbc64} revelaed these test failures, which
# are to be triaged. Isolate tests are skipped on purpose due to the usage of
# batch mode.
diff --git a/tests/language_2/no_such_method_mock_test.dart b/tests/language_2/no_such_method_mock_test.dart
index 8f146b7..64d0597 100644
--- a/tests/language_2/no_such_method_mock_test.dart
+++ b/tests/language_2/no_such_method_mock_test.dart
@@ -8,11 +8,13 @@
class Cat {
bool eatFood(String food) => true;
String scratch(String furniture) => 'purr';
+ String mood;
}
class MockCat implements Cat {
dynamic noSuchMethod(Invocation invocation) {
- return (invocation.positionalArguments[0] as String).isNotEmpty;
+ var arg = invocation.positionalArguments[0];
+ return arg is String && arg.isNotEmpty;
}
}
@@ -64,6 +66,11 @@
MockCat mock = new MockCat();
Expect.isTrue((mock as dynamic).eatFood("cat food"));
Expect.isFalse(mock.eatFood(""));
+ mock.mood = 'sleepy';
+ (mock as dynamic).mood = 'playful';
+ Expect.throwsTypeError(() {
+ (mock as dynamic).mood = 42;
+ });
// In strong mode this will be a runtime type error:
// bool is not a String. VM will fail with noSuchMethod +.
@@ -154,7 +161,15 @@
Expect.listEquals([String], doStuff('hi'));
// no inference happens because `doStuff2` is dynamic.
- Expect.listEquals([dynamic], doStuff2(42));
Expect.listEquals([num], doStuff2<num>(42));
- Expect.listEquals([dynamic], doStuff2('hi'));
+ expectIsDynamicOrObject(List types) {
+ Expect.equals(1, types.length);
+ var t = types[0];
+ // TODO(jmesserly): allows either type because of
+ // https://github.com/dart-lang/sdk/issues/32483
+ Expect.isTrue(t == dynamic || t == Object, '$t == dynamic || $t == Object');
+ }
+
+ expectIsDynamicOrObject(doStuff2(42));
+ expectIsDynamicOrObject(doStuff2('hi'));
}
diff --git a/tests/language_2/nosuchmethod_forwarding/nosuchmethod_forwarding_arguments_test.dart b/tests/language_2/nosuchmethod_forwarding/nosuchmethod_forwarding_arguments_test.dart
index cf5b1be..ab35197 100644
--- a/tests/language_2/nosuchmethod_forwarding/nosuchmethod_forwarding_arguments_test.dart
+++ b/tests/language_2/nosuchmethod_forwarding/nosuchmethod_forwarding_arguments_test.dart
@@ -30,6 +30,8 @@
return null;
} else if (invoke.memberName == #test6) {
return 1;
+ } else if (invoke.memberName == #test7) {
+ return "hi";
} else if (invoke.memberName == #allTogetherNow) {
Expect.equals(invoke.typeArguments.length, 2);
Expect.equals(invoke.typeArguments[0].toString(), "num");
@@ -51,6 +53,9 @@
void test5<T extends num>(T x);
String test6();
+ int get test7;
+ void set test7(int x);
+
T allTogetherNow<T, S extends T>(S x1, {List<T> foo: const <Null>[]});
}
@@ -80,5 +85,8 @@
Expect.throwsTypeError(() => a.test6());
Expect.throwsTypeError(() => (a.test6 as dynamic)());
+ Expect.throwsTypeError(() => a.test7);
+ Expect.throwsTypeError(() => (a as dynamic).test7 = "hi");
+
a.allTogetherNow<num, double>(2.0, foo: const <num>[3, 4]);
}
diff --git a/tests/language_2/shadow_parameter_and_local_test.dart b/tests/language_2/shadow_parameter_and_local_test.dart
index 12af69a..6082f59 100644
--- a/tests/language_2/shadow_parameter_and_local_test.dart
+++ b/tests/language_2/shadow_parameter_and_local_test.dart
@@ -45,6 +45,31 @@
return a;
}
+ mOptional([a = 0]) {
+ var a = 123;
+ return a;
+ }
+
+ mNamed({a = 0}) {
+ var a = 123;
+ return a;
+ }
+
+ mAsync({a: 0}) async {
+ var a = 123;
+ return a;
+ }
+
+ mSyncStar({a: 0}) sync* {
+ var a = 123;
+ yield a;
+ }
+
+ mAsyncStar({a: 0}) async* {
+ var a = 123;
+ yield a;
+ }
+
get accessor => _value;
set accessor(a) {
var a = 123;
@@ -71,20 +96,39 @@
}
main() async {
- Expect.equals(foo(42), 123);
- Expect.equals(await bar(42), 123);
- Expect.equals(baz(42).single, 123);
- Expect.equals(await qux(42).single, 123);
+ Expect.equals(123, foo(42));
+ Expect.equals(123, await bar(42));
+ Expect.equals(123, baz(42).single);
+ Expect.equals(123, await qux(42).single);
+ await testClass();
+
+ Expect.equals(123, testCatch());
+ Expect.equals(123, testStackTrace());
+}
+
+testClass() async {
var c = new C('hi');
- Expect.equals(c.x, 123);
- Expect.equals(c.method(42), 123);
+ Expect.equals(123, c.x);
+ Expect.equals(123, c.method(42));
c.accessor = 42;
- Expect.equals(c.accessor, 123);
+ Expect.equals(123, c.accessor);
c = new C.initY(42);
- Expect.equals(c.y, 42);
- Expect.equals(c.localY, 123);
+ Expect.equals(42, c.y);
+ Expect.equals(123, c.localY);
- Expect.equals(testCatch(), 123);
- Expect.equals(testStackTrace(), 123);
+ Expect.equals(123, c.mOptional());
+ Expect.equals(123, c.mOptional(42));
+
+ Expect.equals(123, c.mNamed());
+ Expect.equals(123, c.mNamed(a: 42));
+
+ Expect.equals(123, await c.mAsync());
+
+ var iter = c.mSyncStar();
+ Expect.listEquals([123], iter.toList());
+ Expect.listEquals([123], iter.toList(), 'second iteration yields same value');
+
+ var stream = c.mAsyncStar();
+ Expect.listEquals([123], await stream.toList());
}
diff --git a/tests/lib_2/html/cssstyledeclaration_test.dart b/tests/lib_2/html/cssstyledeclaration_test.dart
index ad1ac158..fba53ce 100644
--- a/tests/lib_2/html/cssstyledeclaration_test.dart
+++ b/tests/lib_2/html/cssstyledeclaration_test.dart
@@ -114,13 +114,13 @@
treeSanitizer: new NullTreeSanitizer());
document.documentElement.children.add(listElement);
- var elements = document.queryAll('li');
+ var elements = document.querySelectorAll('li');
expect(elements.style.backgroundColor, equals('red'));
expect(elements.style.borderLeftWidth, equals('10px'));
- elements = document.queryAll('.baz');
+ elements = document.querySelectorAll('.baz');
expect(elements.style.backgroundColor, equals('black'));
expect(elements.style.borderLeftWidth, equals(''));
- elements = document.queryAll('.bar');
+ elements = document.querySelectorAll('.bar');
expect(elements.style.backgroundColor, equals('red'));
});
@@ -134,25 +134,25 @@
treeSanitizer: new NullTreeSanitizer());
document.documentElement.children.add(listElement);
- var elements = document.queryAll('li');
+ var elements = document.querySelectorAll('li');
elements.style.backgroundColor = 'green';
expect(elements.style.backgroundColor, equals('green'));
expect(elements.style.borderLeftWidth, equals('10px'));
- elements = document.queryAll('.baz');
+ elements = document.querySelectorAll('.baz');
expect(elements.style.backgroundColor, equals('green'));
elements.style.backgroundColor = 'yellow';
expect(elements.style.backgroundColor, equals('yellow'));
expect(elements.style.borderLeftWidth, equals(''));
- elements = document.queryAll('.bar');
+ elements = document.querySelectorAll('.bar');
expect(elements.style.backgroundColor, equals('green'));
- elements = document.queryAll('#wat');
+ elements = document.querySelectorAll('#wat');
expect(elements.style.backgroundColor, equals('yellow'));
elements.style.borderLeftWidth = '18px';
expect(elements.style.borderLeftWidth, equals('18px'));
- elements = document.queryAll('li');
+ elements = document.querySelectorAll('li');
expect(elements.style.borderLeftWidth, equals('10px'));
});
diff --git a/tests/lib_2/html/custom/created_callback_test.dart b/tests/lib_2/html/custom/created_callback_test.dart
index 4961b8b..1e75937 100644
--- a/tests/lib_2/html/custom/created_callback_test.dart
+++ b/tests/lib_2/html/custom/created_callback_test.dart
@@ -37,12 +37,12 @@
return;
}
- var t = div.query('#t');
- var v = div.query('#v');
- var w = div.query('#w');
+ var t = div.querySelector('#t');
+ var v = div.querySelector('#v');
+ var w = div.querySelector('#w');
- expect(query('x-b:not(:unresolved)'), this);
- expect(queryAll(':unresolved'), [v, w]);
+ expect(querySelector('x-b:not(:unresolved)'), this);
+ expect(querySelectorAll(':unresolved'), [v, w]);
// As per:
// http://www.w3.org/TR/2013/WD-custom-elements-20130514/#serializing-and-parsing
@@ -91,7 +91,7 @@
upgradeCustomElements(div);
expect(C.createdInvocations, 2);
- expect(div.query('#w') is B, isTrue);
+ expect(div.querySelector('#w') is B, isTrue);
});
test('nesting of constructors', NestedElement.test);
diff --git a/tests/lib_2/html/custom_elements_test.dart b/tests/lib_2/html/custom_elements_test.dart
index 233972e..223145e 100644
--- a/tests/lib_2/html/custom_elements_test.dart
+++ b/tests/lib_2/html/custom_elements_test.dart
@@ -139,7 +139,7 @@
treeSanitizer: new NullTreeSanitizer());
upgradeCustomElements(element);
document.body.nodes.add(element);
- var queried = query(tag) as CustomType;
+ var queried = querySelector(tag) as CustomType;
expect(queried, isNotNull);
expect(queried is CustomType, isTrue);
@@ -154,7 +154,7 @@
treeSanitizer: new NullTreeSanitizer());
upgradeCustomElements(element);
document.body.nodes.add(element);
- var queried = query('#someid') as CustomType;
+ var queried = querySelector('#someid') as CustomType;
expect(queried, isNotNull);
expect(queried is CustomType, isTrue);
diff --git a/tests/lib_2/html/custom_tags_test.dart b/tests/lib_2/html/custom_tags_test.dart
index 5c91168..637879a 100644
--- a/tests/lib_2/html/custom_tags_test.dart
+++ b/tests/lib_2/html/custom_tags_test.dart
@@ -13,10 +13,10 @@
var element = new Element.tag('x-basic1')..id = 'basic1';
document.body.nodes.add(element);
- var queryById = query('#basic1');
+ var queryById = querySelector('#basic1');
expect(queryById, equals(element));
- var queryByTag = queryAll('x-basic1');
+ var queryByTag = querySelectorAll('x-basic1');
expect(queryByTag.length, equals(1));
expect(queryByTag[0], equals(element));
});
@@ -27,10 +27,10 @@
treeSanitizer: new NullTreeSanitizer());
document.body.nodes.add(element);
- var queryById = query('#basic2');
+ var queryById = querySelector('#basic2');
expect(queryById is Element, isTrue);
- var queryByTag = queryAll('x-basic2');
+ var queryByTag = querySelectorAll('x-basic2');
expect(queryByTag.length, equals(1));
expect(queryByTag[0], equals(queryById));
});
@@ -41,7 +41,7 @@
treeSanitizer: new NullTreeSanitizer());
document.body.nodes.add(element);
- var queryById = query('#basic3');
+ var queryById = querySelector('#basic3');
expect(queryById is DivElement, isTrue);
});
}
diff --git a/tests/lib_2/html/dart_object_local_storage_test.dart b/tests/lib_2/html/dart_object_local_storage_test.dart
index 2747700..f45fbfa 100644
--- a/tests/lib_2/html/dart_object_local_storage_test.dart
+++ b/tests/lib_2/html/dart_object_local_storage_test.dart
@@ -25,7 +25,7 @@
expect(sessionStorage, equals(window.sessionStorage));
});
test('unknown', () {
- var test = document.query('#test');
+ var test = document.querySelector('#test');
expect(element, equals(test));
});
}
diff --git a/tests/lib_2/html/datalistelement_test.dart b/tests/lib_2/html/datalistelement_test.dart
index df87da0..d46a313 100644
--- a/tests/lib_2/html/datalistelement_test.dart
+++ b/tests/lib_2/html/datalistelement_test.dart
@@ -33,7 +33,7 @@
test('is', () {
try {
- var list = document.query('#browsers');
+ var list = document.querySelector('#browsers');
expect(list, isDataListElement);
} catch (e) {
expect(DataListElement.supported, false);
@@ -42,8 +42,8 @@
test('list', () {
try {
- var list = document.query('#browsers') as DataListElement;
- var input = document.query('#input') as InputElement;
+ var list = document.querySelector('#browsers') as DataListElement;
+ var input = document.querySelector('#input') as InputElement;
expect(input.list, list);
} catch (e) {
expect(DataListElement.supported, false);
@@ -52,7 +52,8 @@
test('options', () {
try {
- var options = (document.query('#browsers') as DataListElement).options;
+ var options =
+ (document.querySelector('#browsers') as DataListElement).options;
expect(options.length, 5);
} catch (e) {
expect(DataListElement.supported, false);
diff --git a/tests/lib_2/html/document_test.dart b/tests/lib_2/html/document_test.dart
index 9536b3f..1ded093 100644
--- a/tests/lib_2/html/document_test.dart
+++ b/tests/lib_2/html/document_test.dart
@@ -32,7 +32,7 @@
</ResultSet>''',
'text/xml');
- var rs = doc.query('ResultSet');
+ var rs = doc.querySelector('ResultSet');
expect(rs, isNotNull);
});
@@ -50,7 +50,7 @@
expect(doc.adoptNode(div), div);
expect(div.ownerDocument, doc);
doc.body.nodes.add(div);
- expect(doc.query('#foo').text, 'bar');
+ expect(doc.querySelector('#foo').text, 'bar');
});
test('importNode', () {
@@ -60,7 +60,7 @@
expect(div2, notEquals(div));
expect(div2.ownerDocument, doc);
doc.body.nodes.add(div2);
- expect(doc.query('#foo').text, 'bar');
+ expect(doc.querySelector('#foo').text, 'bar');
});
test('typeTest1', () {
diff --git a/tests/lib_2/html/documentfragment_test.dart b/tests/lib_2/html/documentfragment_test.dart
index ac07b64..603769a 100644
--- a/tests/lib_2/html/documentfragment_test.dart
+++ b/tests/lib_2/html/documentfragment_test.dart
@@ -163,8 +163,8 @@
test('query searches the fragment', () {
var fragment = new DocumentFragment.html(
"<div class='foo'><a>foo</a><b>bar</b></div>");
- expect(fragment.query(".foo a").tagName, "A");
- expect(
- _nodeStrings(fragment.queryAll<Element>(".foo *")), equals(["A", "B"]));
+ expect(fragment.querySelector(".foo a").tagName, "A");
+ expect(_nodeStrings(fragment.querySelectorAll<Element>(".foo *")),
+ equals(["A", "B"]));
});
}
diff --git a/tests/lib_2/html/element_classes_test.dart b/tests/lib_2/html/element_classes_test.dart
index 1688422..3bd1507 100644
--- a/tests/lib_2/html/element_classes_test.dart
+++ b/tests/lib_2/html/element_classes_test.dart
@@ -278,7 +278,7 @@
test('listClasses=', () {
var elements = listElementSetup();
elements.classes = ['foo', 'qux'];
- elements = document.queryAll('li');
+ elements = document.querySelectorAll('li');
for (Element e in elements) {
expect(e.classes, equals(['foo', 'qux']));
expect(extractClasses(e), equals(['foo', 'qux']));
diff --git a/tests/lib_2/html/element_dimensions_test.dart b/tests/lib_2/html/element_dimensions_test.dart
index 666049b..68aa316 100644
--- a/tests/lib_2/html/element_dimensions_test.dart
+++ b/tests/lib_2/html/element_dimensions_test.dart
@@ -42,7 +42,7 @@
setUp(initDiv);
test('contentEdge.height', () {
- var all1 = queryAll('#test');
+ var all1 = querySelectorAll('#test');
expect(all1.contentEdge.height, 10);
expect(all1[0].getComputedStyle().getPropertyValue('height'), '10px');
@@ -68,7 +68,7 @@
});
test('contentEdge.height with border-box', () {
- var all1 = queryAll('#test');
+ var all1 = document.querySelectorAll('#test');
div.style.boxSizing = 'border-box';
expect(all1.contentEdge.height, 2);
div.style.padding = '20pc';
@@ -78,7 +78,7 @@
});
test('contentEdge.width', () {
- var all1 = queryAll('#test');
+ var all1 = document.querySelectorAll('#test');
expect(all1.contentEdge.width, 11);
expect(all1[0].getComputedStyle().getPropertyValue('width'), '11px');
@@ -101,7 +101,7 @@
});
test('contentEdge.width with border-box', () {
- var all1 = queryAll('#test');
+ var all1 = document.querySelectorAll('#test');
div.style.boxSizing = 'border-box';
expect(all1.contentEdge.width, 3);
div.style.padding = '20pc';
@@ -111,7 +111,7 @@
});
test('paddingEdge.height', () {
- var all1 = queryAll('#test');
+ var all1 = document.querySelectorAll('#test');
expect(all1.paddingEdge.height, 18);
all1[0].style.visibility = 'hidden';
expect(all1.paddingEdge.height, 18);
@@ -126,7 +126,7 @@
});
test('paddingEdge.height with border-box', () {
- var all1 = queryAll('#test');
+ var all1 = document.querySelectorAll('#test');
div.style.boxSizing = 'border-box';
expect(all1.paddingEdge.height, 10);
div.style.padding = '20pc';
@@ -136,7 +136,7 @@
});
test('paddingEdge.width', () {
- var all1 = queryAll('#test');
+ var all1 = document.querySelectorAll('#test');
expect(all1.paddingEdge.width, 19);
all1[0].style.visibility = 'hidden';
expect(all1.paddingEdge.width, 19);
@@ -152,7 +152,7 @@
});
test('paddingEdge.width with border-box', () {
- var all1 = queryAll('#test');
+ var all1 = document.querySelectorAll('#test');
div.style.boxSizing = 'border-box';
expect(all1.paddingEdge.width, 11);
div.style.padding = '20pc';
@@ -162,7 +162,7 @@
});
test('borderEdge.height and marginEdge.height', () {
- var all1 = queryAll('#test');
+ var all1 = document.querySelectorAll('#test');
expect(div.borderEdge.height, 18);
expect(div.marginEdge.height, 30);
expect(all1.borderEdge.height, 18);
@@ -181,7 +181,7 @@
});
test('borderEdge.height and marginEdge.height with border-box', () {
- var all1 = queryAll('#test');
+ var all1 = document.querySelectorAll('#test');
div.style.boxSizing = 'border-box';
expect(all1.borderEdge.height, 10);
expect(all1.marginEdge.height, 22);
@@ -194,7 +194,7 @@
});
test('borderEdge.width and marginEdge.width', () {
- var all1 = queryAll('#test');
+ var all1 = document.querySelectorAll('#test');
expect(all1.borderEdge.width, 19);
expect(all1.marginEdge.width, 31);
@@ -209,7 +209,7 @@
});
test('borderEdge.width and marginEdge.width with border-box', () {
- var all1 = queryAll('#test');
+ var all1 = document.querySelectorAll('#test');
div.style.boxSizing = 'border-box';
expect(all1.borderEdge.width, 11);
expect(all1.marginEdge.width, 23);
@@ -225,7 +225,7 @@
div.style.border = '1px solid #fff';
div.style.margin = '6px 7px';
div.style.padding = '4px 5px';
- var all1 = queryAll('#test');
+ var all1 = document.querySelectorAll('#test');
expect(all1.borderEdge.left, all1[0].getBoundingClientRect().left);
expect(all1.borderEdge.top, all1[0].getBoundingClientRect().top);
@@ -245,7 +245,7 @@
div.style.border = '1px solid #fff';
div.style.margin = '6px 7px';
div.style.padding = '4px 5px';
- var all1 = queryAll('div');
+ var all1 = document.querySelectorAll('div');
all1.contentEdge.height = new Dimension.px(200);
all1.contentEdge.height = 200;
for (Element elem in all1) {
diff --git a/tests/lib_2/html/element_offset_test.dart b/tests/lib_2/html/element_offset_test.dart
index ce5327d..7643660 100644
--- a/tests/lib_2/html/element_offset_test.dart
+++ b/tests/lib_2/html/element_offset_test.dart
@@ -66,15 +66,15 @@
setUp(initPage);
test('offsetTo', () {
- var itema = query('.item-a');
- var itemb = query('.item-b');
- var item1 = query('.item-1');
- var itemii = query('.item-ii');
- var level1 = query('.level-1');
- var baz = query('.baz');
- var bar = query('.bar');
- var qux = query('.qux');
- var quux = query('.quux');
+ var itema = querySelector('.item-a');
+ var itemb = querySelector('.item-b');
+ var item1 = querySelector('.item-1');
+ var itemii = querySelector('.item-ii');
+ var level1 = querySelector('.level-1');
+ var baz = querySelector('.baz');
+ var bar = querySelector('.bar');
+ var qux = querySelector('.qux');
+ var quux = querySelector('.quux');
var point = itema.offsetTo(itemii);
expect(point.x, 40);
@@ -99,14 +99,14 @@
});
test('documentOffset', () {
- var bar = query('.bar');
- var baz = query('.baz');
- var qux = query('.qux');
- var quux = query('.quux');
- var itema = query('.item-a');
- var itemb = query('.item-b');
- var item1 = query('.item-1');
- var itemii = query('.item-ii');
+ var bar = querySelector('.bar');
+ var baz = querySelector('.baz');
+ var qux = querySelector('.qux');
+ var quux = querySelector('.quux');
+ var itema = querySelector('.item-a');
+ var itemb = querySelector('.item-b');
+ var item1 = querySelector('.item-1');
+ var itemii = querySelector('.item-ii');
expect(itema.documentOffset.x, 88);
expect(itema.documentOffset.y, inInclusiveRange(111, 160));
diff --git a/tests/lib_2/html/element_test.dart b/tests/lib_2/html/element_test.dart
index 366b98d..b6eeb2b 100644
--- a/tests/lib_2/html/element_test.dart
+++ b/tests/lib_2/html/element_test.dart
@@ -650,8 +650,8 @@
});
});
- group('queryAll', () {
- List<Element> getQueryAll() {
+ group('querySelectorAll', () {
+ List<Element> getQuerySelectorAll() {
return new Element.html("""
<div>
<hr/>
@@ -662,59 +662,61 @@
</p>
<hr class='q'/>
</div>
-""").queryAll('.q');
+""").querySelectorAll('.q');
}
- List<Element> getEmptyQueryAll() => new Element.tag('div').queryAll('img');
+ List<Element> getEmptyQuerySelectorAll() =>
+ new Element.tag('div').querySelectorAll('img');
test('last', () {
- expect(getQueryAll().last, isHRElement);
+ expect(getQuerySelectorAll().last, isHRElement);
});
test('forEach', () {
var els = [];
- getQueryAll().forEach((el) => els.add(el));
+ getQuerySelectorAll().forEach((el) => els.add(el));
expect(els[0], isAnchorElement);
expect(els[1], isSpanElement);
expect(els[2], isHRElement);
});
test('map', () {
- var texts = getQueryAll().map((el) => el.text).toList();
+ var texts = getQuerySelectorAll().map((el) => el.text).toList();
expect(texts, equals(['Dart!', 'Hello', '']));
});
test('where', () {
- var filtered = getQueryAll().where((n) => n is SpanElement).toList();
+ var filtered =
+ getQuerySelectorAll().where((n) => n is SpanElement).toList();
expect(filtered.length, 1);
expect(filtered[0], isSpanElement);
expect(filtered, isElementList);
});
test('every', () {
- var el = getQueryAll();
+ var el = getQuerySelectorAll();
expect(el.every((n) => n is Element), isTrue);
expect(el.every((n) => n is SpanElement), isFalse);
});
test('any', () {
- var el = getQueryAll();
+ var el = getQuerySelectorAll();
expect(el.any((n) => n is SpanElement), isTrue);
expect(el.any((n) => n is svg.SvgElement), isFalse);
});
test('isEmpty', () {
- expect(getEmptyQueryAll().isEmpty, isTrue);
- expect(getQueryAll().isEmpty, isFalse);
+ expect(getEmptyQuerySelectorAll().isEmpty, isTrue);
+ expect(getQuerySelectorAll().isEmpty, isFalse);
});
test('length', () {
- expect(getEmptyQueryAll().length, 0);
- expect(getQueryAll().length, 3);
+ expect(getEmptyQuerySelectorAll().length, 0);
+ expect(getQuerySelectorAll().length, 3);
});
test('[]', () {
- var els = getQueryAll();
+ var els = getQuerySelectorAll();
expect(els[0], isAnchorElement);
expect(els[1], isSpanElement);
expect(els[2], isHRElement);
@@ -722,7 +724,7 @@
test('iterator', () {
var els = [];
- for (var subel in getQueryAll()) {
+ for (var subel in getQuerySelectorAll()) {
els.add(subel);
}
expect(els[0], isAnchorElement);
@@ -731,31 +733,34 @@
});
test('sublist', () {
- expect(getQueryAll().sublist(1, 2) is List<Element>, isTrue);
+ expect(getQuerySelectorAll().sublist(1, 2) is List<Element>, isTrue);
});
- testUnsupported('[]=', () => getQueryAll()[1] = new Element.tag('br'));
- testUnsupported('add', () => getQueryAll().add(new Element.tag('br')));
+ testUnsupported(
+ '[]=', () => getQuerySelectorAll()[1] = new Element.tag('br'));
+ testUnsupported(
+ 'add', () => getQuerySelectorAll().add(new Element.tag('br')));
testUnsupported('addAll', () {
- getQueryAll().addAll([
+ getQuerySelectorAll().addAll([
new Element.tag('span'),
new Element.tag('a'),
new Element.tag('h1')
]);
});
- testUnsupported('sort', () => getQueryAll().sort((a1, a2) => 0));
+ testUnsupported('sort', () => getQuerySelectorAll().sort((a1, a2) => 0));
testUnsupported('setRange', () {
- getQueryAll().setRange(0, 1, [new BRElement()]);
+ getQuerySelectorAll().setRange(0, 1, [new BRElement()]);
});
- testUnsupported('removeRange', () => getQueryAll().removeRange(0, 1));
+ testUnsupported(
+ 'removeRange', () => getQuerySelectorAll().removeRange(0, 1));
- testUnsupported('clear', () => getQueryAll().clear());
+ testUnsupported('clear', () => getQuerySelectorAll().clear());
- testUnsupported('removeLast', () => getQueryAll().removeLast());
+ testUnsupported('removeLast', () => getQuerySelectorAll().removeLast());
});
group('functional', () {
@@ -849,30 +854,30 @@
document.body.append(elem6);
var firedEvent = false;
- var elems = queryAll('.a');
- queryAll('.a').onClick.listen((event) {
+ var elems = querySelectorAll('.a');
+ querySelectorAll('.a').onClick.listen((event) {
firedEvent = true;
});
expect(firedEvent, false);
- query('.c').click();
+ querySelector('.c').click();
expect(firedEvent, false);
- query('#wat').click();
+ querySelector('#wat').click();
expect(firedEvent, true);
var firedEvent4 = false;
- queryAll('.a').onClick.matches('.d').listen((event) {
+ querySelectorAll('.a').onClick.matches('.d').listen((event) {
firedEvent4 = true;
});
expect(firedEvent4, false);
- query('.c').click();
+ querySelector('.c').click();
expect(firedEvent4, false);
- query('#wat').click();
+ querySelector('#wat').click();
expect(firedEvent4, false);
- query('#cookie').click();
+ querySelector('#cookie').click();
expect(firedEvent4, true);
var firedEvent2 = false;
- queryAll('.a').onClick.listen((event) {
+ querySelectorAll('.a').onClick.listen((event) {
firedEvent2 = true;
});
Element elem2 = new Element.html('<div class="a"><br/>');
@@ -884,7 +889,7 @@
expect(firedEvent2, false);
var firedEvent3 = false;
- queryAll(':root').onClick.matches('.a').listen((event) {
+ querySelectorAll(':root').onClick.matches('.a').listen((event) {
firedEvent3 = true;
});
Element elem3 = new Element.html('<div class="d"><br/>');
@@ -896,11 +901,11 @@
expect(firedEvent3, true);
var firedEvent5 = false;
- queryAll(':root').onClick.matches('.e').listen((event) {
+ querySelectorAll(':root').onClick.matches('.e').listen((event) {
firedEvent5 = true;
});
expect(firedEvent5, false);
- query('.i').click();
+ querySelector('.i').click();
expect(firedEvent5, true);
});
@@ -952,7 +957,7 @@
ElementList<Element> makeElementList() =>
(new Element.html("<div>Foo<br/><!--baz--><br/><br/></div>"))
- .queryAll('br');
+ .querySelectorAll('br');
test('hashCode', () {
var nodes = makeElementList();
diff --git a/tests/lib_2/html/hidden_dom_1_test.dart b/tests/lib_2/html/hidden_dom_1_test.dart
index 9334b5e..820a88a 100644
--- a/tests/lib_2/html/hidden_dom_1_test.dart
+++ b/tests/lib_2/html/hidden_dom_1_test.dart
@@ -11,7 +11,7 @@
<div id='div1'>
Hello World!
</div>'''));
- Element e = document.query('#div1');
+ Element e = document.querySelector('#div1');
expect(e, isNotNull);
expect(() {
diff --git a/tests/lib_2/html/hidden_dom_2_test.dart b/tests/lib_2/html/hidden_dom_2_test.dart
index 5d4d05d..650ee06 100644
--- a/tests/lib_2/html/hidden_dom_2_test.dart
+++ b/tests/lib_2/html/hidden_dom_2_test.dart
@@ -11,7 +11,7 @@
<div id='div1'>
Hello World!
</div>'''));
- Element e = document.query('#div1');
+ Element e = document.querySelector('#div1');
Element e2 = new Element.html(r"<div id='xx'>XX</div>");
expect(e, isNotNull);
diff --git a/tests/lib_2/html/htmlcollection_test.dart b/tests/lib_2/html/htmlcollection_test.dart
index 75e7544..37423c2 100644
--- a/tests/lib_2/html/htmlcollection_test.dart
+++ b/tests/lib_2/html/htmlcollection_test.dart
@@ -37,7 +37,7 @@
test('IsList', () {
Element root = insertTestDiv();
- List<Element> eachChecked = document.query('#allChecked').children;
+ List<Element> eachChecked = document.querySelector('#allChecked').children;
expect(eachChecked is List, isTrue);
@@ -46,11 +46,11 @@
test('Every', () {
Element root = insertTestDiv();
- List<Element> eachChecked = document.query('#allChecked').children;
+ List<Element> eachChecked = document.querySelector('#allChecked').children;
- List<Element> someChecked = document.query('#someChecked').children;
+ List<Element> someChecked = document.querySelector('#someChecked').children;
- List<Element> noneChecked = document.query('#noneChecked').children;
+ List<Element> noneChecked = document.querySelector('#noneChecked').children;
expect(eachChecked.length, 4);
expect(someChecked.length, 4);
@@ -68,11 +68,11 @@
test('Some', () {
Element root = insertTestDiv();
- List<Element> eachChecked = document.query('#allChecked').children;
+ List<Element> eachChecked = document.querySelector('#allChecked').children;
- List<Element> someChecked = document.query('#someChecked').children;
+ List<Element> someChecked = document.querySelector('#someChecked').children;
- List<Element> noneChecked = document.query('#noneChecked').children;
+ List<Element> noneChecked = document.querySelector('#noneChecked').children;
expect(eachChecked.length, 4);
expect(someChecked.length, 4);
@@ -90,11 +90,11 @@
test('Filter', () {
Element root = insertTestDiv();
- List<Element> eachChecked = document.query('#allChecked').children;
+ List<Element> eachChecked = document.querySelector('#allChecked').children;
- List<Element> someChecked = document.query('#someChecked').children;
+ List<Element> someChecked = document.querySelector('#someChecked').children;
- List<Element> noneChecked = document.query('#noneChecked').children;
+ List<Element> noneChecked = document.querySelector('#noneChecked').children;
expect(eachChecked.length, 4);
expect(someChecked.length, 4);
@@ -112,9 +112,9 @@
test('IsEmpty', () {
Element root = insertTestDiv();
- List<Element> someChecked = document.query('#someChecked').children;
+ List<Element> someChecked = document.querySelector('#someChecked').children;
- List<Element> emptyDiv = document.query('#emptyDiv').children;
+ List<Element> emptyDiv = document.querySelector('#emptyDiv').children;
expect(someChecked.length, 4);
expect(emptyDiv.length, 0);
@@ -136,11 +136,11 @@
test('ForEach', () {
Element root = insertTestDiv();
- List<Element> eachChecked = document.query('#allChecked').children;
+ List<Element> eachChecked = document.querySelector('#allChecked').children;
- List<Element> someChecked = document.query('#someChecked').children;
+ List<Element> someChecked = document.querySelector('#someChecked').children;
- List<Element> noneChecked = document.query('#noneChecked').children;
+ List<Element> noneChecked = document.querySelector('#noneChecked').children;
expect(eachChecked.length, 4);
expect(someChecked.length, 4);
@@ -168,11 +168,11 @@
// Uses iterator.
Element root = insertTestDiv();
- List<Element> eachChecked = document.query('#allChecked').children;
+ List<Element> eachChecked = document.querySelector('#allChecked').children;
- List<Element> someChecked = document.query('#someChecked').children;
+ List<Element> someChecked = document.querySelector('#someChecked').children;
- List<Element> noneChecked = document.query('#noneChecked').children;
+ List<Element> noneChecked = document.querySelector('#noneChecked').children;
expect(eachChecked.length, 4);
expect(someChecked.length, 4);
@@ -190,7 +190,7 @@
test('Last', () {
Element root = insertTestDiv();
- List<Element> someChecked = document.query('#someChecked').children;
+ List<Element> someChecked = document.querySelector('#someChecked').children;
expect(someChecked.length, 4);
@@ -201,9 +201,9 @@
test('IndexOf', () {
Element root = insertTestDiv();
- List<Element> someChecked = document.query('#someChecked').children;
+ List<Element> someChecked = document.querySelector('#someChecked').children;
- List<Element> noneChecked = document.query('#noneChecked').children;
+ List<Element> noneChecked = document.querySelector('#noneChecked').children;
expect(someChecked.length, 4);
expect(noneChecked.length, 4);
@@ -228,9 +228,9 @@
test('LastIndexOf', () {
Element root = insertTestDiv();
- List<Element> someChecked = document.query('#someChecked').children;
+ List<Element> someChecked = document.querySelector('#someChecked').children;
- List<Element> noneChecked = document.query('#noneChecked').children;
+ List<Element> noneChecked = document.querySelector('#noneChecked').children;
expect(someChecked.length, 4);
expect(noneChecked.length, 4);
diff --git a/tests/lib_2/html/htmlelement_test.dart b/tests/lib_2/html/htmlelement_test.dart
index 12967a1..fbeb93b 100644
--- a/tests/lib_2/html/htmlelement_test.dart
+++ b/tests/lib_2/html/htmlelement_test.dart
@@ -11,7 +11,7 @@
element.innerHtml = 'Hello World';
document.body.append(element);
- element = document.query('#test');
+ element = document.querySelector('#test');
expect(element.innerHtml, 'Hello World');
element.remove();
});
diff --git a/tests/lib_2/html/query_test.dart b/tests/lib_2/html/query_test.dart
index a1ab333..dab1cff 100644
--- a/tests/lib_2/html/query_test.dart
+++ b/tests/lib_2/html/query_test.dart
@@ -19,7 +19,7 @@
predicate((x) => x is ImageElement, 'is an ImageElement');
test('query', () {
- Element e = query('#testcanvas');
+ Element e = querySelector('#testcanvas');
expect(e, isNotNull);
expect(e.id, 'testcanvas');
expect(e, isCanvasElement);
@@ -27,18 +27,18 @@
});
test('query (None)', () {
- Element e = query('#nothere');
+ Element e = querySelector('#nothere');
expect(e, isNull);
});
test('queryAll (One)', () {
- List l = queryAll('canvas');
+ List l = querySelectorAll('canvas');
expect(l.length, 1);
expect(l[0], canvas);
});
test('queryAll (Multiple)', () {
- List l = queryAll('img');
+ List l = querySelectorAll('img');
expect(l.length, 2);
expect(l[0], isImageElement);
expect(l[1], isImageElement);
@@ -46,7 +46,7 @@
});
test('queryAll (None)', () {
- List l = queryAll('video');
+ List l = querySelectorAll('video');
expect(l.isEmpty, isTrue);
});
}
diff --git a/tests/lib_2/html/queryall_test.dart b/tests/lib_2/html/queryall_test.dart
index 988d083b..e6a913e 100644
--- a/tests/lib_2/html/queryall_test.dart
+++ b/tests/lib_2/html/queryall_test.dart
@@ -26,39 +26,39 @@
new CanvasElement()
]);
- test('queryAll', () {
- List<Node> all = queryAll('*');
+ test('querySelectorAll', () {
+ List<Node> all = querySelectorAll('*');
for (var e in all) {
expect(e, isElement);
}
});
- test('document.queryAll', () {
- List<Element> all1 = queryAll('*');
- List<Element> all2 = document.queryAll('*');
+ test('document.querySelectorAll', () {
+ List<Element> all1 = querySelectorAll('*');
+ List<Element> all2 = document.querySelectorAll('*');
expect(all1.length, equals(all2.length));
for (var i = 0; i < all1.length; ++i) {
expect(all1[i], equals(all2[i]));
}
});
- test('queryAll-canvas', () {
- var all = queryAll('canvas');
+ test('querySelectorAll-canvas', () {
+ var all = querySelectorAll('canvas');
for (var e in all) {
expect(e, isCanvasElement);
}
expect(all.length, equals(2));
});
- test('queryAll-contains', () {
- List<Element> all = queryAll('*');
+ test('querySelectorAll-contains', () {
+ List<Element> all = querySelectorAll('*');
for (var e in all) {
expect(all.contains(e), isTrue);
}
});
- test('queryAll-where', () {
- List<Element> all = queryAll('*');
+ test('querySelectorAll-where', () {
+ List<Element> all = querySelectorAll('*');
var canvases = all.where((e) => e is CanvasElement);
for (var e in canvases) {
expect(e is CanvasElement, isTrue);
@@ -66,8 +66,8 @@
expect(canvases.length, equals(2));
});
- test('node.queryAll', () {
- List<Element> list = div.queryAll('*');
+ test('node.querySelectorAll', () {
+ List<Element> list = div.querySelectorAll('*');
expect(list.length, equals(5));
expect(list[0], isDivElement);
expect(list[1], isCanvasElement);
@@ -77,7 +77,7 @@
});
test('immutable', () {
- List<Element> list = div.queryAll('*');
+ List<Element> list = div.querySelectorAll('*');
int len = list.length;
expect(() {
list.add(new DivElement());
diff --git a/tests/lib_2/html/shadow_dom_test.dart b/tests/lib_2/html/shadow_dom_test.dart
index 347a038..75859d6 100644
--- a/tests/lib_2/html/shadow_dom_test.dart
+++ b/tests/lib_2/html/shadow_dom_test.dart
@@ -39,7 +39,7 @@
expect(() {
init();
- expect(queryAll('.foo'), equals([div1, paragraph2]));
+ expect(querySelectorAll('.foo'), equals([div1, paragraph2]));
}, expectation);
});
@@ -60,7 +60,7 @@
expect(() {
init();
- expect(shadowRoot.queryAll('.foo'), equals([paragraph1]));
+ expect(shadowRoot.querySelectorAll('.foo'), equals([paragraph1]));
}, expectation);
});
diff --git a/tests/lib_2/html/svg_test.dart b/tests/lib_2/html/svg_test.dart
index ef31581..a4996a0 100644
--- a/tests/lib_2/html/svg_test.dart
+++ b/tests/lib_2/html/svg_test.dart
@@ -20,10 +20,10 @@
</svg>
''', validator: new NodeValidatorBuilder()..allowSvg());
- var e = document.query('#svg1');
+ var e = document.querySelector('#svg1');
expect(e, isNotNull);
- svg.RectElement r = document.query('#rect1');
+ svg.RectElement r = document.querySelector('#rect1');
expect(r.x.baseVal.value, 10);
expect(r.y.baseVal.value, 20);
expect(r.height.baseVal.value, 40);
@@ -72,7 +72,7 @@
test('rect_isChecks', () {
var div = insertTestDiv();
- var r = document.query('#rect1');
+ var r = document.querySelector('#rect1');
// Direct inheritance chain
expect(r, isSvgElement);
@@ -121,7 +121,7 @@
testRect(name, checker) {
test(name, () {
var div = insertTestDiv();
- var r = document.query('#rect1');
+ var r = document.querySelector('#rect1');
checker(r);
div.remove();
});
diff --git a/tests/lib_2/html/track_element_constructor_test.dart b/tests/lib_2/html/track_element_constructor_test.dart
index b2077ee..aed7624 100644
--- a/tests/lib_2/html/track_element_constructor_test.dart
+++ b/tests/lib_2/html/track_element_constructor_test.dart
@@ -17,7 +17,7 @@
test('', () {
if (!TrackElement.supported) return;
document.body.append(new TrackElement()..defaultValue = true);
- var trackElement = document.query('track') as TrackElement;
+ var trackElement = document.querySelector('track') as TrackElement;
if (!trackElement.defaultValue) {
throw 'Expected default value to be true';
}
diff --git a/tests/lib_2/html/typing_test.dart b/tests/lib_2/html/typing_test.dart
index d12ffb8..2ea9eef 100644
--- a/tests/lib_2/html/typing_test.dart
+++ b/tests/lib_2/html/typing_test.dart
@@ -7,15 +7,15 @@
predicate((x) => x is List<StyleSheet>, 'is a List<StyleSheet>');
test('NodeList', () {
- List<Element> asList = window.document.queryAll('body');
+ List<Element> asList = window.document.querySelectorAll('body');
// Check it's Iterable
int counter = 0;
- for (Element node in window.document.queryAll('body')) {
+ for (Element node in window.document.querySelectorAll('body')) {
counter++;
}
expect(counter, 1);
counter = 0;
- window.document.queryAll('body').forEach((e) {
+ window.document.querySelectorAll('body').forEach((e) {
counter++;
});
expect(counter, 1);
diff --git a/tests/lib_2/html/unknownelement_test.dart b/tests/lib_2/html/unknownelement_test.dart
index fa88fd8..7b32408 100644
--- a/tests/lib_2/html/unknownelement_test.dart
+++ b/tests/lib_2/html/unknownelement_test.dart
@@ -19,8 +19,8 @@
test('type-check', () {
expect(foo, isUnknownElement);
expect(bar, isUnknownElement);
- expect(query('#foo'), equals(foo));
- expect(query('#bar'), equals(bar));
+ expect(querySelector('#foo'), equals(foo));
+ expect(querySelector('#bar'), equals(bar));
});
test('dispatch-fail', () {
diff --git a/tools/VERSION b/tools/VERSION
index 0827ae8..789f1ce 100644
--- a/tools/VERSION
+++ b/tools/VERSION
@@ -27,5 +27,5 @@
MAJOR 2
MINOR 0
PATCH 0
-PRERELEASE 42
+PRERELEASE 43
PRERELEASE_PATCH 0
diff --git a/tools/dom/dom.json b/tools/dom/dom.json
index e5c2f48..92995fc 100644
--- a/tools/dom/dom.json
+++ b/tools/dom/dom.json
@@ -9925,9 +9925,6 @@
"dart_action": "unstable",
"members": {
"IDBVersionChangeEvent": {},
- "Xyzzy": {
- "support_level": "untriaged"
- },
"dataLoss": {
"support_level": "untriaged"
},
@@ -19156,7 +19153,20 @@
"support_level": "untriaged"
},
"ServiceWorker": {
- "members": {},
+ "members": {
+ "onerror": {
+ "support_level": "untriaged"
+ },
+ "postMessage": {
+ "support_level": "untriaged"
+ },
+ "scriptURL": {
+ "support_level": "untriaged"
+ },
+ "state": {
+ "support_level": "untriaged"
+ }
+ },
"support_level": "untriaged"
},
"ServiceWorkerClient": {
diff --git a/tools/dom/idl/dart/dart.idl b/tools/dom/idl/dart/dart.idl
index b9acad3..0bab867 100644
--- a/tools/dom/idl/dart/dart.idl
+++ b/tools/dom/idl/dart/dart.idl
@@ -381,6 +381,13 @@
[DartSuppress] readonly attribute any dataUnion;
};
+[DartSupplemental,
+ CustomConstructor,
+ Constructor()
+]
+interface MessageChannel {
+};
+
// See https://chromiumcodereview.appspot.com/15901002 for the V8 implementation of
// TextEncoder/TextDecoder
[DartSuppress]
diff --git a/tools/dom/scripts/dartmetadata.py b/tools/dom/scripts/dartmetadata.py
index 230c2dd..3b7ac56 100644
--- a/tools/dom/scripts/dartmetadata.py
+++ b/tools/dom/scripts/dartmetadata.py
@@ -105,11 +105,14 @@
"@Creates('NodeList')",
"@Returns('NodeList')",
],
-
'Element.getBoundingClientRect': [
"@Creates('_DomRect')",
"@Returns('_DomRect|Null')", # TODO(sra): Verify and remove Null.
],
+ 'Element.getClientRects': [
+ "@Creates('DomRectList')",
+ "@Returns('DomRectList|Null')",
+ ],
# Methods returning Window can return a local window, or a cross-frame
# window (=Object) that needs wrapping.
@@ -174,8 +177,8 @@
# TODO(sra): We could determine the following by parsing the compound IDL
# type.
'ExtendableMessageEvent.source': [
- "@Creates('Client|_ServiceWorker|MessagePort')",
- "@Returns('Client|_ServiceWorker|MessagePort|Null')",
+ "@Creates('Client|ServiceWorker|MessagePort')",
+ "@Returns('Client|ServiceWorker|MessagePort|Null')",
],
'File.lastModifiedDate': [
@@ -350,7 +353,7 @@
'ServiceWorkerMessageEvent.source': [
"@Creates('Null')",
- "@Returns('_ServiceWorker|MessagePort')",
+ "@Returns('ServiceWorker|MessagePort')",
],
'ShadowRoot.getElementsByClassName': [
diff --git a/tools/dom/scripts/htmlrenamer.py b/tools/dom/scripts/htmlrenamer.py
index 9033552..6e7b905 100644
--- a/tools/dom/scripts/htmlrenamer.py
+++ b/tools/dom/scripts/htmlrenamer.py
@@ -128,7 +128,6 @@
'RadioNodeList', # Folded onto NodeList in dart2js.
'Rect',
'Response', # TODO: Symbol conflicts with Angular: dartbug.com/20937
- 'ServiceWorker',
'SQLTransactionSync', # Workers
'SQLTransactionSyncCallback', # Workers
'SVGAltGlyphDefElement', # Webkit only.
@@ -429,7 +428,6 @@
'Screen.availLeft',
'Screen.availTop',
'Screen.availWidth',
- 'ServiceWorkerGlobalScope.fetch',
'ShadowRoot.resetStyleInheritance',
'Storage.clear',
'Storage.getItem',
@@ -856,8 +854,6 @@
'MouseEvent.x',
'MouseEvent.y',
'Navigator.bluetooth',
- 'Navigator.registerServiceWorker',
- 'Navigator.unregisterServiceWorker',
'Navigator.isProtocolHandlerRegistered',
'Navigator.unregisterProtocolHandler',
'Navigator.usb',
@@ -886,7 +882,6 @@
'ParentNode.append',
'ParentNode.prepend',
'RTCPeerConnection.generateCertificate',
- 'ServiceWorkerMessageEvent.data',
'ShadowRoot.getElementsByTagNameNS',
'SVGElement.getPresentationAttribute',
'SVGElementInstance.on:wheel',
diff --git a/tools/dom/src/shared_html.dart b/tools/dom/src/shared_html.dart
index 312108e..d9b75ff 100644
--- a/tools/dom/src/shared_html.dart
+++ b/tools/dom/src/shared_html.dart
@@ -19,22 +19,6 @@
}
/**
- * Alias for [querySelector]. Note this function is deprecated because its
- * semantics will be changing in the future.
- */
-@deprecated
-@Experimental()
-Element query(String relativeSelectors) => document.query(relativeSelectors);
-/**
- * Alias for [querySelectorAll]. Note this function is deprecated because its
- * semantics will be changing in the future.
- */
-@deprecated
-@Experimental()
-ElementList<Element> queryAll(String relativeSelectors) =>
- document.queryAll(relativeSelectors);
-
-/**
* Finds the first descendant element of this document that matches the
* specified group of selectors.
*
diff --git a/tools/dom/templates/html/impl/impl_Document.darttemplate b/tools/dom/templates/html/impl/impl_Document.darttemplate
index 6957bd3..a7336fb 100644
--- a/tools/dom/templates/html/impl/impl_Document.darttemplate
+++ b/tools/dom/templates/html/impl/impl_Document.darttemplate
@@ -28,25 +28,6 @@
ElementList<T> querySelectorAll<T extends Element>(String selectors) =>
new _FrozenElementList<T>._wrap(_querySelectorAll(selectors));
- /**
- * Alias for [querySelector]. Note this function is deprecated because its
- * semantics will be changing in the future.
- */
- @deprecated
- @Experimental()
- @DomName('Document.querySelector')
- Element query(String relativeSelectors) => querySelector(relativeSelectors);
-
- /**
- * Alias for [querySelectorAll]. Note this function is deprecated because its
- * semantics will be changing in the future.
- */
- @deprecated
- @Experimental()
- @DomName('Document.querySelectorAll')
- ElementList<T> queryAll<T extends Element>(String relativeSelectors) =>
- querySelectorAll(relativeSelectors);
-
/// Checks if [registerElement] is supported on the current platform.
bool get supportsRegisterElement {
return JS('bool', '("registerElement" in #)', this);
diff --git a/tools/dom/templates/html/impl/impl_DocumentFragment.darttemplate b/tools/dom/templates/html/impl/impl_DocumentFragment.darttemplate
index 7b38a34..2b6bdf6 100644
--- a/tools/dom/templates/html/impl/impl_DocumentFragment.darttemplate
+++ b/tools/dom/templates/html/impl/impl_DocumentFragment.darttemplate
@@ -95,26 +95,5 @@
this.append(new DocumentFragment.html(text, validator: validator,
treeSanitizer: treeSanitizer));
}
-
- /**
- * Alias for [querySelector]. Note this function is deprecated because its
- * semantics will be changing in the future.
- */
- @deprecated
- @Experimental()
- @DomName('DocumentFragment.querySelector')
- Element query(String relativeSelectors) {
- return querySelector(relativeSelectors);
- }
-
- /**
- * Alias for [querySelectorAll]. Note this function is deprecated because its
- * semantics will be changing in the future.
- */
- @deprecated
- @Experimental()
- @DomName('DocumentFragment.querySelectorAll')
- ElementList<T> queryAll<T extends Element>(String relativeSelectors) =>
- querySelectorAll(relativeSelectors);
$!MEMBERS
}
diff --git a/tools/dom/templates/html/impl/impl_Element.darttemplate b/tools/dom/templates/html/impl/impl_Element.darttemplate
index 47d2ce3..c894295 100644
--- a/tools/dom/templates/html/impl/impl_Element.darttemplate
+++ b/tools/dom/templates/html/impl/impl_Element.darttemplate
@@ -603,25 +603,6 @@
new _FrozenElementList<T>._wrap(_querySelectorAll(selectors));
/**
- * Alias for [querySelector]. Note this function is deprecated because its
- * semantics will be changing in the future.
- */
- @deprecated
- @DomName('Element.querySelector')
- @Experimental()
- Element query(String relativeSelectors) => querySelector(relativeSelectors);
-
- /**
- * Alias for [querySelectorAll]. Note this function is deprecated because its
- * semantics will be changing in the future.
- */
- @deprecated
- @DomName('Element.querySelectorAll')
- @Experimental()
- ElementList<T> queryAll<T extends Element>(String relativeSelectors) =>
- querySelectorAll(relativeSelectors);
-
- /**
* The set of CSS classes applied to this element.
*
* This set makes it easy to add, remove or toggle the classes applied to
@@ -784,8 +765,6 @@
@DomName('Element.getClientRects')
@DocsEditable()
- @Returns('DomRectList|Null')
- @Creates('DomRectList')
List<Rectangle> getClientRects() {
var value = _getClientRects();
@@ -855,31 +834,6 @@
*/
void attributeChanged(String name, String oldValue, String newValue) {}
- // Hooks to support custom WebComponents.
-
- @Creates('Null') // Set from Dart code; does not instantiate a native type.
- Element _xtag;
-
- /**
- * Experimental support for [web components][wc]. This field stores a
- * reference to the component implementation. It was inspired by Mozilla's
- * [x-tags][] project. Please note: in the future it may be possible to
- * `extend Element` from your class, in which case this field will be
- * deprecated.
- *
- * If xtag has not been set, it will simply return `this` [Element].
- *
- * [wc]: http://dvcs.w3.org/hg/webcomponents/raw-file/tip/explainer/index.html
- * [x-tags]: http://x-tags.org/
- */
- // Note: return type is `dynamic` for convenience to suppress warnings when
- // members of the component are used. The actual type is a subtype of Element.
- get xtag => _xtag != null ? _xtag : this;
-
- set xtag(Element value) {
- _xtag = value;
- }
-
@DomName('Element.localName')
@DocsEditable()
@Returns('String')
diff --git a/tools/dom/templates/html/impl/impl_HTMLDocument.darttemplate b/tools/dom/templates/html/impl/impl_HTMLDocument.darttemplate
index 1f95dca..6469079 100644
--- a/tools/dom/templates/html/impl/impl_HTMLDocument.darttemplate
+++ b/tools/dom/templates/html/impl/impl_HTMLDocument.darttemplate
@@ -24,48 +24,6 @@
return _elementFromPoint(x, y);
}
- /**
- * Checks if the getCssCanvasContext API is supported on the current platform.
- *
- * See also:
- *
- * * [getCssCanvasContext]
- */
- static bool get supportsCssCanvasContext =>
- JS('bool', '!!(document.getCSSCanvasContext)');
-
-
- /**
- * Gets a CanvasRenderingContext which can be used as the CSS background of an
- * element.
- *
- * CSS:
- *
- * background: -webkit-canvas(backgroundCanvas)
- *
- * Generate the canvas:
- *
- * var context = document.getCssCanvasContext('2d', 'backgroundCanvas',
- * 100, 100);
- * context.fillStyle = 'red';
- * context.fillRect(0, 0, 100, 100);
- *
- * See also:
- *
- * * [supportsCssCanvasContext]
- * * [CanvasElement.getContext]
- */
- @SupportedBrowser(SupportedBrowser.CHROME)
- @SupportedBrowser(SupportedBrowser.SAFARI)
- @Experimental()
- @DomName('Document.getCSSCanvasContext')
- CanvasRenderingContext getCssCanvasContext(String contextId, String name,
- int width, int height) {
- if (HtmlDocument.supportsCssCanvasContext)
- return JS('CanvasRenderingContext', '#.getCSSCanvasContext(#, #, #, #)', this, contextId, name, width, height);
- throw new UnsupportedError("Not supported");
- }
-
@DomName('Document.head')
HeadElement get head => _head;
diff --git a/tools/dom/templates/html/impl/impl_Range.darttemplate b/tools/dom/templates/html/impl/impl_Range.darttemplate
index 64d01a1..c6dba15 100644
--- a/tools/dom/templates/html/impl/impl_Range.darttemplate
+++ b/tools/dom/templates/html/impl/impl_Range.darttemplate
@@ -15,8 +15,6 @@
@DomName('Range.getClientRects')
@DocsEditable()
- @Returns('DomRectList|Null')
- @Creates('DomRectList')
List<Rectangle> getClientRects() {
var value = _getClientRects();
diff --git a/tools/dom/templates/html/impl/impl_ServiceWorker.darttemplate b/tools/dom/templates/html/impl/impl_ServiceWorker.darttemplate
deleted file mode 100644
index 0517910..0000000
--- a/tools/dom/templates/html/impl/impl_ServiceWorker.darttemplate
+++ /dev/null
@@ -1,11 +0,0 @@
-// Copyright (c) 2012, 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.
-
-part of $LIBRARYNAME;
-
-@DocsEditable()
-$(ANNOTATIONS)$(NATIVESPEC)$(CLASS_MODIFIERS)class $CLASSNAME$EXTENDS$IMPLEMENTS {
-$!MEMBERS
-}
-